如何更新数据库,而在我们的服务器端更改 [英] How to update the database,while changing in our server side

查看:358
本文介绍了如何更新数据库,而在我们的服务器端更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我送我的服务器端 JSON数据到数据库中,在那之后,我在一个列表视图显示。但同时改变在服务器端或我的JSON数据将增加,这将不会反映或我的数据库发生变化,改变了我的JSON后其实,我想我也分贝像更新老+新。它也保存在数据库中新的,而任何数据在服务器端还添加了。

这是我的JSON部分:

  {
  邮报:
    {
      ID:249,
      头衔:职业
      内容:最后十几天,工作不顺利,
      伯爵:0
    },
    {
      ID:248,
      头衔:职业
      内容:最后十几天,工作不顺利,
      伯爵:0
    },
]
}

此JSON值在DB存储,如果在网站下一次有些东西会增加,我的JSON也将增加,我的数据库也想补充一点资料,RightNow公司不能添加的数据,仅一次它的抓取和显示。

这是我的Mainactivity.java

  @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_list_item);        mDbHelper =新GinfyDbAdapter(MainActivity.this);
        mDbHelper.open();
         光标projectsCursor = mDbHelper.fetchAllProjects();
         如果(projectsCursor.getCount()大于0)
           {
           fillData(projectsCursor);           Log.i(填充,......);
           }
           其他
           {
                新GetDataAsyncTask()执行();
           }        btnGetSelected =(按钮)findViewById(R.id.btnget);
        btnGetSelected.setOnClickListener(本);    }    私有类GetDataAsyncTask扩展的AsyncTask<太虚,太虚,太虚> {
        私人ProgressDialog对话=新ProgressDialog(MainActivity.this);        在preExecute保护无效(){
            Dialog.setMessage(加载.....);
            Dialog.show();
        }
        @覆盖
        保护无效onPostExecute(虚空结果){
            super.onPostExecute(结果);
            Dialog.dismiss();
            mDbHelper =新GinfyDbAdapter(MainActivity.this); //初始化之前mDbHelper。
            mDbHelper.open();
            光标projectsCursor = mDbHelper.fetchAllProjects();
            如果(projectsCursor.getCount()大于0)
            {
            fillData(projectsCursor);
            }
        }        @覆盖
        保护无效doInBackground(虚空...... PARAMS){
            的getData();
            返回null;
        }
    }    公共无效的getData(){
          尝试
          {
      HttpClient的HttpClient的=新DefaultHttpClient();
      httpclient.getParams()的setParameter(CoreProtocolPNames.PROTOCOL_VERSION,HttpVersion.HTTP_1_1)。
      HTTPGET请求=新HTTPGET(http://192.168.1.18:3001/api/v1/posts.json);
      // HTTPGET请求=新HTTPGET(http://gdata.youtube.com/feeds/api/users/mbbangalore/uploads?v=2&alt=jsonc);      HTT presponse响应= httpclient.execute(请求);
      HttpEntity resEntity = response.getEntity();
      字符串_response = EntityUtils.toString(resEntity); //内容将只消费一次,
       Log.i(.....................,_响应);
      。httpclient.getConnectionManager()关机();
      的JSONObject的JSONObject =新的JSONObject(_response);
      JSONArray接触= jsonObject.getJSONArray(后); //(URL);
          的for(int i = 0; I< contacts.length();我++){
              JSONObject的C = contacts.getJSONObject(I)
              字符串ID = c.getString(ID);
              字符串title = c.getString(标题);
              字符串内容= c.getString(内容);
              字符串计数= c.getString(计数);
              mDbHelper =新GinfyDbAdapter(MainActivity.this);
              mDbHelper.open();
              mDbHelper.saveCategoryRecord(新类别(ID,标题,内容,数量));
      }
  }赶上(例外五){
      e.printStackTrace();
  }
    }    @燮pressLint(NewApi)
     @燮pressWarnings(德precation)
       私人无效fillData(光标projectsCursor){
           //mDbHelper.open();           如果(projectsCursor!= NULL)
           {
           的String [] =由新的String [] {GinfyDbAdapter.CATEGORY_COLUMN_TITLE,GinfyDbAdapter.CATEGORY_COLUMN_CONTENT,GinfyDbAdapter.CATEGORY_COLUMN_COUNT};
           INT []为= INT新[] {R.id.text2,R.id.text1,R.id.count};
            DataAdapter的=新SimpleCursorAdapter(
             对此,R.layout.activity_row,
             projectsCursor,
             从,
             至,
             0);
            setListAdapter(DataAdapter的);
           }其他
           {
               Log.i(...........,空);
           }
       }

在这里,我提我dpclass也。

 私有静态最后弦乐DATABASE_NAME =测试;
    私有静态最后弦乐DATABASE_TABLE_PROJ =工程;
    私有静态最终诠释DATABASE_VERSION = 3;
    公共静态最后弦乐CATEGORY_COLUMN_ID =_id;
    公共静态最后弦乐CATEGORY_COLUMN_TITLE =称号;
    公共静态最后弦乐CATEGORY_COLUMN_CONTENT =内容;
    公共静态最后弦乐CATEGORY_COLUMN_COUNT =伯爵;
    私有静态最后弦乐TAG =GinfyDbAdapter;
    私人DatabaseHelper mDbHelper;
    私有静态SQLiteDatabase MDB;
    私人最终上下文mCtx;    公共无效saveCategoryRecord(ID字符串,字符串title,字符串内容,字符串计数){
        ContentValues​​ contentValues​​ =新ContentValues​​();
        contentValues​​.put(CATEGORY_COLUMN_ID,身份证);
        contentValues​​.put(CATEGORY_COLUMN_TITLE,职称);
        contentValues​​.put(CATEGORY_COLUMN_CONTENT,内容);
        contentValues​​.put(CATEGORY_COLUMN_COUNT,计数);
        mDb.insert(DATABASE_NAME,空,contentValues​​);
        }
    公共光标getTimeRecordList(){
        返回mDb.rawQuery(SELECT * FROM+ DATABASE_NAME,NULL);
        }
    私有静态类DatabaseHelper扩展SQLiteOpenHelper {        DatabaseHelper(上下文的背景下){
            超(背景下,DATABASE_NAME,空,DATABASE_VERSION);
        }        私有静态最后弦乐DATABASE_CREATE_PROJ =
                CREATE TABLE+ DATABASE_TABLE_PROJ +(
                + CATEGORY_COLUMN_ID +整数主键
                + CATEGORY_COLUMN_TITLE +文本不为空,+ CATEGORY_COLUMN_CONTENT +文本不为空,+ CATEGORY_COLUMN_COUNT +整数); ;    @覆盖
    公共无效的onCreate(SQLiteDatabase DB){
        // TODO自动生成方法存根
        字符串DATABASE_CREATE_PROJ =CREATE TABLE+ DATABASE_TABLE_PROJ +(
                + CATEGORY_COLUMN_ID +整数主键
                + CATEGORY_COLUMN_TITLE +文本不为空,+ CATEGORY_COLUMN_CONTENT +文本不为空,+ CATEGORY_COLUMN_COUNT +整数); ;
                db.execSQL(DATABASE_CREATE_PROJ);
    }    @覆盖
    公共无效onUpgrade(SQLiteDatabase分贝,INT oldVersion,诠释静态网页){
        // TODO自动生成方法存根
        db.execSQL(DROP TABLE IF EXISTS+ DATABASE_TABLE_PROJ);
        的onCreate(DB);
    }
}    公共无效saveCategoryRecord(分类类别){         ContentValues​​值=新ContentValues​​();
         values​​.put(CATEGORY_COLUMN_TITLE,category.getTitle());
         values​​.put(CATEGORY_COLUMN_CONTENT,category.getContent());
         values​​.put(CATEGORY_COLUMN_COUNT,category.getCount());
         //插入行
         mDb.insert(DATABASE_TABLE_PROJ,空,价值);
         mDb.close(); //关闭数据库连接
    }    公共光标fetchAllProjects(){
        // TODO自动生成方法存根
        返回mDb.query(DATABASE_TABLE_PROJ,新的String [] {CATEGORY_COLUMN_ID,CATEGORY_COLUMN_TITLE,CATEGORY_COLUMN_CONTENT,CATEGORY_COLUMN_COUNT},NULL,NULL,NULL,NULL,NULL);
    }    公共GinfyDbAdapter(上下文CTX){
        this.mCtx = CTX;    }     公共GinfyDbAdapter的open()抛出的SQLException {
            mDbHelper =新DatabaseHelper(mCtx);
            MDB = mDbHelper.getWritableDatabase();
            返回此;
        }     公共布尔updateProject(长_id,标题字符串,字符串的内容,串计数){
            ContentValues​​ ARGS =新ContentValues​​();
            args.put(CATEGORY_COLUMN_TITLE,职称);
            args.put(CATEGORY_COLUMN_CONTENT,内容);
            args.put(CATEGORY_COLUMN_COUNT,计数);
            返回mDb.update(DATABASE_TABLE_PROJ,ARGS,CATEGORY_COLUMN_ID +=+ _id,NULL)> 0;
        }
}

我的问题是:对于第一次取我的JSON数据并保存在数据库,接下来的时间,同时推出其没有得到新添加的JSON数据的一部分,我希望新老JSON数据应该在数据库存储


解决方案

 公共类Mainactivity延伸活动{
ArrayList的<串GT; ID =新的ArrayList<串GT;();
ArrayList的<串GT; TITLE =新的ArrayList<串GT;();
ArrayList的<串GT; CONTENT =新的ArrayList<串GT;();
ArrayList的<串GT; COUNT =新的ArrayList<串GT;();受保护的onCreate(捆绑savedInastanceState){
}公共无效的getData(){
         //你的JSON code
      JSONArray接触= jsonObject.getJSONArray(后); //(URL);
          的for(int i = 0; I< contacts.length();我++){
              JSONObject的C = contacts.getJSONObject(I)
              字符串ID = c.getString(ID);
              字符串title = c.getString(标题);
              字符串内容= c.getString(内容);
              字符串计数= c.getString(计数);
             ID.add(ID);
             TITLE.add(职称);
             CONTENT.add(内容);
             COUNT.add(计数);
      }
  }赶上(例外五){
      e.printStackTrace();
  }
    }
}
私有类GetDataAsyncTask扩展的AsyncTask<太虚,太虚,太虚> {
        私人ProgressDialog对话=新ProgressDialog(MainActivity.this);        在preExecute保护无效(){
            //
        }
        @覆盖
        保护无效onPostExecute(虚空结果){
            super.onPostExecute(结果);
            Dialog.dismiss();
            //
        }        @覆盖
        保护无效doInBackground(虚空...... PARAMS){            的getData();
            返回null;
        }
      @覆盖
      保护无效onPostExecute(虚空结果){             的for(int i = 0; I< ID.size();我++){
             mDbHelper =新GinfyDbAdapter(MainActivity.this);
              mDbHelper.open();
              mDbHelper.saveCategoryRecord(新类别(ID.get(ⅰ),TITLE.get(ⅰ),CONTENT.get(ⅰ),COUNTER.get(ⅰ)));
              }
    }

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.

解决方案

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)));
              }
    }

这篇关于如何更新数据库,而在我们的服务器端更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆