1

I am sending my Server side JSON data into database,after that i am display in an listview. But while changing in an server side or my json data will increase, it will not reflect or change in my db,Actually after changing my JSON, i want my db also update like Old+new. It has to save the new one also in db while any data add in server side also.

This my JSON part:

{
  "post": [
    {
      "id": 249,
      "title": "Career",
      "content": "Last ten days ,work is not going well",
      "count": 0
    },
    {
      "id": 248,
      "title": "Career",
      "content": "Last ten days ,work is not going well",
      "count": 0
    },
]
}

This JSON value has to store in db,if next time in website some thing will add,my json will also increase,My db also wants to add that data,Rightnow is not adding that data,only one time its fetching and displaying.

This is my Mainactivity.java

@Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_item); 

        mDbHelper=new GinfyDbAdapter(MainActivity.this);
        mDbHelper.open();
         Cursor projectsCursor = mDbHelper.fetchAllProjects();
         if(projectsCursor.getCount()>0)
           {
           fillData(projectsCursor);

           Log.i("filling", "...");
           }
           else
           {
                new GetDataAsyncTask().execute();
           }



        btnGetSelected = (Button) findViewById(R.id.btnget);
        btnGetSelected.setOnClickListener(this);

    }

    private class GetDataAsyncTask extends AsyncTask<Void, Void, Void> {
        private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);

        protected void onPreExecute() {
            Dialog.setMessage("Loading.....");
            Dialog.show();
        }
        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            Dialog.dismiss();
            mDbHelper=new GinfyDbAdapter(MainActivity.this); // initialize mDbHelper before.
            mDbHelper.open();
            Cursor projectsCursor = mDbHelper.fetchAllProjects();
            if(projectsCursor.getCount()>0)
            {
            fillData(projectsCursor);
            }
        }

        @Override
        protected Void doInBackground(Void... params) {
            getData();
            return null;
        }
    }

    public void getData() {
          try
          {
      HttpClient httpclient = new DefaultHttpClient();
      httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
      HttpGet request = new HttpGet("http://192.168.1.18:3001/api/v1/posts.json");
      // HttpGet request = new HttpGet("http://gdata.youtube.com/feeds/api/users/mbbangalore/uploads?v=2&alt=jsonc");     

      HttpResponse response = httpclient.execute(request);
      HttpEntity resEntity = response.getEntity();
      String _response=EntityUtils.toString(resEntity); // content will be consume only once
       Log.i("................",_response);
      httpclient.getConnectionManager().shutdown();
      JSONObject jsonObject = new JSONObject(_response);
      JSONArray contacts = jsonObject.getJSONArray("post");//(url);
          for(int i = 0; i < contacts.length(); i++){
              JSONObject c = contacts.getJSONObject(i);
              String id = c.getString("id");
              String title = c.getString("title");
              String  content = c.getString("content");
              String  count = c.getString("count");
              mDbHelper=new GinfyDbAdapter(MainActivity.this);
              mDbHelper.open();
              mDbHelper.saveCategoryRecord(new Category(id,title,content,count));
      }
  } catch (Exception e) {
      e.printStackTrace();
  }
    }

    @SuppressLint("NewApi")
     @SuppressWarnings("deprecation")
       private void fillData(Cursor projectsCursor) {
           //mDbHelper.open();   

           if(projectsCursor!=null)
           {
           String[] from = new String[]{GinfyDbAdapter.CATEGORY_COLUMN_TITLE, GinfyDbAdapter.CATEGORY_COLUMN_CONTENT, GinfyDbAdapter.CATEGORY_COLUMN_COUNT};
           int[] to = new int[]{R.id.text2, R.id.text1, R.id.count};
            dataAdapter  = new SimpleCursorAdapter(
             this, R.layout.activity_row, 
             projectsCursor, 
             from, 
             to,
             0);
            setListAdapter(dataAdapter);
           }else
           {
               Log.i("...........","null");
           }
       }

Here i mention my dpclass also.

private static final String DATABASE_NAME = "test";
    private static final String DATABASE_TABLE_PROJ = "projects";
    private static final int DATABASE_VERSION = 3;
    public static final String CATEGORY_COLUMN_ID = "_id";
    public static final String CATEGORY_COLUMN_TITLE = "title";
    public static final String CATEGORY_COLUMN_CONTENT = "content";
    public static final String CATEGORY_COLUMN_COUNT = "count";


    private static final String TAG = "GinfyDbAdapter";
    private DatabaseHelper mDbHelper;
    private static SQLiteDatabase mDb;
    private final Context mCtx;





    public void saveCategoryRecord(String id, String title, String content, String count) {
        ContentValues contentValues = new ContentValues();
        contentValues.put(CATEGORY_COLUMN_ID, id);
        contentValues.put(CATEGORY_COLUMN_TITLE, title);
        contentValues.put(CATEGORY_COLUMN_CONTENT, content);
        contentValues.put(CATEGORY_COLUMN_COUNT, count);
        mDb.insert(DATABASE_NAME, null, contentValues);
        }
    public Cursor getTimeRecordList() {
        return mDb.rawQuery("select * from " + DATABASE_NAME, null);
        }
    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }



        private static final String DATABASE_CREATE_PROJ =
                "create table " + DATABASE_TABLE_PROJ + " ("
                + CATEGORY_COLUMN_ID + " integer primary key , "
                + CATEGORY_COLUMN_TITLE + " text not null, " + CATEGORY_COLUMN_CONTENT + " text not null, " + CATEGORY_COLUMN_COUNT + " integer );" ;

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        String DATABASE_CREATE_PROJ = "CREATE TABLE " +  DATABASE_TABLE_PROJ + "( "
                + CATEGORY_COLUMN_ID + " integer primary key, "
                + CATEGORY_COLUMN_TITLE + " text not null, " + CATEGORY_COLUMN_CONTENT + " text not null, " + CATEGORY_COLUMN_COUNT + " integer   );" ;
                db.execSQL(DATABASE_CREATE_PROJ);     
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
        db.execSQL("DROP TABLE IF EXISTS"+ DATABASE_TABLE_PROJ);
        onCreate(db);
    }


}

    public void saveCategoryRecord(Category category) {

         ContentValues values = new ContentValues();
         values.put(CATEGORY_COLUMN_TITLE , category.getTitle());
         values.put(CATEGORY_COLUMN_CONTENT, category.getContent()); 
         values.put(CATEGORY_COLUMN_COUNT, category.getCount());   
         // Inserting Row
         mDb.insert(DATABASE_TABLE_PROJ, null, values);
         mDb.close(); // Closing database connection
    }

    public Cursor fetchAllProjects() {
        // TODO Auto-generated method stub
        return mDb.query(DATABASE_TABLE_PROJ, new String[] {CATEGORY_COLUMN_ID, CATEGORY_COLUMN_TITLE, CATEGORY_COLUMN_CONTENT, CATEGORY_COLUMN_COUNT }, null, null, null, null, null);
    }

    public GinfyDbAdapter(Context ctx) {
        this.mCtx = ctx;

    }

     public GinfyDbAdapter open() throws SQLException {
            mDbHelper = new DatabaseHelper(mCtx);
            mDb = mDbHelper.getWritableDatabase();
            return this;
        }

     public boolean updateProject(long _id, String title, String content, String count) {
            ContentValues args = new ContentValues();
            args.put(CATEGORY_COLUMN_TITLE, title );
            args.put(CATEGORY_COLUMN_CONTENT, content );
            args.put(CATEGORY_COLUMN_COUNT, count );
            return mDb.update(DATABASE_TABLE_PROJ, args, CATEGORY_COLUMN_ID + "=" + _id,  null) > 0;
        }


}

My problem is:For first time it fetches my JSON data and save in db,next time while launching its not getting newly added part of json data,I want that old and new JSON data should be store in db.

Bhavin Nattar
  • 3,189
  • 2
  • 22
  • 30
Karthick M
  • 769
  • 2
  • 11
  • 29

2 Answers2

3

please use insert or replase raw query instead this look this.

SQLite "INSERT OR REPLACE INTO" vs. "UPDATE ... WHERE"

String query = INSERT OR REPLACE INTO DATABASE_TABLE_PROJ (CATEGORY_COLUMN_ID,CATEGORY_COLUMN_TITLE,CATEGORY_COLUMN_CONTENT,CATEGORY_COLUMN_COUNT) VALUES ('1', 'Muhammad','xyz','2'); db.execSQL(query);

Community
  • 1
  • 1
Sandeep Tiwari
  • 2,042
  • 3
  • 24
  • 47
  • @KarthickM dear please use this in saveCategoryRecord() method means insert data by using raw query not by content value – Sandeep Tiwari Jul 10 '13 at 12:32
  • public void saveCategoryRecord(String id, String title, String content, String count) { ContentValues contentValues = new ContentValues(); contentValues.put(CATEGORY_COLUMN_ID, id); contentValues.put(CATEGORY_COLUMN_TITLE, title); contentValues.put(CATEGORY_COLUMN_CONTENT, content); contentValues.put(CATEGORY_COLUMN_COUNT, count); mDb.insert(DATABASE_NAME, null, contentValues); } – Karthick M Jul 10 '13 at 12:33
  • INSERT OR REPLACE into tablename (fields) values(); db.executesql(); not sure method name but this will help you. – Sandeep Tiwari Jul 10 '13 at 12:37
  • sandeep if you dont mind edit my code and tell,what i want to write and where i want to write the insert or replace.kindly help ,edit your code and give answer dude – Karthick M Jul 10 '13 at 12:39
0
public class Mainactivity extends Activity{
ArrayList<String> ID = new ArrayList<String>();
ArrayList<String> TITLE= new ArrayList<String>();
ArrayList<String> CONTENT= new ArrayList<String>();
ArrayList<String> COUNT= new ArrayList<String>();

protected onCreate(Bundle savedInastanceState){


}

public void getData() {
         //your json code
      JSONArray contacts = jsonObject.getJSONArray("post");//(url);
          for(int i = 0; i < contacts.length(); i++){
              JSONObject c = contacts.getJSONObject(i);
              String id = c.getString("id");
              String title = c.getString("title");
              String  content = c.getString("content");
              String  count = c.getString("count");
             ID.add(id);
             TITLE.add(title);
             CONTENT.add(content);
             COUNT.add(count);
      }
  } catch (Exception e) {
      e.printStackTrace();
  }
    }


}
private class GetDataAsyncTask extends AsyncTask<Void, Void, Void> {
        private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);

        protected void onPreExecute() {
            //
        }
        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            Dialog.dismiss();
            //
        }

        @Override
        protected Void doInBackground(Void... params) {

            getData();
            return null;
        }
      @Override
      protected void onPostExecute(Void result) {

             for(int i=0; i<ID.size(); i++){
             mDbHelper=new GinfyDbAdapter(MainActivity.this);
              mDbHelper.open();
              mDbHelper.saveCategoryRecord(new Category(ID.get(i),TITLE.get(i),CONTENT.get(i),COUNTER.get(i)));
              }
    }
TheLittleNaruto
  • 8,325
  • 4
  • 54
  • 73