从预先填充的sqlite数据库填充android列表视图,给出错误NULLpointerException

时间:2014-04-23 07:40:30

标签: android android-listview runtime-error android-sqlite

我正在创建从预先填充的sqlite数据库填充自定义列表视图的Android应用程序。

问题是eclipse显示错误 NULLpointerException

我知道错误在哪里,但我不知道如何修复以及为什么会出现此错误

这是第142行:

 myList.setAdapter(myCursorAdapter);

任何人都可以帮我修复此错误,我将不胜感激任何帮助

错误来自logCat:

04-23 07:31:16.830: E/AndroidRuntime(2758): Caused by: java.lang.NullPointerException
04-23 07:31:16.830: E/AndroidRuntime(2758):     at com.devleb.expandablelistdemo3.MatchScheduleList.populateLitsFromDB(MatchScheduleList.java:142)
04-23 07:31:16.830: E/AndroidRuntime(2758):     at com.devleb.expandablelistdemo3.MatchScheduleList.onCreate(MatchScheduleList.java:70)

这些课程是:

ExternalOpenHelper.java

package com.devleb.expandablelistdemo3;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class ExternalDbOpenHelper extends SQLiteOpenHelper {

    // *****Tbale name******************************//
/*  public static final String PLACE_ID = "_id";
    public static final String STAD_NAME = "stad_name";
    public static final String TEAM1 = "team1";
    public static final String TEAM2 = "team2";
    public static final String STAGE = "stage";
    public static final String MATCH_DATE = "match_date";

    public static final String[] ALL_KEYS = new String[] { PLACE_ID,
            STAD_NAME, TEAM1, TEAM2, STAGE, MATCH_DATE };
*/

    // *****Tbale name******************************//

    public static String DB_PATH;

    public static String DB_NAME;
//  private static final String TABLE_NAME = "match_list";
    public SQLiteDatabase database;
    public final Context context;

    public SQLiteDatabase getDb() {
        return database;
    }

    public ExternalDbOpenHelper(Context context, String databaseName) {
        super(context, databaseName, null, 1);
        this.context = context;

        String packageName = context.getPackageName();
        DB_PATH = String.format("//data//data//%s//databases//", packageName);
        DB_NAME = databaseName;
        openDataBase();
    }

    public void createDataBase() {
        boolean dbExist = checkDataBase();
        if (!dbExist) {
            this.getReadableDatabase();
            try {
                copyDataBase();
            } catch (IOException e) {
                Log.e(this.getClass().toString(), "Copying error");
                throw new Error("Error copying database!");
            }
        } else {
            Log.i(this.getClass().toString(), "Database already exists");
        }
    }

    private boolean checkDataBase() {
        SQLiteDatabase checkDb = null;
        try {
            String path = DB_PATH + DB_NAME;
            checkDb = SQLiteDatabase.openDatabase(path, null,
                    SQLiteDatabase.OPEN_READONLY);
        } catch (SQLException e) {
            Log.e(this.getClass().toString(), "Error while checking db");
        }
        if (checkDb != null) {
            checkDb.close();
        }
        return checkDb != null;
    }

    // ����� ����������� ����
    private void copyDataBase() throws IOException {
        InputStream externalDbStream = context.getAssets().open(DB_NAME);

        String outFileName = DB_PATH + DB_NAME;

        OutputStream localDbStream = new FileOutputStream(outFileName);

        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = externalDbStream.read(buffer)) > 0) {
            localDbStream.write(buffer, 0, bytesRead);
        }

        localDbStream.close();
        externalDbStream.close();

    }

    public SQLiteDatabase openDataBase() throws SQLException {
        String path = DB_PATH + DB_NAME;
        if (database == null) {
            createDataBase();
            database = SQLiteDatabase.openDatabase(path, null,
                    SQLiteDatabase.OPEN_READWRITE);
        }
        return database;
    }

    @Override
    public synchronized void close() {
        if (database != null) {
            database.close();
        }
        super.close();
    }



    @Override
    public void onCreate(SQLiteDatabase db) {
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }
}

MatchScheduleList.java

  package com.devleb.expandablelistdemo3;

import java.util.ArrayList;

import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MatchScheduleList extends Activity {

    private static final String DB_NAME = "world_cup.db";
    // *****Tables name**************************//
    private static final String TABLE_NAME = "match_list";

    // *****Tbale name******************************//

    public static final String PLACE_ID = "_id"; 
    public static final String STAD_NAME = "stad_name"; 
    public static final String TEAM1 = "team1";
    public static final String TEAM2 = "team2"; 
    public static final String STAGE = "stage"; 
    public static final String MATCH_DATE = "match_date";
    public static final String[] ALL_KEYS = new String[] { PLACE_ID,
            STAD_NAME, TEAM1, TEAM2, STAGE, MATCH_DATE };
    // *****Tbale name******************************//

    private SQLiteDatabase database;
    private ListView listView;
    private ArrayList<String> matchList;

    private ExternalDbOpenHelper extDB;

    int[] img = { R.drawable.brazil_flag, R.drawable.croatian_flag,
            R.drawable.mexico_flag, R.drawable.cameroon_flag, R.drawable.spain,
            R.drawable.netherlands_flag, R.drawable.czech_republic_flag,
            R.drawable.australia, R.drawable.colombia_flag, R.drawable.gress,
            R.drawable.cote_divoire_flag, R.drawable.japan,
            R.drawable.uruguay_flag, R.drawable.costa_rica_flag,
            R.drawable.england_flag, R.drawable.italy_flag,
            R.drawable.switzerland, R.drawable.ecuador_flag,
            R.drawable.france_flag, R.drawable.honduras_flag,
            R.drawable.argentina_flag, R.drawable.bousna, R.drawable.iran_flag,
            R.drawable.nigeria_flag, R.drawable.germany_flag,
            R.drawable.portugal, R.drawable.ghana_flag,
            R.drawable.united_states_flag, R.drawable.belgium_flag,
            R.drawable.algeria_flag, R.drawable.russia_flag,
            R.drawable.korea_flag };

    int nextImageIndex = 0;

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

        ExternalDbOpenHelper extDB = new ExternalDbOpenHelper(this, DB_NAME);
        database = extDB.openDataBase();
        populateLitsFromDB();

        // fillFreinds();
        // setUpList();
    }

    /*
     * private void setUpList() {
     * 
     * setListAdapter(new ArrayAdapter<String>(this,
     * android.R.layout.simple_list_item_1, places)); listView = getListView();
     * 
     * 
     * listView.setOnItemClickListener(new OnItemClickListener() { public void
     * onItemClick(AdapterView<?> parent, View view, int position,long id) {
     * Toast.makeText(getApplicationContext(), ((TextView)
     * view).getText().toString(), Toast.LENGTH_SHORT).show(); } }); }
     * 
     * 
     * private void fillFreinds() { places = new ArrayList<String>(); Cursor
     * friendCursor = database.query(TABLE_NAME, new String[] {PLACE_ID,
     * CITY_NAME}, null, null, null, null , CITY_NAME);
     * friendCursor.moveToFirst(); if(!friendCursor.isAfterLast()) { do { String
     * name = friendCursor.getString(1); places.add(name); } while
     * (friendCursor.moveToNext()); } friendCursor.close(); }
     */
    /*
     * public void fillMatchList(){ matchList = new ArrayList<String>()
     * 
     * }
     */

    public Cursor getAllRows() {
        String where = null;


        Cursor c = database.query(true, TABLE_NAME, ALL_KEYS, where, null,
                null, null, null, null);
        if (c != null) {
            c.moveToFirst();


        }

        return c;

    }


    private void populateLitsFromDB() {
        // TODO Auto-generated method stub


        Cursor cursor = getAllRows();

        // allo0w activity to manage life cicle of the cursor

        startManagingCursor(cursor);

        // setup mapping from cursor to view fields
        String[] fromFieldNames = new String[] {MATCH_DATE };
        int[] toViewFields = new int[] { R.id.txtDate };

        // create adapter to map columns of the DB INTO ELEMENT IN THE LIST
        SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(this,
                R.layout.row_list_match_schedule, cursor, fromFieldNames,
                toViewFields);

        Log.d("in the getAllRows", myCursorAdapter.toString());

        // set the adapter for te listView
        ListView myList = (ListView) findViewById(R.id.list);
        myList.setAdapter(myCursorAdapter);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.match_schedule_list, menu);
        return true;
    }

}

activity_match_schedule_list.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=".GroupList" 
    android:background="@drawable/backgroud_list2">

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
    </ListView>

</RelativeLayout>

1 个答案:

答案 0 :(得分:1)

  

这是第142行:

myList.setAdapter(myCursorAdapter);
     

myList在第142行之前初始化ListView myList =(ListView)findViewById(R.id.list);

NPE的唯一方法是因为myListnull。所以findViewById(R.id.list)返回null。如果使用setContentView()设置的布局没有具有此类ID的视图,它将返回null。

查看刚发布的代码,将list_demo_for_match设置为内容视图布局,但视图位于activity_match_schedule_list