mardi 5 avril 2016

Custom Listview with Cursor Adapter

enter image description here

I want my list from sqlite to be displayed. But, its displaying blank or dummy list. I am trying to get a list from SQLite database . But, Something is going wrong and nothing is being displayed in the ListView. As I am relatively new o Android, so I might have missed something. I need your help.

And please tell me , where to add dummy data to the SQLite so that I can check if this is working fine or not.

I am following some online tutorial. MainActivity.java

        import android.app.Activity;
        import android.content.Intent;
        import android.os.Bundle;
        import android.view.View;
        import android.widget.Button;
        import android.widget.ImageButton;
        import android.widget.ListView;

        import java.util.ArrayList;

        public class MainActivity extends Activity {

            private ListView listView1;
            PostsDatabaseHelper dbHelper;
            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
                ArrayList<Favourites> arrayOfFavs = new ArrayList<Favourites>();


                //FavouritesAdapter adapter = new FavouritesAdapter(this,R.layout.listview_item_row, arrayOfFavs);

                // TodoDatabaseHandler is a SQLiteOpenHelper class connecting to SQLite
               // TodoDatabaseHandler handler = new TodoDatabaseHandler(this);
                // null;
                Favourites fav= new Favourites();

                fav.fid="1";
                fav.title="Fav title 1";

                dbHelper.addPost(fav);
                fav.fid="2";
                fav.title="fav title 2";
                dbHelper.addPost(fav);
                arrayOfFavs= dbHelper.getAllPosts();
                FavouritesAdapter adapter = new FavouritesAdapter(this,R.layout.listview_item_row, arrayOfFavs);

              /*
               Get access to the underlying writeable database
               SQLiteDatabase db = fDbase.getWritableDatabase();
               Query for items from the database and get a cursor back
               ArrayList<ArrayList<Object>> todoCursor = fDbase.getAllRowsAsArrays();
               FavouritesAdapter adapter= new FavouritesAdapter(this, R.layout.listview_item_row,todoCursor);
               */

                listView1 = (ListView) findViewById(R.id.listView1);
                //ImageButton editButton =   (ImageButton) findViewById(R.id.editButton);
                //ImageButton deleteButton = (ImageButton) findViewById(R.id.deleteButton);

                View header = (View) getLayoutInflater().inflate(R.layout.listview_header_row, null);
                listView1.addHeaderView(header);


                listView1.setAdapter(adapter);
            }
        }


        PostDaabaseHelper.java

    package portfolio.first_app.practice.com.customlistviewanditems;

    import android.content.ContentValues;
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;

    import java.util.ArrayList;

    /**
     * Created by SouRAV on 4/3/2016.
     */
    public class PostsDatabaseHelper extends SQLiteOpenHelper {
        // Database Info
        private static final String DATABASE_NAME = "postsDatabase";
        private static final int DATABASE_VERSION = 1;

        // Table Names
        private static final String TABLE_POSTS = "posts";
       // private static final String TABLE_USERS = "users";

        // Post Table Columns
        //private static final String KEY_POST_ID = "id";
        //private static final String KEY_POST_USER_ID_FK = "userId";
        private static final String KEY_POST_TEXT = "text";
        private static final String KEY_POST_TITLE= "title";
        private static final String KEY_POST_ID= "fid";
       // private static final  TAG =   ;



      /*  // User Table Columns
        private static fjava.lang.Stringinal String KEY_USER_ID = "id";
        private static final String KEY_USER_NAME = "userName";
        private static final String KEY_USER_PROFILE_PICTURE_URL = "profilePictureUrl";*/

        private static PostsDatabaseHelper sInstance;

        public static synchronized PostsDatabaseHelper getInstance(Context context) {
            // Use the application context, which will ensure that you
            // don't accidentally leak an Activity's context.

            if (sInstance == null) {
                sInstance = new PostsDatabaseHelper(context.getApplicationContext());
            }
            return sInstance;
        }

        /**
         * Constructor should be private to prevent direct instantiation.
         * Make a call to the static method "getInstance()" instead.
         */
        public PostsDatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        // Called when the database connection is being configured.
        // Configure database settings for things like foreign key support, write-ahead logging, etc.
        @Override
        public void onConfigure(SQLiteDatabase db) {
            super.onConfigure(db);
            db.setForeignKeyConstraintsEnabled(true);
        }

        // Called when the database is created for the FIRST time.
        // If a database already exists on disk with the same DATABASE_NAME, this method will NOT be called.
        @Override
        public void onCreate(SQLiteDatabase db) {
         /*   String CREATE_POSTS_TABLE = "CREATE TABLE " + TABLE_POSTS +
                    "(" +
                    KEY_POST_ID + " INTEGER PRIMARY KEY," + // Define a primary key
                    KEY_POST_USER_ID_FK + " INTEGER REFERENCES " + TABLE_USERS + "," + // Define a foreign key
                    KEY_POST_TEXT + " TEXT" +
                    ")";*/

            String CREATE_POSTS_TABLE = "CREATE TABLE " + TABLE_POSTS +
                    "(" +
                    KEY_POST_TITLE + " TEXT," +
                    KEY_POST_TEXT + " TEXT," +
                   // KEY_POST_USER_ID_FK + " TEXT" +
                    ")";

            db.execSQL(CREATE_POSTS_TABLE);
           // db.execSQL(addPost());

            //db.execSQL(CREATE_USERS_TABLE);
        }

        // Called when the database needs to be upgraded.
        // This method will only be called if a database already exists on disk with the same DATABASE_NAME,
        // but the DATABASE_VERSION is different than the version of the database that exists on disk.
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            if (oldVersion != newVersion) {
                // Simplest implementation is to drop all old tables and recreate them
                db.execSQL("DROP TABLE IF EXISTS " + TABLE_POSTS);
               // db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
                onCreate(db);
            }
        }

        // Insert a post into the database
        public void addPost(Favourites fav) {
            // Create and/or open the database for writing
            SQLiteDatabase db = getWritableDatabase();

            // It's a good idea to wrap our insert in a transaction. This helps with performance and ensures
            // consistency of the database.
            db.beginTransaction();
            try {
                // The user might already exist in the database (i.e. the same user created multiple posts).
               // String title = addOrUpdateUser(post.fav);

                ContentValues values = new ContentValues();
                //values.put(KEY_POST_USER_ID_FK, userId);
                values.put(KEY_POST_TITLE, fav.title);
                values.put(KEY_POST_ID, fav.fid);

                // Notice how we haven't specified the primary key. SQLite auto increments the primary key column.
                db.insertOrThrow(TABLE_POSTS, null, values);
                db.setTransactionSuccessful();
            } catch (Exception e) {
               // Log.d(TAG, "Error while trying to add post to database");
            } finally {
                db.endTransaction();
            }
        }

        // Insert or update a user in the database
        // Since SQLite doesn't support "upsert" we need to fall back on an attempt to UPDATE (in case the
        // user already exists) optionally followed by an INSERT (in case the user does not already exist).
        // Unfortunately, there is a bug with the insertOnConflict method
        // 
(http://ift.tt/1oyJaZ3) so we need to fall back to the more
        // verbose option of querying for the user's primary key if we did an update.
      /*  public long addOrUpdateUser(User user) {
            // The database connection is cached so it's not expensive to call getWriteableDatabase() multiple times.
            SQLiteDatabase db = getWritableDatabase();
            long userId = -1;

            db.beginTransaction();
            try {
                ContentValues values = new ContentValues();
                values.put(KEY_USER_NAME, user.userName);
                values.put(KEY_USER_PROFILE_PICTURE_URL, user.profilePictureUrl);

                // First try to update the user in case the user already exists in the database
                // This assumes userNames are unique
                int rows = db.update(TABLE_USERS, values, KEY_USER_NAME + "= ?", new String[]{user.userName});

                // Check if update succeeded
                if (rows == 1) {
                    // Get the primary key of the user we just updated
                    String usersSelectQuery = String.format("SELECT %s FROM %s WHERE %s = ?",
                            KEY_USER_ID, TABLE_USERS, KEY_USER_NAME);
                    Cursor cursor = db.rawQuery(usersSelectQuery, new String[]{String.valueOf(user.userName)});
                    try {
                        if (cursor.moveToFirst()) {
                            userId = cursor.getInt(0);
                            db.setTransactionSuccessful();
                        }
                    } finally {
                        if (cursor != null && !cursor.isClosed()) {
                            cursor.close();
                        }
                    }
                } else {
                    // user with this userName did not already exist, so insert new user
                    userId = db.insertOrThrow(TABLE_USERS, null, values);
                    db.setTransactionSuccessful();
                }
            } catch (Exception e) {
                Log.d(TAG, "Error while trying to add or update user");
            } finally {
                db.endTransaction();
            }
            return userId;
        }*/

        // Get all posts in the database
        public ArrayList<Favourites> getAllPosts() {
            ArrayList<Favourites> posts = new ArrayList<>();

          /*  // SELECT * FROM POSTS
            // LEFT OUTER JOIN USERS
            // ON POSTS.KEY_POST_USER_ID_FK = USERS.KEY_USER_ID
            String POSTS_SELECT_QUERY =
                    String.format("SELECT * FROM %s LEFT OUTER JOIN %s ON %s.%s = %s.%s",
                            TABLE_POSTS,
                            TABLE_USERS,
                            TABLE_POSTS, KEY_POST_USER_ID_FK,
                            TABLE_USERS, KEY_USER_ID);*/

            // "getReadableDatabase()" and "getWriteableDatabase()" return the same object (except under low
            // disk space scenarios)
            String POSTS_SELECT_QUERY=  String.format("SELECT %s FROM %s WHERE %s = ?",
                    KEY_POST_ID, TABLE_POSTS, KEY_POST_TEXT);
            SQLiteDatabase db = getReadableDatabase();
            Cursor cursor = db.rawQuery(POSTS_SELECT_QUERY, null);
            try {
                if (cursor.moveToFirst()) {
                    do {
                       /* Favourites newUser = new Favourites();
                        newUser.title = cursor.getString(cursor.getColumnIndex(KEY_POST_TITLE));
                       // newUser.editButton = cursor.getString(cursor.getColumnIndex(KEY_POST_TEXT));*/

                        Favourites newPost = new Favourites();
                        newPost.title = cursor.getString(cursor.getColumnIndex(KEY_POST_TITLE));
                        newPost.fid =   cursor.getString(cursor.getColumnIndex(KEY_POST_ID));
                        posts.add(newPost);
                    } while(cursor.moveToNext());
                }
            } catch (Exception e) {
              //  Log.d(TAG, "Error while trying to get posts from database");
            } finally {
                if (cursor != null && !cursor.isClosed()) {
                    cursor.close();
                }
            }
            return posts;
        }

        // Update the user's profile picture url
       /* public int updateUserProfilePicture(User user) {
            SQLiteDatabase db = this.getWritableDatabase();

            ContentValues values = new ContentValues();
            values.put(KEY_USER_PROFILE_PICTURE_URL, user.profilePictureUrl);

            // Updating profile picture url for user with that userName
            return db.update(TABLE_USERS, values, KEY_USER_NAME + " = ?",
                    new String[] { String.valueOf(user.userName) });
        }
    */
        // Delete all posts and users in the database
        public void deleteAllPostsAndUsers() {
            SQLiteDatabase db = getWritableDatabase();
            db.beginTransaction();
            try {
                // Order of deletions is important when foreign key relationships exist.
                db.delete(TABLE_POSTS, null, null);
               // db.delete(TABLE_USERS, null, null);
                db.setTransactionSuccessful();
            } catch (Exception e) {
               // Log.d(TAG, "Error while trying to delete all posts and users");
            } finally {
                db.endTransaction();
            }
        }
    // PostsDatabaseHelper dbH= new PostsDatabaseHelper(this);
    }



    Favourites.java

    import android.widget.ImageView;

    /**
     * Created by SouRAV on 4/2/2016.
     */
    public class Favourites {
        public  ImageView deleteButton;
        public  ImageView editButton;
        //public int icon;
        public String title;
        public String fid;
        //long favId;
        public Favourites(){
            super();
        }

        public Favourites(ImageView deleteButton, ImageView editButton, String title,String fid) {
            super();
            this.deleteButton = deleteButton;
            this.editButton= editButton;
            this.title = title;
            this.fid= fid;
        }
    }

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://ift.tt/nIICcg"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFFFFF">

    <ListView
        android:id="@+id/listView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</LinearLayout>

[![enter image description here][1]][1]


  [1]: http://ift.tt/1W9Iveb


I want here the List of Favorites items to be displayed with Title and Text


listview_item_row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://ift.tt/nIICcg"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp">

    <ImageButton android:id="@+id/deleteButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"

        android:text= "Delete"
        android:src="@drawable/delete_button"/>
    <ImageButton android:id="@+id/editButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"

        android:text="Edit"
        android:src="@drawable/edit_button"/>

    <TextView android:id="@+id/txtTitle"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:layout_alignParentTop="true"
        android:layout_alignParentBottom="true"
        android:textStyle="bold"
        android:textSize="22dp"
        android:textColor="#000000"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp" />

</LinearLayout>

Aucun commentaire:

Enregistrer un commentaire