1

I have a ListActivity in which i am population a dialog box for picking contact info and picking Date and Time . In order to generate a notification on that time . I have done it and all the data is showing in ListView .

so what i want to do is as user pick and sets the time for notification the listView row data should store in database (sqlite). and when user start the activity the stored data can be shown to user . so users can see their notifications plan ..

now that i have listViews implemented i don't know how to store and retrieve data in sqlite .. i have searched and tried many tutorials but nothing is working in this context .

i am sharing my code its a bit rough . but i will highlight where the data is and from there how can store it to database.

here is my notification class:

    public class noticall extends ListActivity {


    CustomDateTimePicker custom;
    TextView tv,tv1;
    EditText ed;
    String store;
    static String Names;
    public static final int PICK_CONTACT = 1;
    String [] adi ;
    String [] adi1 ;
    String [] adi2 ;
    String [] adi3 ;
    static int incre=0;
    ArrayList<String> myrows = new ArrayList<String>();
    ArrayList<String> time1 = new ArrayList<String>();
    ArrayList<String> name1 = new ArrayList<String>(); 
    ArrayList<String> number1 = new ArrayList<String>();
    private PendingIntent pendingIntent;
    ListView listview;
    String temp1 ,temp2 ;
    int x=0; 
    OnItemClickListener listener;
    String Date,Time,Name,Number;
    MyNotiAdapter adp;


    private SQLiteAdapter mySQLiteAdapter;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.notify);
            listview = (ListView) findViewById(android.R.id.list);

           listview.setDividerHeight(2);

           // mySQLiteAdapter = new SQLiteAdapter(noticall.this);

    custom = new CustomDateTimePicker(noticall.this,new CustomDateTimePicker.ICustomDateTimeListener() {

               @Override
               public void onCancel() { 
                   finish();
               }


               @Override
               public void onSet(Dialog dialog, Calendar calendarSelected,Date dateSelected, int year, String monthFullName,
                            String monthShortName, int monthNumber, int date,
                            String weekDayFullName, String weekDayShortName,
                            int hour24, int hour12, int min, int sec,
                            String AM_PM) {

                      Calendar calendar =  Calendar.getInstance();
                      calendar.set(year, monthNumber, date, hour24,  min, 0);

                      long when = calendar.getTimeInMillis();         // notification time

                      Intent myIntent = new Intent(noticall.this, MyReceiver.class);
                      pendingIntent = PendingIntent.getBroadcast(noticall.this, 0, myIntent,0);

                      AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
                      alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);


        Date = calendarSelected.get(Calendar.DAY_OF_MONTH) + "/" + (monthNumber+1) + "/" +year; 
        Time = hour12 + ":" + min + " " + AM_PM;

        Log.e("Timeee", Time+"");


        setlisto(Date);


        //Toast.makeText(noticall.this, store, Toast.LENGTH_SHORT).show();

           }
    });      



            custom.set24HourFormat(false);
            custom.setDate(Calendar.getInstance());



                findViewById(R.id.button_date).setOnClickListener(
                    new OnClickListener() {
                        @Override
                        public void onClick(View v) {



                        Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                        startActivityForResult(intent,PICK_CONTACT);
                        custom.showDialog();
                        incre++;
                        }
                    });


         //  if(adi!=null)
                read_db();



    }


     @Override
     protected void onActivityResult(int requestCode, int resultCode, Intent data)
     {
       super.onActivityResult(requestCode, resultCode, data);

        if(resultCode != RESULT_CANCELED){

            if (requestCode == 1)
            {
                // Get the URI that points to the selected contact
                Uri contactUri = data.getData();

                // We only need the NUMBER column, because there will be only one row in the result
                String[] projection = {ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.CONTACT_ID};

                String[] segments = contactUri.toString().split("/");
                String id = segments[segments.length - 1];

                // Perform the query on the contact to get the NUMBER column
                // We don't need a selection or sort order (there's only one result for the given URI)
                // CAUTION: The query() method should be called from a separate thread to avoid blocking
                // your app's UI thread. (For simplicity of the sample, this code doesn't do that.)
                // Consider using CursorLoader to perform the query.
                Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null, null, null);
                cursor.moveToFirst();
                while (!cursor.isAfterLast())
                {
                    int cid = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID);
                    String contactid = cursor.getString(cid);

                    if (contactid.equals(id))
                    {
                        // Retrieve the phone number from the NUMBER column
                        int column = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                        String number = cursor.getString(column);

                        // Retrieve the contact name from the DISPLAY_NAME column
                        int column_name = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
                        String name = cursor.getString(column_name);

                        // Do something with the phone number...
                       // Toast.makeText(this, "I added the Contact: \n" + name + " " + number, Toast.LENGTH_SHORT).show();

                       // ed.setText(name+" - "+number);

                      Name=  Names=name;
                      Number =number;  



                    }

                 cursor.moveToNext();
                }
                cursor.close();

               }
            }
        }


     public void setlisto(String one ){

     Log.e("setlistoo",one+"");
     myrows.add(one);
     time1.add(Time);
     name1.add(Name);
     number1.add(Number);
      adi=myrows.toArray(new String[myrows.size()]);
     adi1=time1.toArray(new String[time1.size()]);
     adi2=name1.toArray(new String[name1.size()]);
     adi3=number1.toArray(new String[number1.size()]);

     mySQLiteAdapter = new SQLiteAdapter(noticall.this);
     mySQLiteAdapter.openToWrite();
     mySQLiteAdapter.deleteAll();

     mySQLiteAdapter.insert(adi,adi1,adi2,adi3);

     listview.setAdapter(new MyNotiAdapter(noticall.this, adi,adi1,adi2,adi3));
     x++;


     mySQLiteAdapter.close();


  }

     public void read_db(){

         /*
             *  Open the same SQLite database
             *  and read all it's content.
             */

         Log.e("jsahbdv", "munda agaya medaan men hay jamaalo");

            mySQLiteAdapter = new SQLiteAdapter(this);
            mySQLiteAdapter.openToRead();

            Cursor cursor = mySQLiteAdapter.queueAll();
            startManagingCursor(cursor);

            String[] from = new String[]{SQLiteAdapter.KEY_Name,SQLiteAdapter.KEY_Number,SQLiteAdapter.KEY_Date,SQLiteAdapter.KEY_Time};
            int[] to = new int[]{R.id.person,R.id.edu,R.id.label,R.id.tym};

            SimpleCursorAdapter cursorAdapter =
                    new SimpleCursorAdapter(this, R.layout.row2, cursor, from, to);

            listview.setAdapter(cursorAdapter);

            mySQLiteAdapter.close();







     }


}

my SQLiteAdapter class:

    public class SQLiteAdapter {

    public static final String MYDATABASE_NAME = "MY_DATABASE";
    public static final String MYDATABASE_TABLE = "MY_TABLE";
    public static final int MYDATABASE_VERSION = 1;
    public static final String KEY_ID = "_id";
    public static final String KEY_Name = "Name";
    public static final String KEY_Number = "Number";
    public static final String KEY_Date = "Date";
    public static final String KEY_Time = "Time";



    //create table MY_DATABASE (ID integer primary key, Content text not null);
    private static final String SCRIPT_CREATE_DATABASE =
        "create table " + MYDATABASE_TABLE + " ("
        + KEY_ID + " integer primary key autoincrement, "
        + KEY_Name + " text not null, " 
        + KEY_Number + " text not null, " 
        + KEY_Date + " text not null, " 
        + KEY_Time + " text not null);";


    private SQLiteHelper sqLiteHelper;
    private SQLiteDatabase sqLiteDatabase;

    private Context context;

    public SQLiteAdapter(Context c){
        context = c;
    }

    public SQLiteAdapter openToRead() throws android.database.SQLException {
        sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
        sqLiteDatabase = sqLiteHelper.getReadableDatabase();
        return this;    
    }

    public SQLiteAdapter openToWrite() throws android.database.SQLException {
        sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
        sqLiteDatabase = sqLiteHelper.getWritableDatabase();
        return this;    
    }

    public void close(){
        sqLiteHelper.close();
    }

    public long insert(String[] content,String[] content1,String[] content2,String[] content3){

        ContentValues contentValues = new ContentValues();
        contentValues.put(KEY_Name, content.toString());
        contentValues.put(KEY_Number, content1.toString());
        contentValues.put(KEY_Date, content2.toString());
        contentValues.put(KEY_Time, content3.toString());
        return sqLiteDatabase.insert(MYDATABASE_TABLE, null, contentValues);
    }

    public int deleteAll(){
        return sqLiteDatabase.delete(MYDATABASE_TABLE, null, null);
    }

    public Cursor queueAll(){
        String[] columns = new String[]{KEY_ID, KEY_Name, KEY_Number, KEY_Date, KEY_Time};
        Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,null, null, null, null, null);

        return cursor;
    }

    public class SQLiteHelper extends SQLiteOpenHelper {

        public SQLiteHelper(Context context, String name,
                CursorFactory factory, int version) {
            super(context, name, factory, version);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            // TODO Auto-generated method stub
            db.execSQL(SCRIPT_CREATE_DATABASE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO Auto-generated method stub

        }

    }

}

My point is as user add list rows for notifications it should also be inserted in database and later when activity is initiated the stored notification data must displayed and later i will implement deleting it from listview and from database.

Table should contain following columns:


| ID | NAME | NUMBER | DATE | TIME |


If someone can help me with sample code or refactor this code for success. My skills in database are really weak .. it will be appreciatable. Thanks

cmon guys i really need help in this please.

error

07-16 11:35:58.140: E/AndroidRuntime(5252): FATAL EXCEPTION: main
07-16 11:35:58.140: E/AndroidRuntime(5252): Process: org.avatarsipphone.sipua, PID: 5252
07-16 11:35:58.140: E/AndroidRuntime(5252): java.lang.RuntimeException: Unable to resume activity {org.avatarsipphone.sipua/org.avatarsipphone.sipua.ui.noticall}: java.lang.IllegalStateException: trying to requery an already closed cursor  android.database.sqlite.SQLiteCursor@520f4d5
07-16 11:35:58.140: E/AndroidRuntime(5252):     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3103)
07-16 11:35:58.140: E/AndroidRuntime(5252):     at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3134)
07-16 11:35:58.140: E/AndroidRuntime(5252):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1388)
07-16 11:35:58.140: E/AndroidRuntime(5252):     at android.os.Handler.dispatchMessage(Handler.java:102)
07-16 11:35:58.140: E/AndroidRuntime(5252):     at android.os.Looper.loop(Looper.java:148)
07-16 11:35:58.140: E/AndroidRuntime(5252):     at android.app.ActivityThread.main(ActivityThread.java:5417)
07-16 11:35:58.140: E/AndroidRuntime(5252):     at java.lang.reflect.Method.invoke(Native Method)
07-16 11:35:58.140: E/AndroidRuntime(5252):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
07-16 11:35:58.140: E/AndroidRuntime(5252):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
07-16 11:35:58.140: E/AndroidRuntime(5252): Caused by: java.lang.IllegalStateException: trying to requery an already closed cursor  android.database.sqlite.SQLiteCursor@520f4d5
07-16 11:35:58.140: E/AndroidRuntime(5252):     at android.app.Activity.performRestart(Activity.java:6296)
07-16 11:35:58.140: E/AndroidRuntime(5252):     at android.app.Activity.performResume(Activity.java:6319)
07-16 11:35:58.140: E/AndroidRuntime(5252):     at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3092)
07-16 11:35:58.140: E/AndroidRuntime(5252):     ... 8 more
Addi.Star
  • 475
  • 2
  • 15
  • 36
  • Please see[Related question like this](http://stackoverflow.com/questions/23284889/i-want-to-store-the-list-of-item-displayed-in-listview-to-android-sqlite-databas) – RoHiT Jul 15 '16 at 12:01
  • @RoHiT i have checked this link and tried to implement it i have edited my question and provided the dbhandler class . i dont know how to store and retrieve data in listview from database . and the link also doesnot provide any info about retrieving data. please i need help in this . i will be very thankful to you – Addi.Star Jul 15 '16 at 13:18
  • A CursorAdapter can help you display data from a database. In any case, your query result has 0 columns, so you can't access it – OneCricketeer Jul 15 '16 at 13:35
  • Also, please try a [mcve]. Or follow a working example from the Android Documentation – OneCricketeer Jul 15 '16 at 13:36
  • how can i implement cursor adapter in my above code ? – Addi.Star Jul 15 '16 at 15:33

2 Answers2

0

@Addi.Star Please see following program,

-SQLiteHelper

public static final String DATABASE_NAME="student.db";
public static final String TABLE_NAME="stud_info";
public static final String col1="ID";
public static final String col2="NAME";


public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);
    //SQLiteDatabase db=this.getWritableDatabase();
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("create table " + TABLE_NAME + " ( Id INTEGER PRIMARY KEY,NAME TEXT ) ");
    Log.e("DB CREATE","DATABASE CREATE");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

public boolean insertData(String id,String name){
    SQLiteDatabase db=this.getWritableDatabase();
    ContentValues contex=new ContentValues();
    contex.put(col1,id);
    contex.put(col2,name);
    long result=db.insert(TABLE_NAME,null,contex);
    if(result==-1)
    {
        return false;
    }else{
        return true;
    }
}

public Cursor getAllData()
{
    SQLiteDatabase db=this.getWritableDatabase();
    Cursor res=db.rawQuery("select * from "+TABLE_NAME,null);
    return res;
}

-and this is function in class or adapter where you can retrieve data from SQlite database

           Cursor res=myDb.getAllData();

            if(res.getCount() == 0){

                ShowMessage("Error", "NOthing found");
                return;
            }

            StringBuffer strBfr=new StringBuffer();
            while (res.moveToNext()){
                strBfr.append("Id :"+ res.getString(0) + "\n");
                strBfr.append("Name:" + res.getString(1) + "\n");

            }
            ShowMessage("Data", strBfr.toString());
RoHiT
  • 372
  • 3
  • 12
  • Also see, http://www.mysamplecode.com/2012/07/android-listview-cursoradapter-sqlite.html – RoHiT Jul 16 '16 at 05:16
  • i have tried to implement the way sqlite supposed to work.. but it is giving error . i have edited and updated the code in question . i dont know why its giving error now . i spend many hours to get success in this but still unable .. Kindly check now what i am doing wrong . i hope you understand my code now . – Addi.Star Jul 16 '16 at 06:44
  • i have checked your answer as well but the way i have done it whats wrong in it . please check **read_db()** method – Addi.Star Jul 16 '16 at 06:47
  • what i want is when first activity starts list is empty . now with click on button i add item to listview the item is contact name number and picks time date and time successfully now when the listview have one item it should also store into database.. so that later i start application and can check which items are there i previously added . later i will implement deleting them one by one . but it is not happening spending nights on it ... please help me in this – Addi.Star Jul 16 '16 at 08:47
  • after spending a lot of time i made it work .. your solution helped me a lot . it works.. thanks for helping rohit.. – Addi.Star Jul 18 '16 at 09:36
  • i am facing some problem after this can you check it here aswel http://stackoverflow.com/questions/38435531/android-setting-sqlite-database-values-in-an-listview – Addi.Star Jul 18 '16 at 11:50
-1

open DB with RootExplorer of your app to see ,If data is inserting in it or not, may be error is due to not rows retuen when SELECT.

theshivamlko
  • 271
  • 2
  • 10
  • i cannot access to RootExplorer... i have no idea how to handle listview in sqlite database .. kindly provide me with simple working code so that i can make it work . thanks – Addi.Star Jul 15 '16 at 15:23