2015-08-26 6 views
-1

Я написал код. Он не дает ошибок, но он просто не работает.My db app перестает работать

Когда я пытаюсь отладить его, он говорит: К сожалению, ваше приложение остановилось.
Пожалуйста, помогите мне, я новичок в разработке

базе данных Helper Класс

public class DatabaseHandler extends SQLiteOpenHelper { 
private static final int DATABASE_VERSION=1; 
private static final String DATABASE_NAME= "permitManager", 
TABLE_CONTACTS ="contacts", 
KEY_ID = "id", 
KEY_CAR="car", 
KEY_STATUS="status", 
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_CAR + "TEXT," + KEY_STATUS + "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_CAR,contact.getCar()); 
    values.put(KEY_STATUS,contact.getStatus()); 
    values.put(KEY_IMAGEURI, contact.getimageURI().toString()); 
    db.insert(TABLE_CONTACTS,null,values); 
    db.close(); 
} 

public Contact getContact(int id){ 
    SQLiteDatabase db =getReadableDatabase(); 
    Cursor cursor =db.query(TABLE_CONTACTS, new String[]{KEY_ID,KEY_CAR,KEY_STATUS,KEY_IMAGEURI},KEY_ID + "=?" , new String[]{String.valueOf(id)},null,null,null); 
    if(cursor!=null) 
     cursor.moveToFirst(); 
    Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),cursor.getString(1),cursor.getString(2), Uri.parse(cursor.getString(3))); 

    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 getContactCount(){ 
    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_CAR,contact.getCar()); 
    values.put(KEY_STATUS,contact.getStatus()); 
    values.put(KEY_IMAGEURI, contact.getimageURI().toString()); 
    db.insert(TABLE_CONTACTS,null,values); 
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),Uri.parse(cursor.getString(3))); 
      contacts.add(contact); 
     } 
     while (cursor.moveToNext()); 
    } 
    return contacts; 
} 
} 

Основной класс Активность

public class MainActivity extends ActionBarActivity { 


EditText carTxt, statusTxt; 
ImageView contactImageImgView; 
List<Contact> Contacts = new ArrayList<Contact>(); 
ListView contactListView; 
Uri imageUri=null; 
DatabaseHandler dbHandler; 



@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    carTxt = (EditText) findViewById(R.id.txtCar); 
    statusTxt = (EditText) findViewById(R.id.txtStatus); 
    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.Creator); 
    tabSpec.setIndicator("Creator"); 
    tabHost.addTab(tabSpec); 

    tabSpec = tabHost.newTabSpec("List"); 
    tabSpec.setContent(R.id.List); 
    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.getContactCount(),String.valueOf(carTxt.getText()),String.valueOf(statusTxt.getText()),imageUri); 
      dbHandler.createContact(contact); 
      Contacts.add(contact); 
      populateList(); 
      Toast.makeText(getApplicationContext(), carTxt.getText().toString() + " has been add to list", Toast.LENGTH_SHORT).show(); 
     } 
    }); 
    carTxt.addTextChangedListener(new TextWatcher() { 
     @Override 
     public void beforeTextChanged(CharSequence s, int start, int count, int after) { 

     } 

     @Override 
     public void onTextChanged(CharSequence s, int start, int before, int count) { 
      addBtn.setEnabled(!carTxt.getText().toString().trim().isEmpty()); 

     } 

     @Override 
     public void afterTextChanged(Editable s) { 

     } 
    }); 

    contactImageImgView.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      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.getContactCount(); 
    for(int i =0;i< contactcount;i++) { 
     Contacts.add(addableContacts.get(1)); 
    } 
    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 car = (TextView) view.findViewById(R.id.contactname); 
     car.setText(currentContact.getCar()); 
     TextView status = (TextView) view.findViewById(R.id.status); 
     status.setText(currentContact.getStatus()); 
     ImageView img = (ImageView) view.findViewById(R.id.img); 
     img.setImageURI(currentContact.getimageURI()); 
     return view; 
    } 

} 
} 

LogCat является

08-27 05:17:06.704 13110-13110/com.newthinktank.helloworld E/Trace﹕ error opening trace file: No such file or directory (2) 
08-27 05:17:06.759 13110-13110/com.newthinktank.helloworld I/System.out﹕ Sending WAIT chunk 
08-27 05:17:06.759 13110-13110/com.newthinktank.helloworld W/ActivityThread﹕ Application com.newthinktank.helloworld is waiting for the debugger on port 8100... 
08-27 05:17:06.766 13110-13117/com.newthinktank.helloworld I/dalvikvm﹕ Debugger is active 
08-27 05:17:06.962 13110-13110/com.newthinktank.helloworld I/System.out﹕ Debugger has connected 
08-27 05:17:06.962 13110-13110/com.newthinktank.helloworld I/System.out﹕ waiting for debugger to settle... 
08-27 05:17:07.157 13110-13110/com.newthinktank.helloworld I/System.out﹕ waiting for debugger to settle... 
08-27 05:17:07.360 13110-13110/com.newthinktank.helloworld I/System.out﹕ waiting for debugger to settle... 
08-27 05:17:07.563 13110-13110/com.newthinktank.helloworld I/System.out﹕ waiting for debugger to settle... 
08-27 05:17:07.759 13110-13110/com.newthinktank.helloworld I/System.out﹕ waiting for debugger to settle... 
08-27 05:17:07.962 13110-13110/com.newthinktank.helloworld I/System.out﹕ waiting for debugger to settle... 
08-27 05:17:08.165 13110-13110/com.newthinktank.helloworld I/System.out﹕ waiting for debugger to settle... 
08-27 05:17:08.368 13110-13110/com.newthinktank.helloworld I/System.out﹕ debugger has settled (1343) 
08-27 05:17:08.766 13110-13110/com.newthinktank.helloworld W/dalvikvm﹕ VFY: unable to find class referenced in signature (Landroid/view/SearchEvent;) 
08-27 05:17:08.766 13110-13110/com.newthinktank.helloworld I/dalvikvm﹕ Could not find method android.view.Window$Callback.onSearchRequested, referenced from method android.support.v7.internal.view.WindowCallbackWrapper.onSearchRequested 
08-27 05:17:08.774 13110-13110/com.newthinktank.helloworld W/dalvikvm﹕ VFY: unable to resolve interface method 14046: Landroid/view/Window$Callback;.onSearchRequested (Landroid/view/SearchEvent;)Z 
08-27 05:17:08.774 13110-13110/com.newthinktank.helloworld D/dalvikvm﹕ VFY: replacing opcode 0x72 at 0x0002 
08-27 05:17:08.774 13110-13110/com.newthinktank.helloworld I/dalvikvm﹕ Could not find method android.view.Window$Callback.onWindowStartingActionMode, referenced from method android.support.v7.internal.view.WindowCallbackWrapper.onWindowStartingActionMode 
08-27 05:17:08.774 13110-13110/com.newthinktank.helloworld W/dalvikvm﹕ VFY: unable to resolve interface method 14050: Landroid/view/Window$Callback;.onWindowStartingActionMode (Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode; 
08-27 05:17:08.774 13110-13110/com.newthinktank.helloworld D/dalvikvm﹕ VFY: replacing opcode 0x72 at 0x0002 
08-27 05:17:10.149 13110-13110/com.newthinktank.helloworld I/dalvikvm﹕ Could not find method android.view.ViewGroup.onRtlPropertiesChanged, referenced from method android.support.v7.widget.Toolbar.onRtlPropertiesChanged 
08-27 05:17:10.149 13110-13110/com.newthinktank.helloworld W/dalvikvm﹕ VFY: unable to resolve virtual method 13947: Landroid/view/ViewGroup;.onRtlPropertiesChanged (I)V 
08-27 05:17:10.149 13110-13110/com.newthinktank.helloworld D/dalvikvm﹕ VFY: replacing opcode 0x6f at 0x0007 
08-27 05:17:10.173 13110-13110/com.newthinktank.helloworld I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.internal.widget.TintTypedArray.getChangingConfigurations 
08-27 05:17:10.173 13110-13110/com.newthinktank.helloworld W/dalvikvm﹕ VFY: unable to resolve virtual method 403: Landroid/content/res/TypedArray;.getChangingConfigurations()I 
08-27 05:17:10.173 13110-13110/com.newthinktank.helloworld D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002 
08-27 05:17:10.173 13110-13110/com.newthinktank.helloworld I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.internal.widget.TintTypedArray.getType 
08-27 05:17:10.173 13110-13110/com.newthinktank.helloworld W/dalvikvm﹕ VFY: unable to resolve virtual method 425: Landroid/content/res/TypedArray;.getType (I)I 
08-27 05:17:10.173 13110-13110/com.newthinktank.helloworld D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002 
08-27 05:17:10.563 13110-13110/com.newthinktank.helloworld I/dalvikvm﹕ Could not find method android.content.res.Resources.getDrawable, referenced from method android.support.v7.internal.widget.ResourcesWrapper.getDrawable 
08-27 05:17:10.563 13110-13110/com.newthinktank.helloworld W/dalvikvm﹕ VFY: unable to resolve virtual method 366: Landroid/content/res/Resources;.getDrawable (ILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable; 
08-27 05:17:10.563 13110-13110/com.newthinktank.helloworld D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002 
08-27 05:17:10.563 13110-13110/com.newthinktank.helloworld I/dalvikvm﹕ Could not find method android.content.res.Resources.getDrawableForDensity, referenced from method android.support.v7.internal.widget.ResourcesWrapper.getDrawableForDensity 
08-27 05:17:10.563 13110-13110/com.newthinktank.helloworld W/dalvikvm﹕ VFY: unable to resolve virtual method 368: Landroid/content/res/Resources;.getDrawableForDensity (IILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable; 
08-27 05:17:10.563 13110-13110/com.newthinktank.helloworld D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002 
08-27 05:17:11.485 13110-13110/com.newthinktank.helloworld E/SQLiteLog﹕ (1) near "FROMcontacts": syntax error 
08-27 05:17:11.493 13110-13110/com.newthinktank.helloworld D/AndroidRuntime﹕ Shutting down VM 
08-27 05:17:11.493 13110-13110/com.newthinktank.helloworld W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40b762a0) 
08-27 05:17:11.665 13110-13110/com.newthinktank.helloworld E/AndroidRuntime﹕ FATAL EXCEPTION: main 
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.newthinktank.helloworld/com.newthinktank.helloworld.MainActivi ty}: android.database.sqlite.SQLiteException: near "FROMcontacts": syntax error (code 1): , while compiling: SELECT * FROMcontacts 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java: 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2174) 
at android.app.ActivityThread.access$700(ActivityThread.java:141) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1267) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:5059) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555) 
at dalvik.system.NativeStart.main(Native Method) 
Caused by: android.database.sqlite.SQLiteException: near "FROMcontacts": syntax error (code 1): , while compiling: SELECT * FROMcontacts 
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method) 
at    android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnecti  on.java:882) 
at   android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:493) 
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:1314) 
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1253) 
at com.newthinktank.helloworld.DatabaseHandler.getAllContacts(DatabaseHandler.java:83) 
at com.newthinktank.helloworld.MainActivity.onCreate(MainActivity.java:106) 
at android.app.Activity.performCreate(Activity.java:5058) 
at  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2100) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2174) 
at android.app.ActivityThread.access$700(ActivityThread.java:141) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1267) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:5059) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at   com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555) 
at dalvik.system.NativeStart.main(Native Method) 
08-27 05:17:12.266 13110-13110/com.newthinktank.helloworld I/Process﹕ Sending signal. PID: 13110 SIG: 9 
+2

Вы должны опубликовать LogCat, который показывает ошибку. – poss

+0

Мой единственный вопрос - почему вы используете базу данных в android? –

ответ

2

Это ваша ошибка (отсутствующие пробелы, скобки + дополнительная запятая на конец):

db.execSQL("CREATE TABLE " + TABLE_CONTACTS +""+ KEY_ID + " INTEGER PRIMARY," + KEY_CAR + "TEXT," + KEY_STATUS + "TEXT," + KEY_IMAGEURI + "TEXT,"); 

и (дважды !!)

Cursor cursor =db.rawQuery("SELECT * FROM" + TABLE_CONTACTS,null); 

и

db.execSQL("DROP TABLE IF EXISTS"+ TABLE_CONTACTS); 

Это исправление:

db.execSQL("CREATE TABLE " + TABLE_CONTACTS +" ("+ KEY_ID + " INTEGER PRIMARY, " + KEY_CAR + " TEXT, " + KEY_STATUS + " TEXT, " + KEY_IMAGEURI + " TEXT)"); 

и (Дважды !!)

Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_CONTACTS, null); 

и

db.execSQL("DROP TABLE IF EXISTS "+ TABLE_CONTACTS); 
+1

Хорошее наблюдение сэр –

+1

Спасибо, сэр! –

+0

Почему люди настаивают на том, чтобы писать сам SQL, когда есть много библиотеки для этого, и b/есть тота с одинаковыми ошибками на SO, все о недостатке в запросе. – njzk2