简体   繁体   中英

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./

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

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 . 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
  • call its open method to open database connection
  • call any helper method for insertion/deletion/getting data
  • close the connection by calling close method of the object

Edit inside your function 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 .

This tutorial might help !

You need to create a class that extends SQLiteOpenHelper .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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