如何从json获取数据到sqlite,以便应用程序可以脱机工作?

时间:2016-01-20 06:15:36

标签: android json sqlite android-sqlite android-json

我正在研究从json到sqlite存储数据的android应用程序,直到现在我已将数据从json存储到sqlite并在listview中显示(当应用程序有Internet时),现在当我运行我的应用程序时没有互联网,我什么都没得到,我没有得到我做错的事。

MainActivity

    public class MainActivity extends Activity {

    private String[] navMenuTitles;
    private TypedArray navMenuIcons;
    private EditText editTextName;
    SharedPreferences sp;
    private String jsonResult;
    private ListView listView;
    private Button b;
    EditText etname, et;
    TextView tv;
    String myJSON;
    private static final String TAG = "MainActivity.java";
    private static final String TAG_NAME = "notice";
    private CategoryHelper databaseHelper;
    Button get, store, select;

    JSONArray peoples = null;

    ArrayList<HashMap<String, String>> personList;

    ListView list;


    public static final String USER_NAME = "USERNAME";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.noticelist);
        //select = (Button) findViewById(R.id.button3);
        databaseHelper=new CategoryHelper(MainActivity.this);
        databaseHelper.getTimeRecordList();


        //SharedPreferences myprefs= getSharedPreferences("user", MODE_WORLD_READABLE);
        // String session_id= myprefs.getString("session_id", null);


        //TextView textView = (TextView) findViewById(R.id.fname);

        //textView.setText("Welcome "+session_id);


        /*select.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub

                select_seqlite();
            }
        });*/



        // load icons from
        // strings.xml


        list = (ListView) findViewById(R.id.listView);
        personList = new ArrayList<HashMap<String,String>>();

        if (isOnline()) { getData(); }
        else { showList(); }
}

    public boolean isOnline() {
        ConnectivityManager cm =
                (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        return netInfo != null && netInfo.isConnectedOrConnecting();
    }




    protected void showList(){
        try {
            JSONArray peoples = new JSONArray(myJSON);
            for(int i=0;i<peoples.length();i++){
                JSONObject c = peoples.getJSONObject(i);
                String name=null, date=null;

                if(c.has("notice"))
                name = c.getString("notice");

                databaseHelper.saveCategoryRecord(name);
                Cursor c1 = databaseHelper.getTimeRecordList();

                if( c1 != null && c1.moveToFirst())
               do {
                    date = c1.getString(0);
                    }while(c1.moveToNext());

                HashMap<String,String> persons = new HashMap<String,String>();
                persons.put(TAG_NAME,date);
                Log.i("tagconvertstr", "[" + date + "]");
                personList.add(persons);

            }

                    ListAdapter adapter = new SimpleAdapter(
                    MainActivity.this, personList, R.layout.list_item1,
                    new String[]{TAG_NAME},
                    new int[]{R.id.name}


            );

   list.setAdapter(adapter);
           /* list.setAdapter(adapter);*/
        } catch (JSONException e) {
            Log.i("tagconvertstr", "["+myJSON+"]");

        }
    }



    private void DisplayContact(Cursor c) {
        // TODO Auto-generated method stub


        Toast.makeText(getBaseContext(),"name " + c.getString(0), Toast.LENGTH_LONG).show();
    }


    public void getData(){
        class GetDataJSON extends AsyncTask<String, Void, String>{


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

                SharedPreferences myprefs= getSharedPreferences("user", MODE_WORLD_READABLE);
                String session_id= myprefs.getString("session_id", null);

                InputStream inputStream = null;
                String result = null;
                try {

                    String postReceiverUrl = "http://10.0.2.2/progress_card/teacher/teacher_notice.php";

                    // HttpClient
                    HttpClient httpClient = new DefaultHttpClient();

                    // post header
                    HttpPost httpPost = new HttpPost(postReceiverUrl);

                    // add your data
                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                    nameValuePairs.add(new BasicNameValuePair("username", "suyash1"));

                    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                    HttpResponse response = httpClient.execute(httpPost);
                    HttpEntity resEntity = response.getEntity();

                    inputStream = resEntity.getContent();
                    // json is UTF-8 by default
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                    StringBuilder sb = new StringBuilder();

                    String line = null;
                    while ((line = reader.readLine()) != null)
                    {
                        sb.append(line + "\n");
                    }
                    result = sb.toString();
                } catch (Exception e) {
                    Log.i("tagconvertstr", "["+result+"]");
                    System.out.println(e);
                }
                finally {
                    try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
                }
                return result;
            }

            @Override
            protected void onPostExecute(String result){
                myJSON = result;
                showList();
            }
        }
        GetDataJSON g = new GetDataJSON();
        g.execute();
    }
    //get json data stop

}

CategoryHelper.java

public class CategoryHelper {
    private static final int DATABASE_VERSION = 2;
    private static final String DATABASE_NAME = "category.db";
    private static final String TABLE_NAME = "tbcategory";

    public static final String CATEGORY_COLUMN_NAME = "name";
    Category openHelper;
    private SQLiteDatabase database;

    public CategoryHelper(Context context){
        openHelper = new Category(context);
        database = openHelper.getWritableDatabase();
    }
    public void saveCategoryRecord(String name) {
        ContentValues contentValues = new ContentValues();

        contentValues.put(CATEGORY_COLUMN_NAME, name);
        database.insert(TABLE_NAME, null, contentValues);
    }
    public Cursor getTimeRecordList() {
        return database.rawQuery("select * from " + TABLE_NAME, null);
    }
    private class Category extends SQLiteOpenHelper {

        public Category(Context context) {
            // TODO Auto-generated constructor stub
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            // TODO Auto-generated method stub
            db.execSQL("CREATE TABLE " + TABLE_NAME + "( "
                    +  CATEGORY_COLUMN_NAME + " TEXT )" );

        }

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

    }
}

2 个答案:

答案 0 :(得分:0)

添加

SearchView

而不是getData():

public boolean isOnline() {
    ConnectivityManager cm =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    return netInfo != null && netInfo.isConnectedOrConnecting();
}

您需要保存myList,因此下次打开应用程序时,它会在本地保存:

myJSON = loadResults();
if (isOnline()) { getData(); }
else if (myJSON != null) { showList(); }
else { Toast.makeText(getContext(), "no data available to show", Toast.LENGTH_SHORT).show(); }

答案 1 :(得分:0)

在单独的函数中输入以下代码,例如loadData()

 public void loadData() {
    Cursor c1 = databaseHelper.getTimeRecordList();
    //Code to iterate c1 cursor.
    //Create Adapter with data from c1 cursor
    //Add adapter to list.
}

 public boolean isOnline() {
    ConnectivityManager cm =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    return netInfo != null && netInfo.isConnectedOrConnecting();
}

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.noticelist);
    //select = (Button) findViewById(R.id.button3);
    databaseHelper=new CategoryHelper(MainActivity.this);
    databaseHelper.getTimeRecordList(); //remove this line as your not catching cursor in any variable.
    ...
    list = (ListView) findViewById(R.id.listView);
    personList = new ArrayList<HashMap<String,String>>();

    if (isOnline()) { getData(); }
    else { loadData(); }
}