尝试通过SQLite数据库中的数据显示ListView时应用程序崩溃

时间:2018-02-07 05:39:20

标签: java android sqlite

所以我创建了一个有3个编辑文本的应用程序,用户必须先输入值,然后点击"查看记录"显示添加到SQLite数据库中的记录的列表视图。添加记录是有效的,我能够将数据存储到数据库中,但是我无法显示它们,因为每当我按下"查看记录"它就会一直崩溃。 。附件是我的ViewRecords页面的代码以及databasehelper。请指教。感谢。

ViewRecords.java

package mdad.project;
import java.util.ArrayList;
import com.example.manandhowproject.R;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class ViewRecords extends Activity {
    DatabaseHelper dbhelper;
    ListView listView;

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

        dbhelper = new DatabaseHelper(this);

        populateListView();
    }

    private void populateListView()
    {
        Cursor records = dbhelper.getRecords();
        ArrayList<String> listRec = new ArrayList<String>();
        while(records.moveToNext()){
            listRec.add(records.getString(1));
        }
    ListAdapter adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,listRec);
    listView.setAdapter(adapter);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
             String BTemp = adapterView.getItemAtPosition(i).toString();
             String HRate = adapterView.getItemAtPosition(i).toString();
             String Bmi = adapterView.getItemAtPosition(i).toString();

             Cursor data = dbhelper.getRecID(BTemp, HRate, Bmi);
             int recID = -1;
             while(data.moveToNext()){
                 recID = data.getInt(0);
             }
             if(recID > -1){

                 Intent editScreenIntent = new Intent(ViewRecords.this, EditDel.class);
                 editScreenIntent.putExtra("id",recID);
                 editScreenIntent.putExtra("Body Temperature",BTemp);
                 editScreenIntent.putExtra("Heart Rate",HRate);
                 editScreenIntent.putExtra("BMI",Bmi);
                 startActivity(editScreenIntent);
             }
             else{
                 Toast.makeText(getApplicationContext(), "No ID Associated", Toast.LENGTH_LONG).show();
             }
         }
     });
 }}

DatabaseHelper.java

package mdad.project;

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

public class DatabaseHelper extends SQLiteOpenHelper {

        public static final String DATABASE_NAME = "medrec.db";
        public static final String TABLE_NAME = "myrec_data";
        public static final String COL1 = "ID";
        public static final String COL2 = "BodyTemp";
        public static final String COL3 = "HeartRate";
        public static final String COL4 = "BMI";



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

    @Override
    public void onCreate(SQLiteDatabase db) {

    String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " + COL2 + " TEXT, " + COL3 + " TEXT, " + COL4 + " TEXT);";
    db.execSQL(createTable);

    }

    @Override
    public void onUpgrade (SQLiteDatabase db,int i, int i1)
    {
         db.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME);
         onCreate(db);
    }

     public boolean addRecord(String BodyTemp, String HeartRate, String BMI) {
            SQLiteDatabase db = this.getWritableDatabase();
            ContentValues contentValues = new ContentValues();
            contentValues.put(COL2, BodyTemp);
            contentValues.put(COL3, HeartRate);
            contentValues.put(COL4, BMI);

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


            if (result == -1) {
                return false;
            } else {
                return true;
            }
        }


     public Cursor getRecords()
     {
         SQLiteDatabase db = this.getWritableDatabase();
         String query = "SELECT * FROM " + TABLE_NAME;
         Cursor records = db.rawQuery(query, null);
         return records;
     }

     public Cursor getRecID(String BTemp, String Hrate, String Bmi){
            SQLiteDatabase db = this.getWritableDatabase();
            String query = "SELECT " + COL1 + " FROM " + TABLE_NAME +
                    " WHERE " + COL2 + " = '" + BTemp + "AND" + COL3 + " = '" + Hrate + "AND" + COL4 + " = '" + Bmi +"'";
            Cursor data = db.rawQuery(query, null);
            return data;
        }

    public void updateBtemp(String bodytemp, int selectedID,
            String selectedBtemp) {
          SQLiteDatabase db = this.getWritableDatabase();
          String query = "UPDATE " + TABLE_NAME + " SET " + COL2 +
                    " = '" + bodytemp + "' WHERE " + COL1 + " = '" + selectedID + "'" +
                    " AND " + COL2 + " = '" + selectedBtemp + "'";
            db.execSQL(query);

    }

    public void updateHrate(String heartrate, int selectedID,
            String selectedHrate) {
        SQLiteDatabase db = this.getWritableDatabase();
          String query = "UPDATE " + TABLE_NAME + " SET " + COL3 +
                    " = '" + heartrate + "' WHERE " + COL1 + " = '" + selectedID + "'" +
                    " AND " + COL3 + " = '" + selectedHrate + "'";
            db.execSQL(query);

    }

    public void updateBMI(String bmi, int selectedID, String selectedBMI) {
        SQLiteDatabase db = this.getWritableDatabase();
          String query = "UPDATE " + TABLE_NAME + " SET " + COL4 +
                    " = '" + bmi + "' WHERE " + COL1 + " = '" + selectedID + "'" +
                    " AND " + COL4 + " = '" + selectedBMI + "'";
            db.execSQL(query);

    }

    public void deleteBtemp(int selectedID, String selectedBtemp) {
           SQLiteDatabase db = this.getWritableDatabase();
            String query = "DELETE FROM " + TABLE_NAME + " WHERE "
                    + COL1 + " = '" + selectedID + "'" +
                    " AND " + COL2 + " = '" + selectedBtemp + "'";

            db.execSQL(query);

    }

    public void deleteHrate(int selectedID, String selectedHrate) {
           SQLiteDatabase db = this.getWritableDatabase();
            String query = "DELETE FROM " + TABLE_NAME + " WHERE "
                    + COL1 + " = '" + selectedID + "'" +
                    " AND " + COL3 + " = '" + selectedHrate + "'";

            db.execSQL(query);

    }

    public void deleteBMI(int selectedID, String selectedBMI) {
           SQLiteDatabase db = this.getWritableDatabase();
            String query = "DELETE FROM " + TABLE_NAME + " WHERE "
                    + COL1 + " = '" + selectedID + "'" +
                    " AND " + COL4 + " = '" + selectedBMI + "'";

            db.execSQL(query);

    }

}

崩溃日志

02-07 00:33:27.041: E/AndroidRuntime(884): FATAL EXCEPTION: main
02-07 00:33:27.041: E/AndroidRuntime(884): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.manandhowproject/mdad.project.ViewRecords}: java.lang.NullPointerException
02-07 00:33:27.041: E/AndroidRuntime(884):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
02-07 00:55:30.310: E/AndroidRuntime(10059): FATAL EXCEPTION: main
02-07 00:55:30.310: E/AndroidRuntime(10059): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.manandhowproject/mdad.project.ViewRecords}: java.lang.NullPointerException
02-07 00:55:30.310: E/AndroidRuntime(10059):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
02-07 00:55:30.310: E/AndroidRuntime(10059):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
02-07 00:55:30.310: E/AndroidRuntime(10059):    at android.app.ActivityThread.access$600(ActivityThread.java:141)
02-07 00:55:30.310: E/AndroidRuntime(10059):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
02-07 00:55:30.310: E/AndroidRuntime(10059):    at android.os.Handler.dispatchMessage(Handler.java:99)
02-07 00:55:30.310: E/AndroidRuntime(10059):    at android.os.Looper.loop(Looper.java:137)
02-07 00:55:30.310: E/AndroidRuntime(10059):    at android.app.ActivityThread.main(ActivityThread.java:5103)
02-07 00:55:30.310: E/AndroidRuntime(10059):    at java.lang.reflect.Method.invokeNative(Native Method)
02-07 00:55:30.310: E/AndroidRuntime(10059):    at java.lang.reflect.Method.invoke(Method.java:525)
02-07 00:55:30.310: E/AndroidRuntime(10059):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
02-07 00:55:30.310: E/AndroidRuntime(10059):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-07 00:55:30.310: E/AndroidRuntime(10059):    at dalvik.system.NativeStart.main(Native Method)
02-07 00:55:30.310: E/AndroidRuntime(10059): Caused by: java.lang.NullPointerException
02-07 00:55:30.310: E/AndroidRuntime(10059):    at mdad.project.ViewRecords.populateListView(ViewRecords.java:37)
02-07 00:55:30.310: E/AndroidRuntime(10059):    at mdad.project.ViewRecords.onCreate(ViewRecords.java:26)
02-07 00:55:30.310: E/AndroidRuntime(10059):    at android.app.Activity.performCreate(Activity.java:5133)
02-07 00:55:30.310: E/AndroidRuntime(10059):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
02-07 00:55:30.310: E/AndroidRuntime(10059):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
02-07 00:55:30.310: E/AndroidRuntime(10059):    ... 11 more

2 个答案:

答案 0 :(得分:2)

从“创建它”中的本地方法中删除ListView的声明,将其初始化以供本地使用。

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

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

            populateListView();
        }

答案 1 :(得分:1)

你有两个listView变量,一个被定义为一个类变量,另一个是本地的,只有onCreate方法的范围。

调用populateListView方法时,它使用的类变量listView为空。

修复方法是确保您始终使用班级listView

因此改变: -

    ListView listView = (ListView) findViewById(R.id.listView);

    listView = (ListView) findViewById(R.id.listView);