-1

i use this codes, nut after i click "insertBTN" in AddActivity.java, nothing shows in my ListView in MyActivity class. please help me where is the problem and how can i solve it? thanks alot.

MyActivity.java:

 public class MyActivity extends Activity {
    private ListView listView;
    private DataBase myDB;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    myDB =new DataBase(this);
    ArrayList total =myDB.getAll();

    ArrayAdapter arrayAdapter = new ArrayAdapter(this,R.layout.list_item,total);

    listView = (ListView) findViewById(R.id.ListView);
    listView.setAdapter(arrayAdapter);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
            // TODO Auto-generated method stub
            int id_To_Search = arg2 + 1;
            Bundle dataBundle = new Bundle();
            dataBundle.putInt("id", id_To_Search);
            Intent intent = new Intent(getApplicationContext(),AddActivity.class);
            intent.putExtras(dataBundle);
            startActivity(intent);
        }
    });
}

   //***************** Menu Button for filling DataBase
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.add, menu);
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{   super.onOptionsItemSelected(item);
    switch(item.getItemId())
    {
        case R.id.add_menu:
            Bundle dataBundle = new Bundle();
            dataBundle.putInt("id", 0);
            Intent intent = new Intent(getApplicationContext(),AddActivity.class);
            intent.putExtras(dataBundle);
            startActivity(intent);
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

main.xml:

  <ListView android:layout_width="match_parent"
          android:layout_height="250dp"
          android:id="@+id/ListView"
          android:layout_gravity="right">
</ListView>

list_item.xml: (for list view)

 <TextView android:layout_width="75dp"
          android:layout_height="200dp"
          android:id="@+id/total_vow_text"
          android:textColor="#ff6400"
          android:textSize="25sp"
          android:layout_gravity="right"/>

AddActivity.java:

 public class AddActivity extends Activity {
    private EditText addNUM;
    private EditText addTEXT ;

    private Button insertBTN;
    private Button deleteBTN;

    private DataBase myDB;
    private int id_To_Update=0;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.add_activity);
    myDB = new DataBase(this);

    addNUM = (EditText) findViewById(R.id.addNum);
    addTEXT  = (EditText) findViewById(R.id.addTEXT);

    insertBTN = (Button) findViewById(R.id.insert);
    deleteBTN = (Button) findViewById(R.id.deleteBTN);

    Bundle extras = getIntent().getExtras();
    if(extras !=null)
    {   int Value = extras.getInt("id");
        if(Value>0){
            //means this is the view part not the add contact part.
            Cursor rs = myDB.getData(Value);
            id_To_Update = Value;
            rs.moveToFirst();
            String number = rs.getString(rs.getColumnIndex(DataBase.TEST_COLUMN_NUMBER));
            String text = rs.getString(rs.getColumnIndex(DataBase.TEST_COLUMN_TEXT));

            if (!rs.isClosed()){
                rs.close();
            }
            addNUM.setText((CharSequence)number);
            addTEXT.setText((CharSequence)text);
        }
    }
}

public void run(View view){
    Bundle extras = getIntent().getExtras();
    if(extras !=null)
    {   int Value = extras.getInt("id");
        if(Value>0){
            if(myDB.updating(id_To_Update,addNUM.getText().toString(), addTEXT.getText().toString())){
                Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getApplicationContext(),MyActivity.class);
                startActivity(intent);
            }else{
                Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show();
            }
        }else{
            if(myDB.inserting(addNUM.getText().toString(), addTEXT.getText().toString())){
                Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(getApplicationContext(), "not done", Toast.LENGTH_SHORT).show();
            }
            Intent intent = new Intent(getApplicationContext(),MyActivity.class);
            startActivity(intent);
        }
    }
}

add_activity.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical"
          android:gravity="right"
          android:layout_gravity="center_horizontal"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:background="#000000">


<EditText android:layout_width="100dp"
          android:layout_height="50dp"
          android:layout_gravity="center_horizontal"
          android:gravity="right|center_vertical"
          android:id="@+id/addNum"
          android:hint="Type Number"
          android:layout_marginTop="10dp"
          android:layout_marginBottom="10dp"
          android:inputType="number"/>


<EditText android:layout_width="150dp"
          android:layout_height="50dp"
          android:hint="Type Text"
          android:layout_gravity="center_horizontal"
          android:gravity="right|center_vertical"
          android:id="@+id/addTEXT"
          android:layout_marginTop="10dp"
          android:layout_marginBottom="15dp"
          android:inputType="text"/>



<LinearLayout android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:orientation="horizontal"
              android:layout_gravity="center_horizontal">

    <Button android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/deleteBTN"
            android:background="@android:drawable/ic_delete"
            />

    <Button android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/insert"
            android:background="@drawable/tick"
            android:onClick="run"/>


</LinearLayout>

and at last,DataBase.java:

  public class DataBase extends SQLiteOpenHelper {
     public static final String DATABASE_NAME = "MyDBName.db";
     public static final String TABLE_NAME = "test";
     public static final String TEST_COLUMN_ID = "id";
     public static final String TEST_COLUMN_NUMBER = "number";
     public static final String TEST_COLUMN_TEXT = "text";

   public DataBase(Context context) {
    super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    db.execSQL(
            "create table test " + "(id integer primary key, number text,text text)"
    );
}

@Override
public void onUpgrade(SQLiteDatabase db, int i, int i2) {
    // TODO Auto-generated method stub
    db.execSQL("DROP TABLE IF EXISTS TEST");
    onCreate(db);
}

public boolean inserting (String number, String text)
{   SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();

    contentValues.put("number", number);
    contentValues.put("text", text);

    db.insert("testing", null, contentValues);
    return true;
}

public Cursor getData(int id){
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res =  db.rawQuery( "select * from tests where id="+id+"", null );
    return res;
}
public int numberOfRows(){
    SQLiteDatabase db = this.getReadableDatabase();
    int numRows = (int) DatabaseUtils.queryNumEntries(db, TABLE_NAME);
    return numRows;
}
public boolean updating (Integer id, String number, String text)
{   SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put("number", number);
    contentValues.put("text", text);
    db.update("testing", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
    return true;
}

public Integer deleting (Integer id)
{   SQLiteDatabase db = this.getWritableDatabase();
    return db.delete("testing","id = ? ",
            new String[] { Integer.toString(id) });
}

     public ArrayList getAll(){
        ArrayList total = new ArrayList();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor res =  db.rawQuery("select * from tests", null );
        res.moveToFirst();
     while(res.isAfterLast() == false){
        total.add(res.getString(res.getColumnIndex(TEST_COLUMN_TEXT)));
        res.moveToNext();
    } return total; }

Updating: there is a problem in "getWritableDatabase" method, enter image description here as I press "Edit Intention Settings" ,this window opens. enter image description here

also I check my SQLliteOpenHelper.class :

// IntelliJ API Decompiler stub source generated from a class file // Implementation of methods is not available

package android.database.sqlite;

public abstract class SQLiteOpenHelper { public SQLiteOpenHelper(android.content.Context context, java.lang.String name, android.database.sqlite.SQLiteDatabase.CursorFactory factory, int version) { /* compiled code */ }

public SQLiteOpenHelper(android.content.Context context, java.lang.String name, android.database.sqlite.SQLiteDatabase.CursorFactory factory, int version, android.database.DatabaseErrorHandler errorHandler) { /* compiled code */ }

public java.lang.String getDatabaseName() { /* compiled code */ }

public void setWriteAheadLoggingEnabled(boolean enabled) { /* compiled code */ }

public android.database.sqlite.SQLiteDatabase getWritableDatabase() { /* compiled code */ }

public android.database.sqlite.SQLiteDatabase getReadableDatabase() { /* compiled code */ }

public synchronized void close() { /* compiled code */ }

public void onConfigure(android.database.sqlite.SQLiteDatabase db) { /* compiled code */ }

public abstract void onCreate(android.database.sqlite.SQLiteDatabase sqLiteDatabase);

public abstract void onUpgrade(android.database.sqlite.SQLiteDatabase sqLiteDatabase, int i, int i1);

public void onDowngrade(android.database.sqlite.SQLiteDatabase db, int oldVersion, int newVersion) { /* compiled code */ }

public void onOpen(android.database.sqlite.SQLiteDatabase db) { /* compiled code */ }

}

  • Did you call `notifyDataSetChanged()` on your listview's adapter ? – Jonas Czech Mar 15 '15 at 15:05
  • no, I use this link for writing this code; http://www.tutorialspoint.com/android/android_sqlite_database.htm –  Mar 15 '15 at 15:16
  • That tutorial is bad, very bad. `notifyDataSetChanged()` is not called anywhere. You have to do something like `myListView.getAdapter().notifyDataSetChanged()` after you modify the database. – Jonas Czech Mar 15 '15 at 15:24
  • oh! would you please suggest me the best tutorial? I don't know what's this method? and how to use it? –  Mar 15 '15 at 15:28

1 Answers1

0

Try something like this:

public class MyActivity extends Activity {
     private ListView listView;
     private DataBase myDB;

     [some code left out]

     @Override
     public void onResume() {
         super.onResume();
         listView.getAdapter().notifyDataSetChanged();        
     }
}
Jonas Czech
  • 12,018
  • 6
  • 44
  • 65
  • I write this in MyActivity. but "notifyDataSetChanged" is not recognized. I don't have separate class for ArrayAdapter. I introduce ArrayAdapter in MyActivity.java class. –  Mar 15 '15 at 15:44
  • @MinaDahesh, What do you mean by 'not recognized' ? – Jonas Czech Mar 15 '15 at 15:49
  • it's color is red and shows this note "Cannot resolve this symbol 'notifyDataSetChanged' ". (I use intelij). of course I use ALT+ENTER but nothing happen. –  Mar 15 '15 at 15:56
  • i read it and with regarding to no.3 I write " arrayAdapter.notifyDataSetChanged();" but no list's item is shown! what can I do? –  Mar 17 '15 at 14:18
  • would you please suggest me a tutorial? –  Mar 17 '15 at 14:27
  • @MinaDahesh , [This one](http://androidsolution4u.blogspot.ie/2013/09/android-populate-listview-from-sqlite.html) is better. There is an option to download the full project code at the bottom. – Jonas Czech Mar 17 '15 at 14:41
  • thanks a lot. I use it, but I have some problems, please help me. in AddActivity.java/saveData.method/ getWritableDatabase().(line1), is not recognized. this tool-tip is shown"Non-static method 'getWritableDatabase' can not be referenced from static context". I don't know what its mean!? –  Mar 19 '15 at 12:03
  • @MinaDahesh, I don't know. Did you use the 'download complete project' link at bottom, maybe you can check / compare ? – Jonas Czech Mar 19 '15 at 19:48
  • yes, I download the source code, and write down and customize codes that needed. but I don't know why this error is shown! –  Mar 20 '15 at 09:07
  • I upload 2 images that shows error, solution that InteliJ suggest me. are they enough? please help me, this code is very important for me –  Mar 21 '15 at 11:01
  • I compare "SQLiteOpenHelper.class"s and find that mine isn't as complete as that tutorial. and also it doesn't let me to edit it. this is my SQLiteOpenHelper.class: –  Mar 21 '15 at 11:42
  • .I compare "SQLiteOpenHelper.class" and find out my SQLiteOpenHelper is not as complete as the tutorial. and it doesn't let me to edit it. I write down my "SQLiteOpenHelper.class" above. –  Mar 21 '15 at 12:01
  • @MinaDahesh, Try something like `mDBHelper = new DataBaseClass(this); SqlDb = mDBHelper.getWritableDatabase();` The `SQLiteOpenHelper.class` is not _your_ one, post the actual 'DBHelper` class from your project. – Jonas Czech Mar 22 '15 at 06:32
  • @JonasCz.thanks a lot! it works. may I ask you please give me your email id, for asking question about DataBase nesxt time? –  Mar 27 '15 at 16:26
  • @MinaDahesh, No, Unfortunately I can't give you my email, but I usually see questions tagged 'android-sqlite'. If you _really_ need it, you can `@mention` me (here, otherwise I don't get it), and I will see. Would be nice if you could accept my answer :-). – Jonas Czech Mar 27 '15 at 17:32
  • apologize me for asking question, but I have problem in Editing and DELETing rows of my data base. I want to use EDIT and DELETE buttons in action mode. would you please help me? –  Apr 10 '15 at 13:21
  • @MinaDahesh, Post new question, put your code in it, tell us what you have tried. You have to ues `DataBase.delete()`. – Jonas Czech Apr 10 '15 at 13:45
  • I have 2 questions about spinner in list view that I posted them in link1:http://stackoverflow.com/questions/31592335/using-spinner-on-listview-qith-sql-lite-in-android --- and link2:http://stackoverflow.com/questions/31237539/how-to-use-spinner-for-showing-date-in-sql-lite-in-android/31260358?noredirect=1#comment50947869_31260358------- would you please help me to find out the solution?thanks! –  Jul 23 '15 at 15:56