从android数据库显示和插入数据时出错

时间:2014-05-23 13:33:24

标签: java android database runtimeexception

我在显示和插入Android数据库时遇到问题。我已经通读了stackoverflow线程,但仍然无法纠正我的错误。这里有什么好心可以帮助我?

record.java

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent; 
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class Record extends Activity{

private ListView uGraduateNamesListView;
private Button addNewUndergraduateButton;

// We need some kind of Adapter to made the connection between ListView UI component and SQLite data set.
private ListAdapter uGraduateListAdapter;

// We need this while we read the query using Cursor and pass data
private ArrayList<Mile> mile;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_record);

    // Initialize UI components
    uGraduateNamesListView = (ListView) findViewById(R.id.list);




    mile = new ArrayList<Mile>();

    // For the third argument, we need a List that contains Strings.
    //We decided to display undergraduates names on the ListView.
    //Therefore we need to create List that contains undergraduates names
    uGraduateListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, populateList());

    uGraduateNamesListView.setAdapter(uGraduateListAdapter);

}


public void showAddForm(View v) {
    Intent addNewUndergraduateIntent = new Intent(this, Add.class);
    startActivity(addNewUndergraduateIntent);
}


//We are going to do it in the separate method
public List<String> populateList(){

    // We have to return a List which contains only String values. Lets create a List first
    List<String> uGraduateNamesList = new ArrayList<String>();

    // First we need to make contact with the database we have created using the DbHelper class
    MySQLiteHelper openHelperClass = new MySQLiteHelper(this);

    // Then we need to get a readable database
    SQLiteDatabase sqliteDatabase = openHelperClass.getReadableDatabase();

    //We need a a guy to read the database query. Cursor interface will do it for us
    //(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy)
    Cursor cursor = sqliteDatabase.query(MySQLiteHelper.TABLE_NAME_Mile, null, null, null, null, null, null);
    // Above given query, read all the columns and fields of the table

    startManagingCursor(cursor);

    // Cursor object read all the fields. So we make sure to check it will not miss any by looping through a while loop
    while (cursor.moveToNext()) {
        // In one loop, cursor read one undergraduate all details
        // Assume, we also need to see all the details of each and every undergraduate
        // What we have to do is in each loop, read all the values, pass them to the POJO class
        //and create a ArrayList of undergraduates
        String date = cursor.getString(cursor.getColumnIndex(MySQLiteHelper.COLUMN_NAME_DATE));
        Double miles = cursor.getDouble(cursor.getColumnIndex(MySQLiteHelper.COLUMN_NAME_MILE_TRAVELLED));
        String kiosk = cursor.getString(cursor.getColumnIndex(MySQLiteHelper.COLUMN_NAME_KIOSK_COMPANY));
        String petrol = cursor.getString(cursor.getColumnIndex(MySQLiteHelper.COLLUMN_NAME_PETROL_TYPE));
        double rate = cursor.getDouble(cursor.getColumnIndex(MySQLiteHelper.COLUMN_NAME_RATE));

        // Finish reading one raw, now we have to pass them to the POJO
        Mile ugPojoClass = new Mile();
        ugPojoClass.setDate(date);
        ugPojoClass.setMile(miles);
        ugPojoClass.setKiosk(kiosk);
        ugPojoClass.setPetrol(petrol);
        ugPojoClass.setRate(rate);

        // Lets pass that POJO to our ArrayList which contains undergraduates as type
        mile.add(ugPojoClass);

        // But we need a List of String to display in the ListView also.
        //That is why we create "uGraduateNamesList"
        uGraduateNamesList.add(date);
    }

    // If you don't close the database, you will get an error
    sqliteDatabase.close();

    return uGraduateNamesList;
}

// If you don't write the following code, you wont be able to see what you have just insert to the database 
@Override
protected void onResume() {
    super.onResume();
    mile = new ArrayList<Mile>();
    uGraduateListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, populateList());        
    uGraduateNamesListView.setAdapter(uGraduateListAdapter);        
}

@Override
protected void onStart() {
    super.onStart();
    mile = new ArrayList<Mile>();
    uGraduateListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, populateList());        
    uGraduateNamesListView.setAdapter(uGraduateListAdapter);    
}

// On ListView you just see the name of the undergraduate, not any other details
// Here we provide the solution to that. When the user click on a list item, he will redirect to a page where
//he can see all the details of the undergraduate
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

    Toast.makeText(getApplicationContext(), "Clicked on :" + arg2, Toast.LENGTH_SHORT).show();

    // We want to redirect to another Activity when the user click an item on the ListView
    Intent updateDeleteUgraduateIntent = new Intent(this, Update.class);

    // We have to identify what object, does the user clicked, because we are going to pass only clicked object details to the next activity
    // What we are going to do is, get the ID of the clicked item and get the values from the ArrayList which has
    //same array id.
    Mile clickedObject =  mile.get(arg2);

    // We have to bundle the data, which we want to pass to the other activity from this activity
    Bundle dataBundle = new Bundle();
    dataBundle.putString("clickedDate", clickedObject.getDate());
    dataBundle.putDouble("clickedMile", clickedObject.getMile());
    dataBundle.putString("clickedKiosk", clickedObject.getKiosk());
    dataBundle.putString("clickedPetrol", clickedObject.getPetrol());
    dataBundle.putDouble("clickedRate", clickedObject.getRate());

    // Attach the bundled data to the intent
    updateDeleteUgraduateIntent.putExtras(dataBundle);

    // Start the Activity
    startActivity(updateDeleteUgraduateIntent);

}
}

我有以下错误

05-23 09:29:03.818: D/gralloc_goldfish(1218): Emulator without GPU emulation detected.
05-23 09:29:58.728: I/Choreographer(1218): Skipped 145 frames!  The application may be doing too much work on its main thread.
05-23 09:30:00.778: D/AndroidRuntime(1218): Shutting down VM
05-23 09:30:00.778: W/dalvikvm(1218): threadid=1: thread exiting with uncaught exception (group=0xb2a62ba8)
05-23 09:30:01.038: E/AndroidRuntime(1218): FATAL EXCEPTION: main
05-23 09:30:01.038: E/AndroidRuntime(1218): Process: com.example.sgdriverdiary, PID: 1218
05-23 09:30:01.038: E/AndroidRuntime(1218): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sgdriverdiary/com.example.sgdriverdiary.Record}: java.lang.NullPointerException
05-23 09:30:01.038: E/AndroidRuntime(1218):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
05-23 09:30:01.038: E/AndroidRuntime(1218):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
05-23 09:30:01.038: E/AndroidRuntime(1218):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
05-23 09:30:01.038: E/AndroidRuntime(1218):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
05-23 09:30:01.038: E/AndroidRuntime(1218):     at android.os.Handler.dispatchMessage(Handler.java:102)
05-23 09:30:01.038: E/AndroidRuntime(1218):     at android.os.Looper.loop(Looper.java:136)
05-23 09:30:01.038: E/AndroidRuntime(1218):     at android.app.ActivityThread.main(ActivityThread.java:5017)
05-23 09:30:01.038: E/AndroidRuntime(1218):     at java.lang.reflect.Method.invokeNative(Native Method)
05-23 09:30:01.038: E/AndroidRuntime(1218):     at java.lang.reflect.Method.invoke(Method.java:515)
05-23 09:30:01.038: E/AndroidRuntime(1218):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-23 09:30:01.038: E/AndroidRuntime(1218):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-23 09:30:01.038: E/AndroidRuntime(1218):     at dalvik.system.NativeStart.main(Native Method)
05-23 09:30:01.038: E/AndroidRuntime(1218): Caused by: java.lang.NullPointerException
05-23 09:30:01.038: E/AndroidRuntime(1218):     at com.example.sgdriverdiary.Record.onCreate(Record.java:50)
05-23 09:30:01.038: E/AndroidRuntime(1218):     at android.app.Activity.performCreate(Activity.java:5231)
05-23 09:30:01.038: E/AndroidRuntime(1218):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
05-23 09:30:01.038: E/AndroidRuntime(1218):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
05-23 09:30:01.038: E/AndroidRuntime(1218):     ... 11 more

fragment_record.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.sgdriverdiary.Record$PlaceholderFragment"
    android:background="@drawable/layout_border" >
<RelativeLayout android:id="@+id/relativeLayout1" 
    android:layout_width="fill_parent" 
    android:layout_height="40dp" 
    android:background="#000000" 
    android:orientation="vertical" > 
    <TextView android:id="@+id/textView1" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_marginLeft="5dp" 
        android:text="Student" 
        android:textAppearance="?android:attr/textAppearanceLarge" 
        android:textColor="#FFFFFF" /> 
    <Button android:id="@+id/button1" 
        android:layout_width="41dp" 
        android:layout_height="40dp" 
        android:layout_alignParentRight="true" 
        android:layout_alignParentTop="true" 
        android:background="#454545" 
        android:onClick="showAddForm" 
        android:text="+" 
        android:textColor="#FFFFFF" 
        android:textSize="30sp" /> 
    </RelativeLayout>
     <RelativeLayout android:id="@+id/relativeLayout1" 
         android:layout_width="fill_parent" 
         android:layout_height="match_parent" 
         android:layout_alignParentLeft="true" 
         android:layout_below="@+id/relativeLayout1" 
         android:orientation="vertical" 
         android:layout_marginTop="40dp"> 
    <ListView android:id="@+id/list" 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content" 
        android:layout_alignParentLeft="true"> 
        </ListView> 
        </RelativeLayout> 



</RelativeLayout>

的manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.sgdriverdiary"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.SET_WALLPAPER" />
    <uses-permission android:name="android.permission.VIBRATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.sgdriverdiary.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.example.sgdriverdiary.Rate"
            android:label="@string/title_activity_rate" >
        </activity>
        <activity
            android:name="com.example.sgdriverdiary.Cal"
            android:label="@string/title_activity_cal" >
        </activity>
        <activity
            android:name="com.example.sgdriverdiary.Search"
            android:label="@string/title_activity_search" >
        </activity>
        <activity
            android:name="com.example.sgdriverdiary.CustomOnItemSelectedListener"
            android:label="@string/title_activity_custom_on_item_selected_listener" >
        </activity>
        <activity
            android:name="com.example.sgdriverdiary.Record"
            android:label="@string/title_activity_record" >
        </activity>
        <activity
            android:name="com.example.sgdriverdiary.MySQLiteHelper"
            android:label="@string/title_activity_my_sqlite_helper" >
        </activity>
        <activity
            android:name="com.example.sgdriverdiary.Recorddb"
            android:label="@string/title_activity_recorddb" >
        </activity>
        <activity
            android:name="com.example.sgdriverdiary.Update"
            android:label="@string/title_activity_update" >
        </activity>
        <activity
            android:name="com.example.sgdriverdiary.Add"
            android:label="@string/title_activity_add" >
        </activity>
    </application>

</manifest>

1 个答案:

答案 0 :(得分:0)

您的activity_record版面不包含ID为list的视图。这真的是Record onCreate()中NPE的唯一解释。

修改:您发布的包含list的布局标记为fragment_record.xml - 它不是activity_record。将列表视图设置移至片段onCreateView(),处理充气rootView,或将ListView移至您的活动布局。