2017-12-27 434 views
0

我的問題是應用程序崩潰,它顯示,不幸的是,應用程序已停止。使用SQLite保存數據並將其添加到ListView

MainActivity.java

public class MainActivity extends AppCompatActivity { 


DatabaseHelper myDB; 
Button btnAdd; 
Button btnList; 
TextView tvView; 
EditText editText; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    btnAdd = (Button) findViewById(R.id.btnAdd); 
    btnList = (Button) findViewById(R.id.btnList); 
    tvView = (TextView) findViewById(R.id.Textview); 
    editText = (EditText) findViewById(R.id.editText); 
    myDB=new DatabaseHelper(this); 


    btnAdd.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      String newEntry = editText.getText().toString(); 
      if (newEntry.length() != 0) { 
       AddData(newEntry); 
       editText.setText(""); 
      } else { 
       Toast.makeText(MainActivity.this, "You must put something in the text field", Toast.LENGTH_LONG).show(); 
      } 
     } 

    }); 
    btnList.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      Intent intent = new Intent(MainActivity.this, ListDataActivity.class); 
      startActivity(intent); 
     } 
    }); 
} 


public void AddData(String newEntry) { 
    boolean insertData = myDB.addData(newEntry); 
    // check inserted successfully 
    if (insertData == true) { 
     Toast.makeText(MainActivity.this, "Successfully Entered Data!", Toast.LENGTH_LONG).show(); 
    } else { 
     Toast.makeText(MainActivity.this, "Something went wrong", Toast.LENGTH_LONG).show(); 
    } 
} 

}

ListAcitivity.java

公共類ListDataActivity延伸AppCompatActivity {

DatabaseHelper myDB; 
ListView listView; 
ArrayAdapter<String>listAdapter; 


@Override 
protected void onCreate(Bundle savedInstanceState){ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.list_layout); 

    listView=(ListView)findViewById(R.id.listView); 
    myDB= new DatabaseHelper(this); 


    //populate an ArrayList<String> from the databases and then view it 
    ArrayList<String> theList=new ArrayList<>(); 
    Cursor data=myDB.getListContent(); 

    if(data.getCount()==0){ 
     Toast.makeText(ListDataActivity.this,"The database was empty",Toast.LENGTH_LONG).show(); 
    }else{ 
     while(data.moveToNext()){ 
      theList.add(data.getString(1)); 
      listAdapter=new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,theList); 
      listView.setAdapter(listAdapter); 
     } 
    } 
} 

DatabaseHelper.java

公共類DatabaseHelper延伸SQLiteOpenHelper {

public static final String DATABASE_NAME = "mylist.db"; 
public static final String TABLE_NAME = "mylist_data"; 
public static final String COL1 = "ID"; 
public static final String COL2 = "ITEM1"; 

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

@Override 
public void onCreate(SQLiteDatabase db) { 
    String createTable="CREATE TABLE"+ TABLE_NAME +"(ID INTEGER PRIMARY KEY AUTOINCREMENT,"+ 
      "ITEM1 TEXT)"; 
      db.execSQL(createTable); 
    db.close(); 


} 

@Override 
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
    db.execSQL("DROP IF TABLE EXITS "+ TABLE_NAME); 
    onCreate(db); 
    db.close(); 



} 
public boolean addData(String item1) { 
    SQLiteDatabase db = this.getWritableDatabase(); 
    ContentValues contentValues = new ContentValues(); 
    contentValues.put(COL2, item1); 


    long result = db.insert(TABLE_NAME, null, contentValues); 

    //if date as instered incorrectly it will return -1 
    if (result == -1) { 
     return false; 
    } else { 
     return true; 
    } 
} 
    /** 
    * Return all the data from database 
    * @return 
    */ 
    public Cursor getListContent() { 
    SQLiteDatabase db = this.getWritableDatabase(); 
    Cursor data =db.rawQuery("SELECT * FROM " + TABLE_NAME,null); 
    return data; 


} 

}

logcat的節目

7月12日至27日:29:26.268 24636-24636/sg.edu.rp.c346.todolist E/AndroidRuntime :致命例外:main 進程:sg.edu.rp.c346.todolist,PID:24636 java.lang.IllegalStateException:嘗試重新打開已關閉的對象:SQLiteDatabase:/data/data/sg.edu。 rp.c346.todolist/databases/mylist.db 在android.database.sqlite.SQLiteClosable.acquireReference(SQLiteClosable.java:55) at android.database.sqlite.SQLiteDatabase.endTransaction(SQLiteDatabase.java:520) at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java :263) at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164) at sg.edu.rp.c346.todolist.DatabaseHelper.addData(DatabaseHelper.java:45) at sg.edu.rp .c346.todolist.MainActivity.AddData(MainActivity.java:58) at sg.edu.rp.c346.todolist.MainActivity $ 1.onClick(MainActivity.java:39) at android.view.View.performClick(View。 java:4438) at android.view.View $ PerformClick.run(View.java:18422) at android.os.Handler.handleCallback(Handler.java:733) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5017) at java.lang.reflect.Method.invokeNative(Native Method) at java .lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:779) at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:595) at dalvik.system.NativeStart.main(Native Method) 12-27 07:29:28.078 24636-24636 /?我/過程:發送信號。 PID:24636 SIG:9

回答

0

您不應該close()SQLiteDatabase給您SQLiteOpenHelperonCreate()onUpgrade()。只有你自己獲得的close()數據庫句柄。

+0

謝謝。它現在工作! – Junhao

1

它看起來像你沒有初始化你的myDB實例。

在嘗試將條目添加到LocalDB之前,請在您的onCreate方法的某處撥打myDB = new DatabaseHelper(this)

+0

如何初始化myDB實例。 – Junhao

+0

編輯我的答案 –

+0

保護無效onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnAdd =(Button)findViewById(R.id.btnAdd); btnList =(Button)findViewById(R.id.btnList); tvView =(TextView)findViewById(R.id.Textview); editText =(EditText)findViewById(R.id.editText); myDB = new DatabaseHelper(this); – Junhao

0

在訪問它之前,您必須初始化myDB變量。在你的MainActivity.java中你沒有初始化Helper類。

myDB= new DatabaseHelper(this); 

只要做到這一點。 也修改這個條件

if (editText.length() != 0) { // Change this to newEntry.length() !=0 
      AddData(newEntry); 
      editText.setText(""); 
     } else { 
      Toast.makeText(MainActivity.this, "You must put something in the text field", Toast.LENGTH_LONG).show(); 
     } 

希望這會起作用。

+0

我在哪裏把initalize myDB? – Junhao

+0

在MainActivity - > onCreate方法中。 –

+0

保護無效onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnAdd =(Button)findViewById(R.id.btnAdd); btnList =(Button)findViewById(R.id.btnList); tvView =(TextView)findViewById(R.id.Textview); editText =(EditText)findViewById(R.id.editText); myDB = new DatabaseHelper(this); – Junhao

相關問題