在android中的ListView中显示数据库的数据

时间:2015-03-15 14:47:45

标签: android database sqlite listview

我使用此代码,在AddActivity.java中点击“insertBTN”之后,在MyActivity类的ListView中没有显示任何内容。请帮助我问题在哪里,我该如何解决?非常感谢。

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 :(用于列表视图)

 <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>

最后,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; }

更新: “getWritableDatabase”方法存在问题, enter image description here 当我按下“编辑意图设置”时,此窗口打开。 enter image description here

我也检查了我的SQLliteOpenHelper.class

// IntelliJ API从类文件生成的反编译器存根源   //无法实现方法

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){/ *编译代码* /}

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 */ }

}

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

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

     [some code left out]

     @Override
     public void onResume() {
         super.onResume();
         listView.getAdapter().notifyDataSetChanged();        
     }
}