Why i can not save the json object into the json array?

前端 未结 2 1974
春和景丽
春和景丽 2021-01-29 08:53

I\'m beginner in android,write simple application to send json array to server,write this code:

JSONArray jsonArray = new JSONArray();
            JSONObjec         


        
2条回答
  •  情深已故
    2021-01-29 09:30

    It is only storing the last record because you are not creating a new JSONObject in your do...while loop. See my edited code.

    JSONArray jsonArray = new JSONArray();
            JSONObject obj = new JSONObject();
            String DATABASE_NAME = "TEMPFOOD";
            String TABLE_NAME = "tempData";
            try{
                SQLiteDatabase mydb = openOrCreateDatabase(DATABASE_NAME, TempActivity.MODE_PRIVATE,null);
                Cursor allrows  = mydb.rawQuery("SELECT * FROM "+  TABLE_NAME, null);
                if(allrows.moveToFirst()){
                    do{
                        obj = new JSONObject();
                        String Food_Name = allrows.getString(0);
                        String Value = allrows.getString(1);
                        String NOBAT = allrows.getString(2);
                        String TIME = allrows.getString(3);
                        String DATE = allrows.getString(4);
                        try {
                            obj.put("Food_Name", Food_Name)
                                    .put("Value", Value)
                                    .put("NOBAT", NOBAT)
                                    .put("TIME", TIME)
                                    .put("DATE", DATE);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        jsonArray.put(obj);
                    }
                    while(allrows.moveToNext());
                }
                mydb.close();
            }catch(Exception e){
                //Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG).show();
            }
            String jsonText = jsonArray.toString();
    

提交回复
热议问题