尝试从EditText添加数据库中的数据时,Android应用程序崩溃

时间:2014-02-21 17:35:07

标签: android eclipse android-sqlite

package com.sachinrana.importantdatabse;

import java.util.ArrayList;

import android.os.Bundle;


import android.app.Activity;

import android.database.Cursor;

import android.view.Menu;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.EditText;

import android.widget.ListView;

public class MainActivity extends Activity {

    SqlHandler sqlHandler;

    ListView lvCustomList;

    EditText etName;

    Button btnsubmit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        lvCustomList = (ListView) findViewById(R.id.lv_custom_list);

        etName = (EditText) findViewById(R.id.et_name);

        btnsubmit = (Button) findViewById(R.id.btn_submit);

        sqlHandler = new SqlHandler(this);

        showList();

        btnsubmit.setOnClickListener(new OnClickListener() {

           @Override
           public void onClick(View v) {

            String name = etName.getText().toString();


            String query = "INSERT INTO Sachin_Medicine(name) values ('"
              + name +"')";

            sqlHandler.executeQuery(query);

            showList();

            etName.setText("");


           }
          });
    }
    private void showList() {

          ArrayList<MedListItems> medList = new ArrayList<MedListItems>();

          medList.clear();

          String query = "SELECT * FROM Sachin_Medicine ";

          Cursor c1 = sqlHandler.selectQuery(query);

          if (c1 != null && c1.getCount() != 0) {

           if (c1.moveToFirst()) {

            do {

             MedListItems medListItems = new MedListItems();

             medListItems.setSlno(c1.getString(c1
               .getColumnIndex("slno")));

             medListItems.setName(c1.getString(c1
               .getColumnIndex("name")));

             medList.add(medListItems);

            } while (c1.moveToNext());
           }
          }
          c1.close();

          MedListAdapter medListadapter = new MedListAdapter(

            MainActivity.this, medList);

          lvCustomList.setAdapter(medListadapter);

         }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.

        getMenuInflater().inflate(R.menu.main, menu);

        return true;
    }

}
  

SqlDbHelper.java       包com.sachinrana.importantdatabse;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class SqlDbHelper  extends SQLiteOpenHelper{

public static final String DATABASE_TABLE = "Sachin_Medicine";

 public static final String COLUMN1 = "slno";
 public static final String COLUMN2 = "Name";

 private static final String CREATE_DATABASE = "create table "
   + DATABASE_TABLE + " (" + COLUMN1
   + " integer primary key autoincrement, " + COLUMN2
   + " text not null );";


public SqlDbHelper(Context context, String name, CursorFactory factory,
        int version) {
    super(context, name, factory, version);
    // TODO Auto-generated constructor stub
}

@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    db.execSQL(CREATE_DATABASE);

}

@Override
public void onUpgrade(SQLiteDatabase db,int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
     db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
      onCreate(db);


}

}
  

SqlHandler.java

package com.sachinrana.importantdatabse;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class SqlHandler {

public static final String DATABASE_NAME = "YOYO_DATABASE";
public static final int DATABASE_VERSION = 2;
Context context;
SQLiteDatabase sqlDatabase;
SqlDbHelper dbHelper;

public SqlHandler(Context context) {

      dbHelper = new SqlDbHelper(context, DATABASE_NAME, null,
        DATABASE_VERSION);
      sqlDatabase = dbHelper.getWritableDatabase();
     }

     public void executeQuery(String query) {
      try {

       if (sqlDatabase.isOpen()) {
        sqlDatabase.close();
       }

       sqlDatabase = dbHelper.getWritableDatabase();
       sqlDatabase.execSQL(query);

      } catch (Exception e) {

       System.out.println("DATABASE ERROR " + e);
      }

     }

     public Cursor selectQuery(String query) {
      Cursor c1 = null;
      try {

       if (sqlDatabase.isOpen()) {
        sqlDatabase.close();

       }
       sqlDatabase = dbHelper.getWritableDatabase();
       c1 = sqlDatabase.rawQuery(query, null);

      } catch (Exception e) {

       System.out.println("DATABASE ERROR " + e);

      }
      return c1;

     }


}
  

MedListItems       包com.sachinrana.importantdatabse;

public class MedListItems {
String slno;
String name;

public String getSlno() {
      return slno;
     }

     public void setSlno(String slno) {
      this.slno = slno;
     }

     public String getName() {
      return name;
     }

     public void setName(String name) {
      this.name = name;
     }

 }
  

MedListadapter       包com.sachinrana.importantdatabse;

import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class MedListAdapter  extends BaseAdapter{
Context context;
ArrayList<MedListItems> medList;

public MedListAdapter(Context context, ArrayList<MedListItems> list) {

    this.context = context;
    medList = list;
}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    return medList.size();
}

@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
     return medList.get(position);
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup arg2) {
    // TODO Auto-generated method stub
    MedListItems contactListItems = medList.get(position);

    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.med_list_row, null);

    }
    TextView tvSlNo = (TextView) convertView.findViewById(R.id.tv_slno);
    tvSlNo.setText(contactListItems.getSlno());
    TextView tvName = (TextView) convertView.findViewById(R.id.tv_name);
    tvName.setText(contactListItems.getName());


    return convertView;

}


}
  

LogCat输出

  02-21 13:09:55.419: D/dalvikvm(1158): GC_FOR_ALLOC freed 53K, 5% free 3081K/3220K,        paused 72ms, total 73ms
    02-21 13:09:55.429: I/dalvikvm-heap(1158): Grow heap (frag case) to 3.696MB for 635812-byte allocation
    02-21 13:09:55.539: D/dalvikvm(1158): GC_FOR_ALLOC freed <1K, 4% free 3702K/3844K, paused 105ms, total 105ms
    02-21 13:09:55.889: E/CursorWindow(1158): Failed to read row 0, column -1 from a CursorWindow which has 1 rows, 2 columns.
    02-21 13:09:55.889: D/AndroidRuntime(1158): Shutting down VM
    02-21 13:09:55.889: W/dalvikvm(1158): threadid=1: thread exiting with uncaught exception (group=0xb3aeeba8)
   02-21 13:09:55.929: E/AndroidRuntime(1158): FATAL EXCEPTION: main
   02-21 13:09:55.929: E/AndroidRuntime(1158): Process: com.sachinrana.importantdatabse, PID: 1158
   02-21 13:09:55.929: E/AndroidRuntime(1158): java.lang.RuntimeException: Unable to start activity         ComponentInfo{com.sachinrana.importantdatabse/com.sachinrana.importantdatabse.MainActivity}: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.
   02-21 13:09:55.929: E/AndroidRuntime(1158):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
   02-21 13:09:55.929: E/AndroidRuntime(1158):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
   02-21 13:09:55.929: E/AndroidRuntime(1158):  at android.app.ActivityThread.access$800(ActivityThread.java:135)
   02-21 13:09:55.929: E/AndroidRuntime(1158):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
   02-21 13:09:55.929: E/AndroidRuntime(1158):  at android.os.Handler.dispatchMessage(Handler.java:102)
   02-21 13:09:55.929: E/AndroidRuntime(1158):  at android.os.Looper.loop(Looper.java:136)
   02-21 13:09:55.929: E/AndroidRuntime(1158):  at android.app.ActivityThread.main(ActivityThread.java:5017)
   02-21 13:09:55.929: E/AndroidRuntime(1158):  at java.lang.reflect.Method.invokeNative(Native Method)
   02-21 13:09:55.929: E/AndroidRuntime(1158):  at java.lang.reflect.Method.invoke(Method.java:515)
   02-21 13:09:55.929: E/AndroidRuntime(1158):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
   02-21 13:09:55.929: E/AndroidRuntime(1158):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
   02-21 13:09:55.929: E/AndroidRuntime(1158):  at dalvik.system.NativeStart.main(Native Method)
   02-21 13:09:55.929: E/AndroidRuntime(1158): Caused by: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.
   02-21 13:09:55.929: E/AndroidRuntime(1158):  at android.database.CursorWindow.nativeGetString(Native Method)
  02-21 13:09:55.929: E/AndroidRuntime(1158):   at android.database.CursorWindow.getString(CursorWindow.java:434)
  02-21 13:09:55.929: E/AndroidRuntime(1158):   at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
  02-21 13:09:55.929: E/AndroidRuntime(1158):   at com.sachinrana.importantdatabse.MainActivity.showList(MainActivity.java:63)
  02-21 13:09:55.929: E/AndroidRuntime(1158):   at com.sachinrana.importantdatabse.MainActivity.onCreate(MainActivity.java:31)
  02-21 13:09:55.929: E/AndroidRuntime(1158):   at android.app.Activity.performCreate(Activity.java:5231)
  02-21 13:09:55.929: E/AndroidRuntime(1158):   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
  02-21 13:09:55.929: E/AndroidRuntime(1158):   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
  02-21 13:09:55.929: E/AndroidRuntime(1158):   ... 11 more
  02-21 13:10:04.229: I/Process(1158): Sending signal. PID: 1158 SIG: 9
  

LogCat o / p 2

02-22 08:41:11.126: D/dalvikvm(1285): GC_FOR_ALLOC freed 64K, 5% free 3081K/3232K, paused 97ms, total 101ms
02-22 08:41:11.136: I/dalvikvm-heap(1285): Grow heap (frag case) to 3.696MB for 635812-byte allocation
02-22 08:41:11.276: D/dalvikvm(1285): GC_FOR_ALLOC freed 4K, 5% free 3698K/3856K, paused 115ms, total 115ms
02-22 08:41:12.706: I/Choreographer(1285): Skipped 142 frames!  The application may be doing too much work on its main thread.
02-22 08:41:12.776: D/gralloc_goldfish(1285): Emulator without GPU emulation detected.
02-22 08:41:13.156: I/Choreographer(1285): Skipped 53 frames!  The application may be doing too much work on its main thread.
02-22 08:41:20.906: E/CursorWindow(1285): Failed to read row 0, column -1 from a CursorWindow which has 1 rows, 2 columns.
02-22 08:41:20.906: D/AndroidRuntime(1285): Shutting down VM
02-22 08:41:20.916: W/dalvikvm(1285): threadid=1: thread exiting with uncaught exception (group=0xb3a7dba8)
02-22 08:41:20.986: E/AndroidRuntime(1285): FATAL EXCEPTION: main
02-22 08:41:20.986: E/AndroidRuntime(1285): Process: com.sachinrana.importantdatabse, PID: 1285
02-22 08:41:20.986: E/AndroidRuntime(1285): java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.
02-22 08:41:20.986: E/AndroidRuntime(1285):     at android.database.CursorWindow.nativeGetString(Native Method)
02-22 08:41:20.986: E/AndroidRuntime(1285):     at android.database.CursorWindow.getString(CursorWindow.java:434)
02-22 08:41:20.986: E/AndroidRuntime(1285):     at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
02-22 08:41:20.986: E/AndroidRuntime(1285):     at com.sachinrana.importantdatabse.MainActivity.showList(MainActivity.java:63)
02-22 08:41:20.986: E/AndroidRuntime(1285):     at com.sachinrana.importantdatabse.MainActivity.access$0(MainActivity.java:50)
02-22 08:41:20.986: E/AndroidRuntime(1285):     at com.sachinrana.importantdatabse.MainActivity$1.onClick(MainActivity.java:43)
02-22 08:41:20.986: E/AndroidRuntime(1285):     at android.view.View.performClick(View.java:4438)
02-22 08:41:20.986: E/AndroidRuntime(1285):     at android.view.View$PerformClick.run(View.java:18422)
02-22 08:41:20.986: E/AndroidRuntime(1285):     at android.os.Handler.handleCallback(Handler.java:733)
02-22 08:41:20.986: E/AndroidRuntime(1285):     at android.os.Handler.dispatchMessage(Handler.java:95)
02-22 08:41:20.986: E/AndroidRuntime(1285):     at android.os.Looper.loop(Looper.java:136)
02-22 08:41:20.986: E/AndroidRuntime(1285):     at android.app.ActivityThread.main(ActivityThread.java:5017)
02-22 08:41:20.986: E/AndroidRuntime(1285):     at java.lang.reflect.Method.invokeNative(Native Method)
02-22 08:41:20.986: E/AndroidRuntime(1285):     at java.lang.reflect.Method.invoke(Method.java:515)
02-22 08:41:20.986: E/AndroidRuntime(1285):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
02-22 08:41:20.986: E/AndroidRuntime(1285):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
02-22 08:41:20.986: E/AndroidRuntime(1285):     at dalvik.system.NativeStart.main(Native Method)
02-22 08:41:25.926: I/Process(1285): Sending signal. PID: 1285 SIG: 9



>updated LogCat
03-01 02:38:45.270: D/dalvikvm(1163): GC_FOR_ALLOC freed 46K, 4% free 3081K/3208K, paused 84ms, total 87ms
03-01 02:38:45.280: I/dalvikvm-heap(1163): Grow heap (frag case) to 3.692MB for 635812-byte allocation
03-01 02:38:45.390: D/dalvikvm(1163): GC_FOR_ALLOC freed 4K, 4% free 3698K/3832K, paused 98ms, total 98ms
03-01 02:38:46.140: I/Choreographer(1163): Skipped 66 frames!  The application may be doing too much work on its main thread.
03-01 02:38:46.170: D/gralloc_goldfish(1163): Emulator without GPU emulation detected.
03-01 02:38:46.660: I/Choreographer(1163): Skipped 84 frames!  The application may be doing too much work on its main thread.
03-01 02:38:52.090: E/CursorWindow(1163): Failed to read row 0, column -1 from a CursorWindow which has 1 rows, 2 columns.
03-01 02:38:52.090: D/AndroidRuntime(1163): Shutting down VM
03-01 02:38:52.090: W/dalvikvm(1163): threadid=1: thread exiting with uncaught exception (group=0xb3b05ba8)
03-01 02:38:52.130: E/AndroidRuntime(1163): FATAL EXCEPTION: main
03-01 02:38:52.130: E/AndroidRuntime(1163): Process: com.sachinrana.importantdatabse, PID: 1163
03-01 02:38:52.130: E/AndroidRuntime(1163): java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it.
03-01 02:38:52.130: E/AndroidRuntime(1163):     at android.database.CursorWindow.nativeGetLong(Native Method)
03-01 02:38:52.130: E/AndroidRuntime(1163):     at android.database.CursorWindow.getLong(CursorWindow.java:507)
03-01 02:38:52.130: E/AndroidRuntime(1163):     at android.database.CursorWindow.getInt(CursorWindow.java:574)
03-01 02:38:52.130: E/AndroidRuntime(1163):     at android.database.AbstractWindowedCursor.getInt(AbstractWindowedCursor.java:69)
03-01 02:38:52.130: E/AndroidRuntime(1163):     at com.sachinrana.importantdatabse.MainActivity.showList(MainActivity.java:60)
03-01 02:38:52.130: E/AndroidRuntime(1163):     at com.sachinrana.importantdatabse.MainActivity.access$0(MainActivity.java:49)
03-01 02:38:52.130: E/AndroidRuntime(1163):     at com.sachinrana.importantdatabse.MainActivity$1.onClick(MainActivity.java:42)
03-01 02:38:52.130: E/AndroidRuntime(1163):     at android.view.View.performClick(View.java:4438)
03-01 02:38:52.130: E/AndroidRuntime(1163):     at android.view.View$PerformClick.run(View.java:18422)
03-01 02:38:52.130: E/AndroidRuntime(1163):     at android.os.Handler.handleCallback(Handler.java:733)
03-01 02:38:52.130: E/AndroidRuntime(1163):     at android.os.Handler.dispatchMessage(Handler.java:95)
03-01 02:38:52.130: E/AndroidRuntime(1163):     at android.os.Looper.loop(Looper.java:136)
03-01 02:38:52.130: E/AndroidRuntime(1163):     at android.app.ActivityThread.main(ActivityThread.java:5017)
03-01 02:38:52.130: E/AndroidRuntime(1163):     at java.lang.reflect.Method.invokeNative(Native Method)
03-01 02:38:52.130: E/AndroidRuntime(1163):     at java.lang.reflect.Method.invoke(Method.java:515)
03-01 02:38:52.130: E/AndroidRuntime(1163):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-01 02:38:52.130: E/AndroidRuntime(1163):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-01 02:38:52.130: E/AndroidRuntime(1163):     at dalvik.system.NativeStart.main(Native Method)
03-01 02:38:57.490: I/Process(1163): Sending signal. PID: 1163 SIG: 9

2 个答案:

答案 0 :(得分:1)

TL; DR:在SQLite Android API中,列名称区分大小写。该表格为Name,您正在尝试访问name

以下一些信息如何调试这样的问题:

  

java.lang.IllegalStateException:无法从CursorWindow读取第0行col -1。在从中访问数据之前,请确保Cursor已正确初始化。

列索引-1无效。如果游标不包含具有给定名称的列,则getColumnIndex()返回-1。

您的查询是

String query = "SELECT * FROM Sachin_Medicine ";

您尝试访问的列是

medListItems.setSlno(c1.getString(c1
    .getColumnIndex("slno")));

medListItems.setName(c1.getString(c1
    .getColumnIndex("name")));

此处的表格创建表明您有slnoName列:

public static final String COLUMN1 = "slno";
public static final String COLUMN2 = "Name";

private static final String CREATE_DATABASE = "create table "
    + DATABASE_TABLE + " (" + COLUMN1
    + " integer primary key autoincrement, " + COLUMN2
    + " text not null );";

现在,SQL中的列名称不区分大小写,但在Android SQLite API中,它们区分大小写。因此,将getColumnIndex()调用更改为具有相同的大小写:

medListItems.setName(c1.getString(c1
    .getColumnIndex("Name")));

答案 1 :(得分:0)

在插入数据之前,您总是关闭数据库。从executeQueryselectQuery中删除以下代码:

if (sqlDatabase.isOpen()) {
    sqlDatabase.close();
}