如何从Android中的Sqlite数据库中获取数据并在List视图中打印

时间:2015-04-13 06:40:06

标签: android

class download extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub

            try {
                result = JSONfunctions.getJSONfromURL(URL);
                _jarray1 = new JSONArray(result);

                for (int i = 0; i < _jarray1.length(); i++) {
                    DataModel datamodel = new DataModel();

                    JSONObject _obj = _jarray1.getJSONObject(i);
                    ImagePath = _obj.getString("news_title");
                    if (ImagePath != null) {
                        datamodel.setImagepath(_obj.getString("news_title"));

                        Log.e("Valueeeeeeeeeeeeeeeeeee",
                                "IMAGE PATHAAAAAAAAAAAA: "
                                        + _obj.getString("news_title"));

                    }
                    list.add(datamodel);
                }

                dbmanger.writeContactsToDB(list);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub

            CustomList adapter = new CustomList(MainActivity.this, list);
            fruitList.setAdapter(adapter);
            super.onPostExecute(result);
        }
    }

}


public class DataBaseManager extends SQLiteOpenHelper {
    Context mContext;

    public DataBaseManager(Context applicationcontext) {
        super(applicationcontext, "androidsqlite.db", null, 1);
        Log.d("Database", "Created");
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        String query;
        query = "CREATE TABLE News ( newsId INTEGER PRIMARY KEY, newsTITLE TEXT)";
        db.execSQL(query);
        Log.d("NEWS Table", "Students Created");

    }

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

    }

    public int inserOrUpdateContact(DataModel datamodel) {
        SQLiteDatabase database = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("NewsTitle", datamodel.getImagepath());
        database.insert("Values", null, values);
        database.close();
        return -1;

    }

    public ArrayList<DataModel> getAllStudents() {
        ArrayList<DataModel> wordList;
        wordList = new ArrayList<DataModel>();
        String selectQuery = "SELECT  * FROM Students";
        SQLiteDatabase database = this.getWritableDatabase();
        Cursor cursor = database.rawQuery(selectQuery, null);
        if (cursor.moveToFirst()) {
            do {
                // HashMap<DataModel> map = new HashMap<DataModel>();
                // map.put("StudentId", cursor.getString(0));
                // map.put("StudentName", cursor.getString(1));
                // wordList.add(map);
            } while (cursor.moveToNext());
        }

        // return contact list
        return wordList;
    }

    public void writeContactsToDB(ArrayList<DataModel> newslist) {
        // TODO Auto-generated method stub
        int numContact = newslist.size();

        for (int i = 0; i < numContact; i++) {

            inserOrUpdateContact(newslist.get(i));

        }

    }

}

使用此下载类我可以在本地数据库中插入数据但我无法从本地数据库中获取数据我必须在列表视图中打印当前我能够显示来自Web服务的数据但我必须从本地请帮我如何创建从Sqlite获取数据的功能如何使用游标从Web服务获取所有数据请建议我初学者并尝试学习Sqlite数据库./

2 个答案:

答案 0 :(得分:0)

您必须创建一个扩展您创建的Sql数据库类的类: 那么你将不得不实现这样的方法: 在这里,我创建了一个类,我在我的简单笔记中使用了应用程序

public class simple_notes_db extends Activity {
    private static String row_key="id";
    private static String title="title";
    private static String text_note="note";
    private static String tag="tag";
    private static int db_version=1;


    private static String db_name="simple_notes";
    private static String table_name="notes_table";

    static sql ourhelper;
    static Context ourcontext;
    SQLiteDatabase ourdatabase;


   public simple_notes_db(Context context)
    {
        ourcontext=context;
        ourhelper=new sql(context);


    }


    public class sql extends SQLiteOpenHelper {


        public sql(Context c)
        {
            super(c, db_name, null, db_version);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE " + table_name + " (" + row_key + " INTEGER PRIMARY KEY AUTOINCREMENT," + title + " TEXT NOT NULL, " + text_note+" TEXT NOT NULL, "+tag+" TEXT "+  ");");

        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        }
    }

    public simple_notes_db open()
    {
        ourdatabase=ourhelper.getWritableDatabase();
        return this;

    }

    public void close(){ourhelper.close();}

    public long create_entry(String titlefrom,String note,String tagfrom)
    {


        ContentValues cv=new ContentValues();
        cv.put(title,titlefrom);
        cv.put(text_note,note);
        cv.put(tag,tagfrom);
        return ourdatabase.insert(table_name,null,cv);
    }

    public List<db_value_holder> get_values()
    {

        List<db_value_holder> values=new LinkedList<db_value_holder>();
        String col[]=new String[]{row_key,title,text_note,tag};
        Cursor c = ourdatabase.query(table_name,col,null,null,null,null,null);
        int irow=c.getColumnIndex(row_key);
        int ititle=c.getColumnIndex(title);
        int itext=c.getColumnIndex(text_note);
        int itag=c.getColumnIndex(tag);
        for(c.moveToFirst();!c.isAfterLast();c.moveToNext())
        {
            db_value_holder holder=new db_value_holder();
            holder.rowid_h=c.getInt(irow);
            holder.title_h=c.getString(ititle);
            holder.note_h=c.getString(itext);
            holder.tag_h=c.getString(itag);
            values.add(holder);

        }
        return values;


    }

    public List<String> get_record(int i)
    {
        List<String> values=new LinkedList<String>();
        String col[]=new String[]{row_key,title,text_note};

        Cursor c = ourdatabase.query(table_name,col,row_key+"="+i,null,null,null,null);
        int ititle=c.getColumnIndex(title);
        int itext=c.getColumnIndex(text_note);
        c.moveToFirst();
        values.add(c.getString(ititle));
        values.add(c.getString(itext));
        return values;

    }
    public long fetchPlacesCount() {
        String sql = "SELECT COUNT(*) FROM " + table_name;
        SQLiteStatement statement = ourdatabase.compileStatement(sql);
        long count = statement.simpleQueryForLong();
        return count;
    }



}

在上面的类simple_notes_db中,我创建了一个内部类,它将创建,打开和关闭所述数据库。外部类负责实现其他方法,如插入,删除和从数据库中获取数据。

如果您想在任何活动中使用它。

  • 制作simple_notes_db
  • 的对象
  • 调用其open方法打开数据库连接
  • 调用任何帮助方法来插入/删除/获取数据
  • 通过调用对象的close方法来关闭连接

编辑  函数内的 public int inserOrUpdateContact(DataModel datamodel):

    values.put("newsID", datamodel.getNewsID());
    values.put("newsTitle", datamodel.getImagepath());
    database.insert("news", null, values);

你将newsID与NewsID,newstitle与NewsTitle混淆,第一个参数od insert function是表名。

答案 1 :(得分:0)

This tutorial might help

您需要创建一个extends SQLiteOpenHelper

的课程