【问题标题】:Display variable data from SQLite using base adapter and listview使用基本适配器和列表视图显示来自 SQLite 的变量数据
【发布时间】:2015-12-01 02:53:24
【问题描述】:

您好,我正在开发的应用程序包含来自解析的 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();
        }
}

【问题讨论】:

  • 您能否正确地提供一些关于您想要实现的目标的见解?您面临的任何错误和问题都可以帮助社区了解您实际遇到的问题
  • 我想在列表视图中显示存储在sqlite中的json数据(其中“警报”“消息”“日期”)
  • @Fabiano Francesconi
  • 你可以从数据库中取回来,然后显示出来。你在寻找什么问题?
  • 如何找回它...@Diyoda

标签: android sqlite listview adapter


【解决方案1】:

进行中,,,

  1. 编写您的 Dao 类(在您的情况下为 DatabaseHandler 类)以从数据库中获取数据(或者您可以编写一个内容提供程序 - 实现此目的的好方法。)

一个示例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 中显示的对象列表。

在此示例中,geDocuments() 将为您提供对象列表。

  1. 将其注入您的 Adapter 并为 listView 引用设置 Adapter。

【讨论】:

    【解决方案2】:

    公共类 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
    
    }
    

    }

    【讨论】:

      【解决方案3】:
      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;
      }
      

      }

      【讨论】:

        猜你喜欢
        • 2014-06-11
        • 1970-01-01
        • 2014-12-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多