-2

我在我的应用程序中遇到这部分错误:

我有这个logcat:

03-09 00:25:49.213: D/AndroidRuntime(431): Shutting down VM
03-09 00:25:49.213: W/dalvikvm(431): threadid=1: thread exiting with uncaught exception (group=0x40015560)
03-09 00:25:49.253: E/AndroidRuntime(431): FATAL EXCEPTION: main
03-09 00:25:49.253: E/AndroidRuntime(431): java.lang.NullPointerException
03-09 00:25:49.253: E/AndroidRuntime(431):  at me.mojica.caloriewatch.Search$1.onItemClick(Search.java:231)
03-09 00:25:49.253: E/AndroidRuntime(431):  at android.widget.AdapterView.performItemClick(AdapterView.java:284)
03-09 00:25:49.253: E/AndroidRuntime(431):  at android.widget.ListView.performItemClick(ListView.java:3513)
03-09 00:25:49.253: E/AndroidRuntime(431):  at android.widget.AbsListView$PerformClick.run(AbsListView.java:1812)
03-09 00:25:49.253: E/AndroidRuntime(431):  at android.os.Handler.handleCallback(Handler.java:587)
03-09 00:25:49.253: E/AndroidRuntime(431):  at android.os.Handler.dispatchMessage(Handler.java:92)
03-09 00:25:49.253: E/AndroidRuntime(431):  at android.os.Looper.loop(Looper.java:123)
03-09 00:25:49.253: E/AndroidRuntime(431):  at android.app.ActivityThread.main(ActivityThread.java:3683)
03-09 00:25:49.253: E/AndroidRuntime(431):  at java.lang.reflect.Method.invokeNative(Native Method)
03-09 00:25:49.253: E/AndroidRuntime(431):  at java.lang.reflect.Method.invoke(Method.java:507)
03-09 00:25:49.253: E/AndroidRuntime(431):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
03-09 00:25:49.253: E/AndroidRuntime(431):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
03-09 00:25:49.253: E/AndroidRuntime(431):  at dalvik.system.NativeStart.main(Native Method)
03-09 00:25:51.363: I/Process(431): Sending signal. PID: 431 SIG: 9
03-09 00:25:53.853: D/dalvikvm(441): GC_EXTERNAL_ALLOC freed 58K, 52% free 2603K/5379K, external 2000K/2137K, paused 105ms

我唯一能理解的部分是:

03-09 00:25:49.253: E/AndroidRuntime(431):  at me.mojica.caloriewatch.Search$1.onItemClick(Search.java:231)

在我的课上

       String data1 = food.getText().toString();
       String data2 = calories.getText().toString();
       mySQLiteAdapter1.insert1(data1, data2); <---------------- line number 231
       updateList();

在我的适配器中,我这样说

public long insert(String foodname, int i){
    ContentValues contentValues = new ContentValues();
    contentValues.put(KEY_FOODNAME, foodname);
    contentValues.put(KEY_CALORIES, i);
    return sqLiteDatabase.insert(MYDATABASE_TABLE, null, contentValues);    

}

我不知道错误的部分是否在我的课堂上我在字符串中声明了它然后在我的适配器中有 1 个 int 和 1 个字符串

更新:这是我班的代码:

package me.mojica.caloriewatch;

import java.util.ArrayList;



import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class Search extends Activity {

private SQLiteAdapter mySQLiteAdapter;
private FoodlogAdapter mySQLiteAdapter1;

int arlene=0;
int textlength=0;

ListView listContent1, transact;
EditText search, food, calories;
Button FSearch;
TextView result;


SimpleCursorAdapter cursorAdapter, cursorAdap;
Cursor cursor, Tcursor;
private String[] listview_array;
private ArrayList<String> array_sort= new ArrayList<String>();

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


  listContent1  = (ListView)findViewById(R.id.lFoodlist1);
  //transact  = (ListView)findViewById(R.id.transact);
  search= (EditText) findViewById(R.id.eFsearch);
  food= (EditText) findViewById(R.id.editText1);
  calories= (EditText) findViewById(R.id.editText2);  
  FSearch=(Button) findViewById(R.id.bFsearch);
  result=(TextView)findViewById(R.id.textView3);


  /*
   *  Create/Open a SQLite database
   *  and fill with dummy content
   *  and close it
   */
  mySQLiteAdapter = new SQLiteAdapter(this);
  mySQLiteAdapter.openToWrite();
  mySQLiteAdapter.deleteAll();

  mySQLiteAdapter.insert("Adobong Baboy (1 bowl)", 339);
  mySQLiteAdapter.insert("Adobong Kangkong ( 1 bowl)", 84);
  mySQLiteAdapter.insert("Adobong Manok (1 bowl) ", 624);
  mySQLiteAdapter.insert("Adobong Pusit (1 bowl)", 121);
  mySQLiteAdapter.insert("Arroz Caldo (1 bowl)", 500);
  mySQLiteAdapter.insert("Chicken Afritada (1 bowl)", 323);
  mySQLiteAdapter.insert("Chicken Asado (1 bowl)", 205);
  mySQLiteAdapter.insert("Chicken Empanada (1 bowl)", 150);
  mySQLiteAdapter.insert("Chicken Tinola (1 bowl)", 267);
  mySQLiteAdapter.insert("Dinuguan (1 bowl)", 255);
  mySQLiteAdapter.insert("Fried Bangus (1 pc)", 162);
  mySQLiteAdapter.insert("Ginataang Kalabasa (1 bowl)", 225);
  mySQLiteAdapter.insert("Ginataang Langka (1 bowl)", 167);
  mySQLiteAdapter.insert("Ginataang Pinakbet (1 bowl)", 155);
  mySQLiteAdapter.insert("Igado (1 bowl)", 297);
  mySQLiteAdapter.insert("Kare Kare (1 bowl)", 129);
  mySQLiteAdapter.insert("Laing (1 bowl)", 202);
  mySQLiteAdapter.insert("Lechon Kawali (1 bowl)", 245);
  mySQLiteAdapter.insert("Pakbet (1 bowl)", 233);
  mySQLiteAdapter.insert("Paksiw na Isda (1 bowl)", 73);
  mySQLiteAdapter.insert("Paksiw na Pata (1 bowl)", 342);
  mySQLiteAdapter.insert("Pinakbet (1 bowl)", 110);
  mySQLiteAdapter.insert("Pork Afritada (1 bowl)", 402);
  mySQLiteAdapter.insert("Pork Asado (1 bowl)", 533);
  mySQLiteAdapter.insert("Pork Barbaque on Stick (1 stick)", 111);
  mySQLiteAdapter.insert("Pork Embutido (1 bowl)", 350);
  mySQLiteAdapter.insert("Pork Mechado (1 bowl)", 157);
  mySQLiteAdapter.insert("Pork Nilaga (1 bowl)", 181);
  mySQLiteAdapter.insert("Pork Pochero (1 bowl)", 798);
  mySQLiteAdapter.insert("Pork Sinigang (1 bowl)", 290);
  mySQLiteAdapter.insert("Relyenong Bangus (1 bowl)", 390);
  mySQLiteAdapter.insert("Salmon Sinigang (1 bowl)", 190);
  mySQLiteAdapter.insert("Sisig (1 bowl)", 293);
  mySQLiteAdapter.insert("Tilapia (1 pc)", 100);
  mySQLiteAdapter.insert("Tinolang Manok (1 bowl)", 843);
  mySQLiteAdapter.insert("Tortang Talong (1 pc)", 291);
  mySQLiteAdapter.insert("Balut (1 egg)", 188);
  mySQLiteAdapter.insert("Beefsteak (1 bowl)", 210);
  mySQLiteAdapter.insert("Bibingka", 100);
  mySQLiteAdapter.insert("Biko (1 slice)", 100);
  mySQLiteAdapter.insert("Buko Pie (1 slice)", 145);
  mySQLiteAdapter.insert("Cassava Cake (1 slice)", 100);
  mySQLiteAdapter.insert("Chicsilog (1 meal)", 284);
  mySQLiteAdapter.insert("Coorned Beef (1 meal)", 267);
  mySQLiteAdapter.insert("Danggit (1 pc)",98);
  mySQLiteAdapter.insert("Ice Cream", 157);
  mySQLiteAdapter.insert("Embotido", 187);
  mySQLiteAdapter.insert("Ensaymada", 410);
  mySQLiteAdapter.insert("Espasol", 50);
  mySQLiteAdapter.insert("Fishball (1 pc)", 9);
  mySQLiteAdapter.insert("Fruit Salad (1 bowl)", 211);
  mySQLiteAdapter.insert("Galapong (1 slice)", 100);
  mySQLiteAdapter.insert("Ginataan (1 bowl)", 167);
  mySQLiteAdapter.insert("Halaya", 70);
  mySQLiteAdapter.insert("Halo halo (1 cup)", 80);
  mySQLiteAdapter.insert("Hotdog (1 pc)", 183);
  mySQLiteAdapter.insert("Kutsinta", 100);
  mySQLiteAdapter.insert("Leche Flan", 228);
  mySQLiteAdapter.insert("Lomi", 222);
  mySQLiteAdapter.insert("Longganisa (1 pc)", 170);
  mySQLiteAdapter.insert("Lumpiang Shanghai (1 pc)", 169);
  mySQLiteAdapter.insert("Palabok", 305);
  mySQLiteAdapter.insert("Palitaw", 100);
  mySQLiteAdapter.insert("Pancit", 416);
  mySQLiteAdapter.insert("Pansit Palabok", 305);
  mySQLiteAdapter.insert("Pastillas (1 pc)", 76);
  mySQLiteAdapter.insert("Porksilog (1 meal)", 555);
  mySQLiteAdapter.insert("Pulvoron (1 pc)", 40);
  mySQLiteAdapter.insert("Puto (1 pc)", 112);
  mySQLiteAdapter.insert("Puto Bumbong (1 pc)", 50);
  mySQLiteAdapter.insert("Puto Pao (1 bun)", 120);
  mySQLiteAdapter.insert("Qwek qwek (1 pc)", 14);
  mySQLiteAdapter.insert("Saging na Saba", 122);
  mySQLiteAdapter.insert("Sapin sapin (1 slice)", 100);
  mySQLiteAdapter.insert("Scrambled Egg", 100);
  mySQLiteAdapter.insert("Sinangag (1 cup)", 300);
  mySQLiteAdapter.insert("Siopao", 240);
  mySQLiteAdapter.insert("Suman (1 pc )", 31);
  mySQLiteAdapter.insert("Taho (1 cup)", 180);
  mySQLiteAdapter.insert("Tapsilog (1 meal)", 364);
  mySQLiteAdapter.insert("Tikoy (1 slice)", 100);
  mySQLiteAdapter.insert("Tuyo (1 pc)", 57);
  mySQLiteAdapter.insert("Yema (1 pc)", 20);

  mySQLiteAdapter.insert("Apple", 80);
  mySQLiteAdapter.insert("Apricots", 17);
  mySQLiteAdapter.insert("Avocado", 30);
  mySQLiteAdapter.insert("Banana", 105);
  mySQLiteAdapter.insert("Blueberries", 82);
  mySQLiteAdapter.insert("Cherry", 4);
  mySQLiteAdapter.insert("Coconut", 159);
  mySQLiteAdapter.insert("Eggplant", 132);
  mySQLiteAdapter.insert("Grape Fruit", 62);
  mySQLiteAdapter.insert("Guava", 61);
  mySQLiteAdapter.insert("Kiwi Fruit", 25);
  mySQLiteAdapter.insert("Lemon", 24);
  mySQLiteAdapter.insert("Limes", 20);
  mySQLiteAdapter.insert("Lychee", 4);
  mySQLiteAdapter.insert("Mango", 107);
  mySQLiteAdapter.insert("Melon", 188);
  mySQLiteAdapter.insert("Orange", 62);
  mySQLiteAdapter.insert("Peach", 38);
  mySQLiteAdapter.insert("Pineapple (1 slice)", 42);
  mySQLiteAdapter.insert("Pomelo (per section)", 72);
  mySQLiteAdapter.insert("Rambutan", 7);
  mySQLiteAdapter.insert("Raspberries", 82);
  mySQLiteAdapter.insert("Strawberry", 8);
  mySQLiteAdapter.insert("Tomato", 15);
  mySQLiteAdapter.insert("Watermelon (per slice)", 46);



  mySQLiteAdapter.close();

  /*
   *  Open the same SQLite database
   *  and read all it's content.
   */
  mySQLiteAdapter = new SQLiteAdapter(this);
  mySQLiteAdapter.openToRead();

  Cursor cursor = mySQLiteAdapter.queueAll();
  startManagingCursor(cursor);

  String[] from = new String[]{SQLiteAdapter.KEY_FOODNAME,SQLiteAdapter.KEY_CALORIES};
  int[] to = new int[]{R.id.tv1, R.id.tv2};

  SimpleCursorAdapter cursorAdapter =
   new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);

  listContent1.setAdapter(cursorAdapter);
  listContent1.setOnItemClickListener(listContentOnItemClickListener); 
  mySQLiteAdapter.close();
  }

  private ListView.OnItemClickListener listContentOnItemClickListener = new         ListView.OnItemClickListener(){
  public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
       Cursor cursor = (Cursor) parent.getItemAtPosition(position);

      String item_content1 = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_FOODNAME));
      String item_content2 = cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_CALORIES));
      arlene = arlene + Integer.parseInt(item_content2);
      String item = String.valueOf(" Food Name: " + item_content1 ) + "\n" +
              " Calories: " +  item_content2;

       Toast.makeText(Search.this, item, Toast.LENGTH_LONG).show();      

       food.setText(item_content1);
       calories.setText(String.valueOf(arlene));

       /*Intent myIntent = new Intent(Search.this, Foodlog.class);
       Bundle bundle = new Bundle();
       bundle.putString("SQLITEDATA1", food.getText().toString()); 
       bundle.putString("SQLITEDATA2", calories.getText().toString()); 
       myIntent.putExtras(bundle);
       startActivity(myIntent); */

       String data1 = food.getText().toString();
       String data2 = calories.getText().toString();
       mySQLiteAdapter1.insert1(data1, data2);
       updateList();

       //SavePreferences("food", food.getText().toString());
       SavePreferences("calories", calories.getText().toString());
       LoadPreferences();
  }}
  ;

protected void SavePreferences(String key, String value) {
// TODO Auto-generated method stub
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}

private void updateList() {
// TODO Auto-generated method stub
 Tcursor.requery();
}


protected void LoadPreferences() {
// TODO Auto-generated method stub
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
String strSavedMem1 = sharedPreferences.getString("food", "");
String strSavedMem2 = sharedPreferences.getString("calories", "");


//food.setText(strSavedMem1);
calories.setText(strSavedMem2); 
}

  }

至于我的适配器:

package me.mojica.caloriewatch;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.os.Bundle;
import android.util.Log;


public class SQLiteAdapter extends Search{

@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.row);
}

public static final String APP_NAME = "AdvancedSearch";
public static final String MYDATABASE_NAME = "Food_DB";
public static final String MYDATABASE_TABLE = "Food_Table";
public static final int MYDATABASE_VERSION = 1;

public static final String KEY_ID = "_id";
public static final String KEY_FOODNAME = "FoodName";
public static final String KEY_CALORIES = "Calories";

//create table MY_DATABASE (ID integer primary key, Content text not null);

private static final String SCRIPT_CREATE_DATABASE =
        "create table " + MYDATABASE_TABLE + " ("
                + KEY_ID + " integer primary key autoincrement, "
                + KEY_FOODNAME + " text not null, " + 
                KEY_CALORIES + " integer);";



private SQLiteHelper sqLiteHelper;
private SQLiteDatabase sqLiteDatabase;

private Context context;

public SQLiteAdapter(Context c){
    context = c;
}

public SQLiteAdapter openToRead() throws android.database.SQLException {
    sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
    sqLiteDatabase = sqLiteHelper.getReadableDatabase();
    return this;
}

public SQLiteAdapter openToWrite() throws android.database.SQLException {
    sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null, MYDATABASE_VERSION);
    sqLiteDatabase = sqLiteHelper.getWritableDatabase();
    return this;
}

public void close()
{
    sqLiteHelper.close();
}

public long insert(String foodname, int i){
    ContentValues contentValues = new ContentValues();
    contentValues.put(KEY_FOODNAME, foodname);
    contentValues.put(KEY_CALORIES, i);
    return sqLiteDatabase.insert(MYDATABASE_TABLE, null, contentValues);    

}

public long insert1(String foodname, int i){
    ContentValues contentValues = new ContentValues();
    contentValues.put(KEY_FOODNAME, foodname);
    contentValues.put(KEY_CALORIES, i);
    return sqLiteDatabase.insert(MYDATABASE_TABLE, null, contentValues);    

}


public int deleteAll(){
    return sqLiteDatabase.delete(MYDATABASE_TABLE, null, null);
}

public Cursor queueAll(){
    String[] columns = new String[]{KEY_ID, KEY_FOODNAME, KEY_CALORIES};
    Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,
            null, null, null, null, null);

    return cursor;
}

 public void update_byID(int id, String v1, String v2){
      ContentValues values = new ContentValues();
      values.put(KEY_FOODNAME, v1);
      values.put(KEY_CALORIES, v2);
      sqLiteDatabase.update(MYDATABASE_TABLE, values, KEY_ID+"="+id, null);
     }


public class SQLiteHelper extends SQLiteOpenHelper {

    public SQLiteHelper(Context context, String name,
            CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

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

    }


    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

    }

        }

public String[] qall(){
    Cursor cursor = null;
    String[] columns = new String[]{KEY_ID, KEY_FOODNAME, KEY_CALORIES};
    String[] listview_array = null;
    try{
         cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,
                null, null, null, null, null);

        if(cursor!=null && cursor.getCount()>0 && cursor.moveToFirst()){
            listview_array=new String[cursor.getCount()];

            int foodName = cursor.getColumnIndex(KEY_FOODNAME );
            int keyColories = cursor.getColumnIndex(KEY_CALORIES );
            int l=0;
            boolean moveToNext = cursor.moveToFirst();
            do{
            listview_array[l]=cursor.getString(foodName) + "                              " +
                    cursor.getString(keyColories);
               l++;
            }while(cursor.moveToNext());
        }
    }catch(Exception e){
        Log.e(APP_NAME, "An error occurred while searching for "+search+": "+e.toString(), e);
    }finally{
        if(cursor!=null && !cursor.isClosed()){
            cursor.close();
        }
    }
    return listview_array;

}

public void open()
{
    sqLiteDatabase = sqLiteHelper.getWritableDatabase();
}

public void delete_byID(int item_id) {
    // TODO Auto-generated method stub
    sqLiteDatabase.delete(MYDATABASE_TABLE, KEY_ID, null);
}


}
4

1 回答 1

1

NullPointerException 发生是因为 mySQLiteAdapter1 为空,而不是您传入的任何值。

从您发布的代码来看,mySQLiteAdapter1 似乎没有在任何地方初始化。我希望它被初始化为你的 onCreate() 的一部分。

于 2013-03-08T17:01:44.393 回答