从SQLite获取JSON数据并填充到ListView中

时间:2014-04-18 05:58:04

标签: java android json sqlite listview

我编写了一个程序,我在其中解析JSON,然后将JSON数据存储到SQLite中,但在这里我需要您的指导,使用SQLite将数据显示到List中。

现在每当我关闭Internet连接都不会将数据放入列表中时,请告诉我在DatabaseHelper类中需要使用哪些代码来获取所有记录以及需要在MainActivity中应用哪些更改以将代码显示到的ListView。

请参阅下面的代码,我将其用于将数据存储到数据库中, DatabaseHelper.java : -

public class DatabaseHelper extends SQLiteOpenHelper {

    // Database Version
    private static final int DATABASE_VERSION = 2;
    // Database Name
    private static final String DATABASE_NAME = "storeJSON";
    // Table Name
    private static final String TABLE_MEMBER = "churchResults";

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

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        // Create Table Name
        db.execSQL("CREATE TABLE " + TABLE_MEMBER + 
                  "(Id VARCHAR(100)," +
                  " Title VARCHAR(100));");

        Log.d("CREATE TABLE","Create Table Successfully");
    }

    // Insert Data
    public long InsertData(String strId, String strTitle) {
        // TODO Auto-generated method stub

         try {
            SQLiteDatabase db;
            db = this.getWritableDatabase(); // Write Data

            ContentValues Val = new ContentValues();
            Val.put("Id", strId); 
            Val.put("Title", strTitle);

            long rows = db.insert(TABLE_MEMBER, null, Val);

            db.close();
            return rows; // return rows inserted.

         } catch (Exception e) {
            return -1;
         }
    }

    // Update Data
    public long UpdateData(String strId, String strTitle){
    // TODO Auto-generated method stub

        try {
            SQLiteDatabase db;
            db = this.getWritableDatabase(); // Write Data

            ContentValues Val = new ContentValues();
            Val.put("Id", strId);
            Val.put("Title", strTitle);

            long rows = db.update(TABLE_MEMBER, Val, "Id=?",
                    new String[] { String.valueOf(strId) });

            db.close();
            return rows; // return rows updated.

        } catch (Exception e) {
            return -1;
        }   
    }

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

}

和活动代码,我用它来向ListView显示数据, MainActivity.java: -

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

 //  initialize databaseHelper object in oncreate of Activity before using it
        dHelper = new DatabaseHelper(MainActivity.this);

        // Hashmap for ListView
        contactList = new ArrayList<HashMap<String, String>>();

        // Creating JSON Parser instance
        jParser = new JSONParser();

        // getting JSON string from URL
        jObject = jParser.getJSONFromUrl(url);

        try {
            // Getting Array of events
            jArray = jObject.getJSONArray(TAG_CHURCH);

            // looping through All events
            for(int i = 0; i < jArray.length(); i++){
                JSONObject c = jArray.getJSONObject(i);

                // Storing each json item in variable
                strId = c.getString(TAG_ID);
                Log.d("strId :: --", strId);
                strTitle = c.getString(TAG_TITLE);
                Log.d("strTitle :: --", strTitle);

                dHelper.InsertData(strId, strTitle);

                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();

                // adding each child node to HashMap key => value
                map.put(TAG_ID, strId);
                map.put(TAG_TITLE, strTitle);

                // adding HashList to ArrayList
                contactList.add(map);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }


        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(this, contactList,
                R.layout.activity_list,
                new String[] { TAG_TITLE }, new int[] {
                        R.id.title });

        setListAdapter(adapter);

        // selecting single ListView item
        final ListView lv = getListView();

        // Launching new screen on Selecting Single ListItem
        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long iD) {
                strId = contactList.get(position).get(TAG_ID);
                Log.d("strId-onItemClick :: --", strId);
                strTitle = contactList.get(position).get(TAG_TITLE);
                Log.d("strTitle-onItemClick :: --", strTitle);
                Toast.makeText(getApplicationContext(),"Id-"+strId+"Title-"+strTitle, Toast.LENGTH_LONG);
            }
        });     
    }

0 个答案:

没有答案