简体   繁体   English

如何从android中的Sqlite数据库获取数据并在列表视图中打印

[英]how to fetch data and print in List view from Sqlite database in 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));

        }

    }

}

download class using this i am able to Insert Data in database locally but i am unable to fetch data from local database i have to print in List view currently i am able to display data from web service but i have to display it from locally please help me how to create function for fetch data from Sqlite how to use cursor to get all data from web service please suggest me am beginner and try to learn Sqlite database./ 使用该类的下载类,我能够在本地数据库中插入数据,但我无法从本地数据库中获取数据,我目前必须在列表视图中打印,我能够显示来自Web服务的数据,但我必须从本地显示,请帮助我如何创建用于从Sqlite提取数据的函数如何使用游标从Web服务获取所有数据,请建议我是初学者并尝试学习Sqlite数据库。

you will have to create a class that extends the Sql database class you created : then you will have to implement a method like this : here i have created a class that i use in my simple note taking app 您将必须创建一个扩展您创建的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;
    }



}

in the above class simple_notes_db i have created a inner class that will create , open and close the said database . 在上面的类simple_notes_db中,我创建了一个内部类,该内部类将创建,打开和关闭所述数据库。 the outer class is responsible to implement other methods like insertion , deletion and getting the data from the database . 外部类负责实现其他方法,如插入,删除和从数据库中获取数据。

if you want to use this in any of your activity . 如果您想在任何活动中使用它。

  • make an object of simple_notes_db 制作一个simple_notes_db对象
  • call its open method to open database connection 调用其open方法打开数据库连接
  • call any helper method for insertion/deletion/getting data 调用任何辅助方法进行插入/删除/获取数据
  • close the connection by calling close method of the object 通过调用对象的close方法关闭连接

Edit inside your function public int inserOrUpdateContact(DataModel datamodel): 在您的函数public int inserOrUpdateContact(DataModel datamodel)中进行编辑:

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

you are confusing the newsID with NewsID , newstitle with NewsTitle and the first parameter od insert function is the table name . 您会将newsID与NewsID混淆,将新闻标题与NewsTitle混淆,插入函数的第一个参数是表名。

This tutorial might help ! 本教程可能会有所帮助

You need to create a class that extends SQLiteOpenHelper . 您需要创建一个extends SQLiteOpenHelper的类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM