当我尝试在模拟器中运行我的应用程序时,我收到错误消息Unfortunately the application has stopped working
。
这是应用程序的数据库处理程序
package com.nkannan.contactmanager;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import java.util.ArrayList;
import java.util.List;
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "contactManager",
TABLE_CONTACTS = "contacts",
KEY_ID = "id",
KEY_NAME = "name",
KEY_PHONE = "phone",
KEY_EMAIL = "email",
KEY_ADDRESS = "address",
KEY_IMAGEURI = "imageUri";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE" + TABLE_CONTACTS + "(" + KEY_ID + "INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + "TEXT," + KEY_PHONE + "TEXT," + KEY_EMAIL + "TEXT," + KEY_ADDRESS + "TEXT," + KEY_IMAGEURI + "TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + TABLE_CONTACTS);
onCreate(db);
}
public void createContact(Contact contact) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PHONE, contact.getPhone());
values.put(KEY_EMAIL, contact.getEmail());
values.put(KEY_ADDRESS, contact.getAddress());
values.put(KEY_IMAGEURI, contact.get_imageUri().toString());
db.insert(TABLE_CONTACTS, null, values);
}
public Contact getContact(int id) {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[]{KEY_ID, KEY_NAME, KEY_PHONE, KEY_EMAIL, KEY_ADDRESS, KEY_IMAGEURI}, KEY_ID + "=?", new String[]{String.valueOf(id)}, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
assert cursor != null;
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), Uri.parse(cursor.getString(5)));
db.close();
cursor.close();
return contact;
}
public void deleteContact(Contact contact) {
SQLiteDatabase db = getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + "=?", new String[]{String.valueOf(contact.getId())});
db.close();
}
public int getContactsCount() {
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_CONTACTS, null);
int count = cursor.getCount();
db.close();
cursor.close();
return count;
}
public int updateContact(Contact contact) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PHONE, contact.getPhone());
values.put(KEY_EMAIL, contact.getEmail());
values.put(KEY_ADDRESS, contact.getAddress());
values.put(KEY_IMAGEURI, contact.get_imageUri().toString());
return db.update(TABLE_CONTACTS, values, KEY_ID + "=?", new String[]{String.valueOf(contact.getId())});
}
public List<Contact> getAllContacts(){
List<Contact> contacts = new ArrayList<>();
SQLiteDatabase db = getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_CONTACTS, null);
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4), Uri.parse(cursor.getString(5)));
contacts.add(contact);
}
while (cursor.moveToNext());
cursor.close();
}
return contacts;
}
}
//这是主要的活动类
package com.nkannan.contactmanager;
import android.annotation.TargetApi;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ActionBarActivity {
EditText nameTxt, phoneTxt, emailTxt, addressTxt;
ImageView contactImageImgView;
List<Contact> Contacts = new ArrayList<>();
ListView contactListView;
Uri imageUri = Uri.parse("android.resource://com.nkannan.contactManager/drawable/no_images.jpg");
DatabaseHandler dbHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameTxt = (EditText) findViewById(R.id.txtName);
phoneTxt = (EditText) findViewById(R.id.txtPhone);
emailTxt = (EditText) findViewById(R.id.txtEmail);
addressTxt = (EditText) findViewById(R.id.txtAddress);
contactListView = (ListView) findViewById(R.id.listView);
contactImageImgView = (ImageView) findViewById(R.id.imgViewContactImage);
dbHandler = new DatabaseHandler(getApplicationContext());
TabHost tabHost = (TabHost) findViewById(R.id.tabHost);
tabHost.setup();
TabHost.TabSpec tabSpec = tabHost.newTabSpec("creator");
tabSpec.setContent(R.id.tabCreator);
tabSpec.setIndicator("Creator");
tabHost.addTab(tabSpec);
tabSpec = tabHost.newTabSpec("list");
tabSpec.setContent(R.id.tabContactList);
tabSpec.setIndicator("List");
tabHost.addTab(tabSpec);
final Button addBtn = (Button) findViewById(R.id.btnAdd);
addBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Contact contact = new Contact(dbHandler.getContactsCount(),String.valueOf(nameTxt.getText()),String.valueOf(phoneTxt.getText()),String.valueOf(emailTxt.getText()),String.valueOf(addressTxt.getText()),imageUri);
dbHandler.createContact(contact);
Contacts.add(contact);
populateList();
Toast.makeText(getApplicationContext(),nameTxt.getText().toString() + "Your Contact has been created",Toast.LENGTH_SHORT).show();
}
});
nameTxt.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
addBtn.setEnabled(!nameTxt.getText().toString().trim().isEmpty());
}
@Override
public void afterTextChanged(Editable s) {
}
});
contactImageImgView.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Contact Image"), 1);
}
});
List<Contact> addableContacts = dbHandler.getAllContacts();
int contactCount = dbHandler.getContactsCount();
for (int i = 0; i<contactCount; i++) {
Contacts.add(addableContacts.get(i));
}
if (!addableContacts.isEmpty())
populateList();
}
public void onActivityResult(int reqCode, int resCode, Intent data) {
if (resCode == RESULT_OK) {
if (reqCode == 1)
imageUri = data.getData();
contactImageImgView.setImageURI(data.getData());
}
}
private void populateList(){
ArrayAdapter<Contact> adapter = new ContactListAdapter();
contactListView.setAdapter(adapter);
}
private class ContactListAdapter extends ArrayAdapter<Contact>{
public ContactListAdapter(){
super(MainActivity.this, R.layout.listview_item, Contacts);
}
@Override
public View getView(int position, View view, ViewGroup parent){
if (view == null)
view = getLayoutInflater().inflate(R.layout.listview_item, parent,false);
Contact currentContact = Contacts.get(position);
TextView name = (TextView) view.findViewById(R.id.contactName);
name.setText(currentContact.getName());
TextView phone = (TextView) view.findViewById(R.id.phoneNumber);
phone.setText(currentContact.getPhone());
TextView email = (TextView) view.findViewById(R.id.emailAddress);
email.setText(currentContact.getEmail());
TextView address = (TextView) view.findViewById(R.id.cAddress);
address.setText(currentContact.getAddress());
ImageView ivContactImage = (ImageView) view.findViewById(R.id.ivContactImage);
ivContactImage.setImageURI(currentContact.get_imageUri());
return view;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
package com.nkannan.contactmanager;
import android.net.Uri;
public class Contact {
private String _name,_phone,_email,_address;
private Uri _imageUri;
private int _id;
public Contact (int id, String name, String phone, String email, String address, Uri imageUri){
_id = id;
_name = name;
_phone = phone;
_email = email;
_address = address;
_imageUri = imageUri;
}
public int getId(){return _id;}
public String getName(){return _name;}
public String getPhone(){return _phone;}
public String getEmail(){return _email;}
public String getAddress(){return _address;}
public Uri get_imageUri() {return _imageUri;}
// logcat消息
05-28 11:57:54.408 2446-2453/com.nkannan.contactmanager W/art﹕ Suspending all threads took: 5.103ms
05-28 11:57:54.513 2446-2446/com.nkannan.contactmanager E/SQLiteLog﹕ (1) no such table: contacts
05-28 11:57:54.514 2446-2446/com.nkannan.contactmanager D/AndroidRuntime﹕ Shutting down VM
--------- beginning of crash
05-28 11:57:54.514 2446-2446/com.nkannan.contactmanager E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.nkannan.contactmanager, PID: 2446
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.nkannan.contactmanager/com.nkannan.contactmanager.MainActivity}: android.database.sqlite.SQLiteException: no such table: contacts (code 1): , while compiling: SELECT * FROM contacts
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: android.database.sqlite.SQLiteException: no such table: contacts (code 1): , while compiling: SELECT * FROM contacts
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1255)
at com.nkannan.contactmanager.DatabaseHandler.getAllContacts(DatabaseHandler.java:115)
at com.nkannan.contactmanager.MainActivity.onCreate(MainActivity.java:109)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
05-28 11:58:06.579 2446-2453/com.nkannan.contactmanager W/art﹕ Suspending all threads took: 171.174ms
05-28 11:58:19.382 2446-2453/com.nkannan.contactmanager W/art﹕ Suspending all threads took: 30.624ms
05-28 11:58:24.047 2446-2453/com.nkannan.contactmanager W/art﹕ Suspending all threads took: 5.010ms
logcat错误消息说明了这一点
SQLiteException: no such table: contact (code 1): while compiling: SELECT * FROM contacts
出现此错误的原因是什么?