Search code examples
androidxmldatabaseparsingrss

How to save parsed rss to database in Android


Beginner here!

So I need help with saving parsed RSS feed into database to view later offline.

I am parsing RSS with SAXParser and then displaying it in ListView. I have managed to make working database, but I have no clue how to add parsed strings to the database. Should I to it right after parsing or after displaying ListView or something else?

My project is based on http://www.itcuties.com/android/how-to-write-android-rss-parser/ RSS parser example.

Example code would be greatly appreciated.

Thank you in advance!

EDIT: My main activity AsyncTask:

private class GetRSSDataTask extends AsyncTask<String, Void, List<RssItem> > {
    @Override
    protected List<RssItem> doInBackground(String... urls) {


        try {
            // Create RSS reader
            RssReader rssReader = new RssReader(urls[0]);

            // Parse RSS, get items
            return rssReader.getItems();

        } catch (Exception e) {
            Log.e("RssParser", e.getMessage());
        }


        return null;
    }

    @Override
    protected void onPostExecute(List<RssItem> result) {


        RssItem item = new RssItem();

        db.open();
        //do something by database
        db.insertNewsInfo(item);
        Log.i("String", item.toString());
        db.close();


        // Get a ListView from main view
        ListView itcItems = (ListView) findViewById(R.id.listView);

        // Create a list adapter
        ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(local,android.R.layout.simple_list_item_1, result);
        // Set list adapter for the ListView
        itcItems.setAdapter(adapter);

        // Set list view item click listener
        itcItems.setOnItemClickListener(new ListListener(result, local));


    }
}

Solution

  • For Example: To parse a news website, you can make a class NewsInformation.java

    public class NewsInformation {
        public String completeTextLink;
        public String title;
        public String writerName;
        public String dateWriten;
        public String source;
        public String smallBody;
        public String bigBody;  
        public String page;
    }
    

    And by using the above class, insert your news to database

    DatabaseHelper.java

    public class DatabaseHelper extends SQLiteOpenHelper {
    
        private final String TAG = "DatabaseHelper";
        private static final String DATABASE_NAME = "db_for_news";
    
        public DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, 10);
        
            //fdd
            Log.i(TAG, "Object created.");
        }
    
        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE news ( page TEXT ," +
                " completeTextLink TEXT  ,title TEXT , writerName TEXT , dateWriten TEXT ," +
                " source TEXT ,  smallBody TEXT , bigBody TEXT);");
        }
    
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(DatabaseHelper.class.getName(), "Upgrading database from version "
                + oldVersion + " to " + newVersion + ", which will destroy all old data");
            db.execSQL("Drop table if exists news" );   
            onCreate(db);
        }
    }
    

    DatabaseHandler.java

    public class DatabaseHandler {
    
        private DatabaseHelper dbHelper;
        private SQLiteDatabase database;
    
        
        public DatabaseHandler(Context context) {
            dbHelper = new DatabaseHelper(context);
        }
    
        //methods for all table
        public void open() throws SQLException {
            database = dbHelper.getWritableDatabase();
        }
    
        public void close() {
            dbHelper.close();
        }
    
        public void clearTable(String tableName) {
            database.delete( tableName, null, null);
        }
    
        //news table method
    
        public void insertNewsInfo(NewsInformation newsInfo) {
            ContentValues cv = new ContentValues();
            cv.put("bigBody"          ,  newsInfo.bigBody );
            cv.put("completeTextLink" ,  newsInfo.completeTextLink );
            cv.put("dateWriten"       ,  newsInfo.dateWriten );
            cv.put("source"            ,  newsInfo.source );
            cv.put("smallBody"        ,  newsInfo.smallBody );
            cv.put("title"            ,  newsInfo.title );
            cv.put("writerName"       ,  newsInfo.writerName );
            cv.put("page"             ,  newsInfo.page );
        
            database.insert("news" , "writerName", cv);
        }
    
    
        public List<NewsInformation> getAllNewsForPage(String page) {   
            List<NewsInformation> NewsInfoList = new ArrayList<NewsInformation>();
         
            Cursor cursor = database.rawQuery("select completeTextLink " +
                " , title , writerName , dateWriten , source , smallBody , bigBody" +
                " FROM news where page = ?", new String[]{page});
        
    
            cursor.moveToFirst();
            while (!cursor.isAfterLast()) {
                NewsInformation newsInfo = new NewsInformation();
            
                newsInfo.completeTextLink = cursor.getString(0);
                newsInfo.title = cursor.getString(1);
                newsInfo.writerName = cursor.getString(2);
                newsInfo.dateWriten = cursor.getString(3);
                newsInfo.source = cursor.getString(4);
                newsInfo.smallBody = cursor.getString(5);
                newsInfo.bigBody = cursor.getString(6);
                newsInfo.page = page;
                    
                NewsInfoList.add(newsInfo);
                cursor.moveToNext();
            }
        
            // Make sure to close the cursor
            cursor.close();
        
            return NewsInfoList;
        }
    
        public String getBigBody(String completeBodyLink) {
            Cursor cursor = database.rawQuery("select bigBody FROM news where completeTextLink = ?", new String[]{completeBodyLink});
            cursor.moveToFirst();
            String bigBody = cursor.getString(0);
            cursor.close();
            return bigBody;
        }       
    }
    

    In your Activity to save news to DataBase

    In DATA >> private NewsDatabaseHandler    db;
    In onCreate() >> db = new NewsDatabaseHandler(this);
    
    // Where you want insert to database or read from it
    db.open();
    
    // do something by database
    // for Example:
    NewsInformation item = new NewsInformation();
    item.completeTextLink = "Your Link of news";
    item.title            = "title of news";
    item.writerName       = "writer of news";
    item.dataWriten       = "1999";
    item.source           = "something";
    item.smallBody        = "news body";
    item.bigBody          = "news text";
    item.page             = "1";
    db.insertNewsInfo(item);
    db.close();