使用基本适配器和列表视图显示来自SQLite的可变数据

时间:2015-09-04 21:12:04

标签: android sqlite listview adapter

您好我正在处理应用程序包含来自解析的json通知和应用程序将它存储在SQLite中我执行了该任务但是我有一个很大的问题,那就是我想在列表视图中显示存储的通知在主要活动中显示它是我的代码

public class Receiver extends ParsePushBroadcastReceiver {


 @Override
    public void onPushReceive(Context context, Intent intent) {
        super.onPushReceive(context, intent);
        Log.e("Push", "Clicked");
        Intent i = new Intent(context, splashscreen.class);
        i.putExtras(intent.getExtras());
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i); 


        Log.d("Alert: ", "Inserting from onReceive"); 
        Bundle extras = intent.getExtras();
        String jsonData = extras.getString("com.parse.Data");
        JSONObject jsonObject;
        try {
            jsonObject = new JSONObject(jsonData);
            String alert = jsonObject.getString("alert");
            Log.d("Insert: ",alert); 
            String Message = jsonObject.getString("Message");
            Log.d("Title: ",Message); 
            String Date = jsonObject.getString("Date");
            Log.d("Date: ",Date); 


            DatabaseHandler db=new DatabaseHandler(context);

            db.addnotification(new notification(alert,Message,Date));

            Log.d("Reading: ", "Reading all notifications.."); 
            List<notification> notifications = db.getAllnotifications();       

            for (notification cn : notifications) {
                String log = "Id: "+cn.getID()+" ,Title: " + cn.gettitle() + " ,Message: " + cn.getmessage()+ " ,Date: " + cn.gettimedate();
                // Writing notifications to log
                Log.d("Name: ", log);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
}

3 个答案:

答案 0 :(得分:0)

正在进行中,

  1. 编写您的Dao类(在您的情况下,DatabaseHandler类)以从数据库中获取数据(或者您可以编写内容提供程序 - 实现此目的的绝佳方式。)
  2. 示例dao类如下,

    public class DocumentRepository {
    
                public static final String TABLE_DOCUMENT = "document";
                public static final String COLUMN_ID = BaseColumns._ID;
                public static final String RECORD_ID = "record_id";
                public static final String UUID_DOCUMENT_NAME = "unique_file_name";
    
                public static final String DOCUMENT_TABLE_CREATE = "create table if not exists "
                        + TABLE_DOCUMENT + "(" + COLUMN_ID
                        + " integer primary key autoincrement, " + RECORD_ID
                        + " integer , " + UUID_DOCUMENT_NAME
                        + " text );";
                private Context context;
    
                public DocumentRepository(Context context) {
                    this.context = context;
                }
    
    
                public ArrayList<Document> geDocuments(Integer customerId) {
                    ArrayList<Document> documents = new ArrayList<>();
                    String query = "SELECT * FROM " + TABLE_DOCUMENT + " WHERE " + RECORD_ID + " = '" + customerId + "'";
                    SQLiteDatabase database = ......// create a instance of your SqliteDatabase implementation 
                    Cursor cursor = database.rawQuery(query, null);
    
                    if (cursor.moveToFirst()) {
                        do {
                            Document document = new Document();
                            document.setId(cursor.getInt(0));
                            document.setUniqueIdentifier(cursor.getString(3));
                            documents.add(document);
                        } while (cursor.moveToNext());
                    }
                    return documents;
                }
            }
    
    1. 获取要在ListView中显示的对象列表。
    2. 在此示例中,

      geDocuments()将为您提供对象列表。

      1. 将其注入适配器并为listView参考设置适配器。

答案 1 :(得分:0)

公共类DatabaseHandler扩展了SQLiteOpenHelper {

// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "notificationsbase";

// notifications table name
private static final String TABLE_notifications = "notifications";

// notifications Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_title = "title";
private static final String KEY_message = "message";
private static final String KEY_timedate = "timedate";

public DatabaseHandler(Context context) 
{
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_notificationS_TABLE = "CREATE TABLE " + TABLE_notifications + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_title + " TEXT,"
            + KEY_message + " TEXT ,"  + KEY_timedate + " NUMERIC " + ")";
    db.execSQL(CREATE_notificationS_TABLE);
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_notifications);

    // Create tables again
    onCreate(db);
}

/**
 * All CRUD(Create, Read, Update, Delete) Operations
 */

// Adding new notification
void addnotification(notification notification) 
{
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_title, notification.gettitle());            // title
    values.put(KEY_message, notification.getmessage());       // message
    values.put(KEY_timedate, notification.gettimedate());    // timedate

    // Inserting Row
    db.insert(TABLE_notifications, null, values);
    db.close(); // Closing database connection
}

// Getting single notification
notification getContact(int id) {
    SQLiteDatabase db = this.getReadableDatabase();

    Cursor cursor = db.query(TABLE_notifications, new String[] { KEY_ID,
            KEY_title, KEY_message, KEY_timedate }, KEY_ID + "=?",
            new String[] { String.valueOf(id) }, null, null, null, null);
    if (cursor != null)
        cursor.moveToFirst();

    notification notifications = new notification(Integer.parseInt(cursor.getString(0)),
            cursor.getString(1), cursor.getString(2), cursor.getString(3));
    // return contact
    return notifications;
}

// Getting All notifications
public List<notification> getAllnotifications() {
    List<notification> notificationList = new ArrayList<notification>();
    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_notifications;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list
    if (cursor.moveToFirst()) {
        do {
            notification notification = new notification();
            notification.setID(Integer.parseInt(cursor.getString(0)));
            notification.settitle(cursor.getString(1));
            notification.setmessage(cursor.getString(2));
            notification.settimedate(cursor.getString(3));
            // Adding notification to list
            notificationList.add(notification);
        } while (cursor.moveToNext());
    }

    // return notification list
    return notificationList;
}

// Updating single notification
public int updatenotification(notification notification) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_title, notification.gettitle());
    values.put(KEY_message, notification.getmessage());
    values.put(KEY_timedate, notification.gettimedate());


    // updating row
    return db.update(TABLE_notifications, values, KEY_ID + " = ?",
            new String[] { String.valueOf(notification.getID()) });
}

// Deleting single notification
public void deletenotification(notification notification) {
    SQLiteDatabase db = this.getWritableDatabase();
    db.delete(TABLE_notifications, KEY_ID + " = ?",
            new String[] { String.valueOf(notification.getID()) });
    db.close();
}


// Getting notifications Count
public int getnotificationsCount() {
    String countQuery = "SELECT  * FROM " + TABLE_notifications;
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(countQuery, null);
    cursor.close();

    // return count
    return cursor.getCount();
}

public void open() {
    // TODO Auto-generated method stub

}

}

答案 2 :(得分:0)

public class notification 

{

//private variables
int id;
String title;
String message;
String timedate;


// Empty constructor
public notification(){

}
// constructor
public notification(int id, String title, String message, String timedate){
    this.id = id;
    this.title = title;
    this.message = message;
    this.timedate = timedate;


}

// constructor
public notification(String title, String message, String timedate){
    this.title = title;
    this.message = message;
    this.timedate = timedate;

}
// getting ID
public int getID(){
    return this.id;
}

// setting id
public void setID(int id){
    this.id = id;
}

// getting title
public String gettitle(){
    return this.title;
}

// setting title
public void settitle(String title){
    this.title = title;
}

// getting message
public String getmessage(){
    return this.message;
}

// setting message
public void setmessage(String message){
    this.message = message;
}

// getting timedate
public String gettimedate(){
    return this.timedate;
}

// setting message
public void settimedate(String timedate){
    this.timedate = timedate;
}

}