【问题标题】:how to make listview from JSON -> Sqlite?如何从 JSON -> Sqlite 制作列表视图?
【发布时间】:2016-04-21 21:19:10
【问题描述】:

我正在一个 android 应用程序中工作,其中数据以 json 的形式存在,来自 json 的数据保存在 Sqlite 中。直到现在我已经将 json 保存到 sqlite 但是当我试图在 listview 中获取数据时,应用程序崩溃了

主活动

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

    getData();




}

//发送消息停止

//get json data start
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()) {
                date = c1.getString(c1.getColumnIndexOrThrow("name"));

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

        }




           /*ListAdapter adapter = new SimpleAdapter(
                   Messages.this, personList, R.layout.list_item,
                   new String[]{TAG_NAME,TAG_ADD},
                   new int[]{R.id.name, R.id.address}
           );*/


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


        );

// http://www.vogella.com/tutorials/AndroidListView/article.html // 列表视图的自定义适配器

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

    }
}

private void select_seqlite() {
    // TODO Auto-generated method stub

    databaseHelper.getTimeRecordList();

    Cursor c = databaseHelper.getTimeRecordList();
    if (c.moveToFirst())
    {
        do {
            DisplayContact(c);
        } while (c.moveToNext());
    }


}

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

//获取json数据停止 }

CategoryHelper (Sqlite)

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

    }
}

Logcat

01-16 15:04:21.735  29380-29380/org.pitechnologies.jsontosqlite E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: org.pitechnologies.jsontosqlite, PID: 29380
android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
        at android.database.AbstractCursor.checkPosition(AbstractCursor.java:426)
        at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
        at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
        at org.pitechnologies.jsontosqlite.MainActivity.showList(MainActivity.java:131)
        at org.pitechnologies.jsontosqlite.MainActivity$1GetDataJSON.onPostExecute(MainActivity.java:249)
        at org.pitechnologies.jsontosqlite.MainActivity$1GetDataJSON.onPostExecute(MainActivity.java:196)
        at android.os.AsyncTask.finish(AsyncTask.java:636)
        at android.os.AsyncTask.access$500(AsyncTask.java:177)
        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5257)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

【问题讨论】:

  • 我解决了空指针异常问题,但现在我得到了另一个,我已经更新了我的 logcat

标签: android json sqlite listview


【解决方案1】:

关于这个错误:

Index -1 requested, with a size of 1

检查这一行的光标,

Cursor c1 = databaseHelper.getTimeRecordList();

                HashMap<String,String> persons = new HashMap<String,String>();
                persons.put(TAG_NAME,c1.getString(0));
                personList.add(persons);

你应该在打电话之前移到下一个

c1.getString(0)

【讨论】:

  • 感谢它现在工作,但数据在列表视图中重复。
  • 你能更新你的新代码吗,通常这可能是因为你添加了相同的项目,这意味着你没有为每个列表视图项目声明新对象。
【解决方案2】:

将此方法调用从 onCreate 移至 getData() 的 onPostExecute()。还有一个建议,请删除这意味着您使用两个地方的行数更少。

 databaseHelper.getTimeRecordList();

删除

      onCreate()
    //showList();

然后穿上

         @Override
        protected void onPostExecute(String result){
            myJSON = result;
            showList();
        }

并尝试在使用后关闭数据库,否则数据库会给您一个数据库泄漏问题。比如创建两个方法。

       void open() {
         database = openHelper.getWritableDatabase();
       }

       void close() {
          database.close();
       }

然后像这样调用这个方法

        public void saveCategoryRecord(String name) {
             ContentValues contentValues = new ContentValues();
             contentValues.put(CATEGORY_COLUMN_NAME, name);
             open();
             database.insert(TABLE_NAME, null, contentValues);
             close();
         }

         public Cursor getTimeRecordList() {
             open();
             Cursor c = database.rawQuery("select * from " + TABLE_NAME, null);
             close();
             return c;
            }

并从构造函数中删除这一行。

 database = openHelper.getWritableDatabase();

希望这对你有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多