How to fetch data from SQLite and store it to List

2019-09-25 02:29发布

问题:

I am very novice programmer in Android. My query is to fetch data from SQLite and then reflect all data in to list column . now when i click on button, that all data must be converted in .pdf format with good tabularised format... Millions of thank in advance..

public class Details_List extends Activity {
Button share;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.details_list);
    ListView lv= (ListView)findViewById(R.id.listview);
    share = (Button)findViewById(R.id.email);
    share.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(Details_List.this, Email.class);
            startActivity(i);
        }
    });

    // create the grid item mapping
    String[] from = new String[] {"rowid", "col_1", "col_2", "col_3", "col_4", "col_5"};
    int[] to = new int[] { R.id.item1, R.id.item2, R.id.item3, R.id.item4,  R.id.item5,  R.id.item6};

    // prepare the list of all records
    List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();
    for(int i = 1; i < 10; i++){
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("rowid", "" + i);
        map.put("col_1", "col_1_item_" + i);
        map.put("col_2", "col_2_item_" + i);
        map.put("col_3", "col_3_item_" + i);
        map.put("col_3", "col_4_item_" + i);
        map.put("col_3", "col_5_item_" + i);
        fillMaps.add(map);
    }

    // fill in the grid_item layout
    SimpleAdapter adapter = new SimpleAdapter(this, fillMaps, R.layout.grid_item, from, to);
    lv.setAdapter(adapter);
}
}

回答1:

for your first purpose to get data from SQLite DB into arraylist, here is an example below:

public class DatabaseHelper_Notification extends SQLiteOpenHelper
{
public String TAG = "DatabaseHelper:";
private static final String DATABASE_NAME = "Notifications";
private final Context cntxtDBContext;
final static int DATABASE_VERSION = 2;
final String _TableName = "Notifications";
final String _RowID = "RowID";
final String _NotificationID = "NotificationID";
final String _NotificationText = "NotificationText";
final String _NotificationRead = "NotificationRead";

/**
 * the default constructor of this class
 * 
 * @param context
 *             the context in which this object is to be used
 */
public DatabaseHelper_Notification(Context context)
{
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    this.cntxtDBContext = context;
    // strDB_path = cntxtDBContext.getDatabasePath(strDB_NAME).toString();
}

@Override
public void onCreate(SQLiteDatabase db)
{
    String CREATE_CONTACTS_TABLE = "CREATE TABLE " + _TableName + "(" + _RowID + " INTEGER PRIMARY KEY," + _NotificationID
            + " INTEGER NOT NULL  DEFAULT (0)," + _NotificationText + " TEXT" + "," + _NotificationRead + "  BOOL NOT NULL DEFAULT (0))";
    db.execSQL(CREATE_CONTACTS_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
    if (newVersion > oldVersion)
    {
        db.execSQL("DROP TABLE IF EXISTS " + _TableName);

        // Create tables again
        onCreate(db);
    }

}

/**
 * gets all notification news from notifications database
 * 
 * @return the list of the notification present in the database
 */
public ArrayList<NotificationCls> getAllNotifications()
{
    ArrayList<NotificationCls> alNotifications = new ArrayList<NotificationCls>();
    ;
    Cursor curData = null;
    SQLiteDatabase db = null;
    try
    {
        db = this.getReadableDatabase();
        String strSelectQuery = "SELECT * FROM " + _TableName;
        curData = db.rawQuery(strSelectQuery, null);
        if (curData.getCount() > 0)
        {
            curData.moveToFirst();
            do
            {
                NotificationCls noti = new NotificationCls();
                noti.setStrNotificationText(curData.getString(curData.getColumnIndex(_NotificationText)));
                noti.setiNotificationiID(curData.getInt(curData.getColumnIndex(_NotificationID)));
                boolean bRead = curData.getInt(curData.getColumnIndex(_NotificationRead)) == 0 ? false : true;
                noti.setbNotificationRead(bRead);
                alNotifications.add(noti);
            }
            while (curData.moveToNext());
        }
    }
    catch (SQLException e)
    {
        e.printStackTrace();
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        if (curData != null)
        {
            curData.close();
        }
        if (db != null)
        {
            db.close();
        }

    }
    return alNotifications;
}

/**
 * insert the notification message in the database
 * 
 * @param Msg
 *             the message received in push notification
 * @param id
 *             the id on which the notification was sent
 * @return this method will return <code>true</code> if the DB transaction was successful else it will return <code>false</code>
 */
public boolean insertNotification(String Msg, int id)
{
    long lid = -1;
    SQLiteDatabase db = null;
    try
    {
        db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(_NotificationID, id);
        values.put(_NotificationText, Msg);
        db.insert(_TableName, null, values);
        db.close();
    }
    catch (SQLException e)
    {
        lid = -1;
        e.printStackTrace();
    }
    catch (Exception e)
    {
        lid = -1;
        e.printStackTrace();
    }
    finally
    {
        if (db != null)
            db.close();
    }
    return lid == -1 ? false : true;
}

/**
 * this method will delete all the records associated with the specified notification id
 * 
 * @param iNotificationiID
 *             the id on which the notification was sent
 * @return this method will return <code>true</code> if the DB transaction was successful else it will return <code>false</code>
 */
public boolean deleteNotification(int iNotificationiID)
{
    int result = 0;
    SQLiteDatabase db = this.getWritableDatabase();
    result = db.delete(_TableName, _NotificationID + " = " + iNotificationiID, new String[] {});
    db.close();
    if (result > 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

/**
 * this method will delete all the records from the database
 * 
 * @return this method will return <code>true</code> if the DB transaction was successful else it will return <code>false</code>
 */
public boolean deleteAllNotifications()
{
    int result = 0;
    SQLiteDatabase db = this.getWritableDatabase();
    result = db.delete(_TableName, null, new String[] {});
    db.close();
    if (result > 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

/**
 * this method will return the number of records present in the database
 * 
 * @return the number of records present in the database
 */
public int getNotificationsCount()
{
    String countQuery = "SELECT  * FROM " + _TableName;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    cursor.close();
    // return count
    return cursor.getCount();
}

public boolean markNotificationAsRead(int iNotificationiID)
{
    // TODO Auto-generated method stub
    int result = -1;
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(_NotificationRead, 1);

    // updating row
    result = db.update(_TableName, values, _NotificationID + " = ?", new String[] { String.valueOf(iNotificationiID) });
    db.close();
    if (result > 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

public boolean markAllNotificationAsRead()
{
    // TODO Auto-generated method stub
    int result = -1;
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(_NotificationRead, 1);

    // updating row
    result = db.update(_TableName, values, null, new String[] {});
    db.close();
    if (result > 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

/**
 * gets all notification news from notifications database
 * 
 * @return the list of the notification present in the database
 */
public ArrayList<NotificationCls> getAllUnreadNotifications()
{
    ArrayList<NotificationCls> alNotifications = new ArrayList<NotificationCls>();
    ;
    Cursor curData = null;
    SQLiteDatabase db = null;
    try
    {
        db = this.getReadableDatabase();
        String strSelectQuery = "SELECT * FROM " + _TableName + " WHERE " + _NotificationRead + "=0";
        curData = db.rawQuery(strSelectQuery, null);
        if (curData.getCount() > 0)
        {
            curData.moveToFirst();
            do
            {
                NotificationCls noti = new NotificationCls();
                noti.setStrNotificationText(curData.getString(curData.getColumnIndex(_NotificationText)));
                noti.setiNotificationiID(curData.getInt(curData.getColumnIndex(_NotificationID)));
                alNotifications.add(noti);
            }
            while (curData.moveToNext());
        }
    }
    catch (SQLException e)
    {
        e.printStackTrace();
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        if (curData != null)
        {
            curData.close();
        }
        if (db != null)
        {
            db.close();
        }

    }
    return alNotifications;
}

and this is the entity class:

public class NotificationCls
{
String strNotificationText;
int iNotificationiID;
boolean bNotificationRead = false;

public String getStrNotificationText()
{
    return strNotificationText;
}

public void setStrNotificationText(String strNotificationText)
{
    this.strNotificationText = strNotificationText;
}

public int getiNotificationiID()
{
    return iNotificationiID;
}

public void setiNotificationiID(int iNotificationiID)
{
    this.iNotificationiID = iNotificationiID;
}

public boolean isbNotificationRead()
{
    return bNotificationRead;
}

public void setbNotificationRead(boolean bNotificationRead)
{
    this.bNotificationRead = bNotificationRead;
}

}

to get all data from SQLite in arraylist write below code in your activity:

DatabaseHelper_Notification databaseHelper_notification = new DatabaseHelper_Notification(this);
ArrayList<NotificationCls> alNotifications = databaseHelper_notification.getAllNotifications();

I hope this helps you...