java - 尝试从 Android 数据库中删除但获得空对象引用

标签 java android listview

TripList.java 类中,我有一个 listView,其中将我的旅行目的地和日期填充到这些单独的数组中。现在,在 listView 中的每个项目上,我都有一个 X,单击该 X 时,我希望它从数据库中删除该项目。

java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.nikscodingmachine.truckersexpence.DatabaseHelper.deleteData(java.lang.String)' on a null object reference
            at com.example.nikscodingmachine.truckersexpence.TripList.getBack(TripList.java:185)

我尝试了很多不同的方法,但似乎没有任何效果。如果我试图访问已经存储了内容的数据库,我不明白为什么会有空指针。似乎一旦我退出 TripList 和 TruckAdapter 类中的 onCreate 循环,从 TruckAdapter.java 返回到 TripList.java 就是问题所在。我尝试创建另一个类并在那里传递数据,但是因为其中一些类扩展了其他类,所以当我尝试这样做时会出现错误。如果有人请告诉我如何正确地做。非常感谢,我的类(class)如下。

import android.app.DatePickerDialog;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;



public class TripList extends ActionBarActivity {
//Instance of my created database
public DatabaseHelper myDb;
private TruckAdapter adapter;

//my variables
private String destination;
private int day;
private int month;
private int year;
private ListView listView;

private String da;
private String mo;
private String ye;




//ArrayLists you populate from database so we can later use them in the list
private List destinationArray = new ArrayList();
private List monthArray = new ArrayList();
private List dayArray = new ArrayList();
private List yearArray = new ArrayList();
int[] deleteArray = {R.drawable.delete_button};

//Just an empty constructor
public TripList(){
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_trip_list);
    //Creating myDb class
    myDb = new DatabaseHelper(this);
    //receiving information from InitialEntry
    destination = getIntent().getStringExtra("names");
    day = getIntent().getIntExtra("toDay", -1);
    month = getIntent().getIntExtra("toMonth", -1);
    year = getIntent().getIntExtra("toYear", -1);
    //Setting my dates toString
    mo = Integer.toString(month);
    da = Integer.toString(day);
    ye = Integer.toString(year);
    //Sending to method below
    addData(destination, mo, da, ye);


}
//called from onCreate above
public void addData(String destination, String mo, String da, String ye) {
    //passing three arguments into the insertData
    boolean isInserted = myDb.insertData(destination.toString(), mo.toString(), da.toString(), ye.toString());
    //It would return true if data was inserted
    if (isInserted == true) {
        Toast.makeText(TripList.this, "Data Inserted", Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(TripList.this, "Data not Inserted", Toast.LENGTH_LONG).show();
    }
    //calling these methods to upload from database to local ArrayList
    destinationList();
    monthList();
    dayList();
    yearList();

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

    //custom class
    adapter = new TruckAdapter(getApplication(), R.layout.list_custom_layout);
    listView.setAdapter(adapter);

    for(int i = 0; i < destinationArray.size(); i++){
        //passing destination, month, day, and year that we collected from our database to ArrayLists
        TruckDataProvider dataProvider = new TruckDataProvider(destinationArray.get(i).toString(), monthArray.get(i).toString(), dayArray.get(i).toString(), yearArray.get(i).toString(), deleteArray[0]);
        //adding the objects from TruckDataProvider to TruckAdapter
        adapter.add(dataProvider);

    }


    //when one of the destinations in the list is clicked
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            //We need to increment the position by one because position starts at zero but our table starts at one
            position++;
            Intent in = new Intent("com.example.nikscodingmachine.truckersexpence.MainActivity");
            //Setting position toString
            String pO = String.valueOf(position);
            //sending position to MainActivity before we go there
            in.putExtra("toPosition", pO);
            startActivity(in);
        }

    });

}



//Adding from the database to list so my destinations will be on the list array
public void destinationList() {
    //reaching into DatabaseHelper class
    Cursor res = myDb.getAllData();
    //Moves down the rows
    while (res.moveToNext()) {
        //From the row that it moved we are getting it's colume in position 1
        //and adding it to the list array
        destinationArray.add(res.getString(1));

    }

}






}
<小时/>
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.view.View;
import android.widget.Toast;


//needed for database methods below
private SQLiteDatabase db = this.getWritableDatabase();
private ContentValues contentValues = new ContentValues();



//our constructor
public DatabaseHelper(Context context) {
    super(context, DATABASE_NAME, null, 1);

}



@Override
public void onCreate(SQLiteDatabase db) {
    //(ID is Primary Key which also auto increments) (... ...)
    db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, DESTINATION TEXT, MONTH INTEGER, DAY INTEGER, YEAR INTEGER, FUEL INTEGER, MEAL INTEGER, MAINTENANCE INTEGER, LICENCING INTEGER, TRAILER INTEGER, INSURANCE INTEGER, EXTRA INTEGER, MISCELLANEOUS INTEGER)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
    onCreate(db);
}
//set and checking data method
public boolean insertData(String destination, String month, String day, String year) {
    contentValues.put(COL_2, destination);
    contentValues.put(COL_3, month);
    contentValues.put(COL_4,day);
    contentValues.put(COL_5,year);
    long result = db.insert(TABLE_NAME,null ,contentValues);
    //returns -1 if nothing is in the data base
    if(result == -1)
        return false;
    else
        return true;
}
//inserting the amount of fuel
public void insertFuelData(String addedResult, String Id) {
    contentValues.put(COL_1, Id);
    contentValues.put(COL_6, addedResult);
    //sendoff to method below
    ourUpdate(Id);
}

//inserting the meal amount
public void insertMealData(String addedResult, String Id) {
    contentValues.put(COL_1, Id);
    contentValues.put(COL_7, addedResult);
    //sendoff to method below
    ourUpdate(Id);
}


//getting data method
//which is used in a TripList to find and add to the list array the destinations
public Cursor getAllData(){
    //db is instance of a data base, a built in class
    Cursor res = db.rawQuery("select * from " + TABLE_NAME, null);
    return res;
}


public void deleteData(String id){
    db.delete(TABLE_NAME, "ID = ?", new String[] {id});
}

//part of update more convenient this way
public void ourUpdate(String Id){
    //built in update Id is where
    db.update(TABLE_NAME, contentValues, "ID = ?", new String[]{Id});
}


}
<小时/>
import android.content.Context;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

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



public class TruckAdapter extends ArrayAdapter {
TripList tList;
List list = new ArrayList();
private int pos;


public TruckAdapter(Context context, int resource) {
    super(context, resource);
    tList = new TripList();
}

//made a class
static class DataHandler{

    TextView title;
    TextView month;
    TextView day;
    TextView year;
    ImageView delete;


}
DataHandler handler = new DataHandler();

@Override
public void add(Object object) {
    super.add(object);
    list.add(object);
}

@Override
public int getCount() {
    return this.list.size();
}

@Override
public Object getItem(int position) {
    return this.list.get(position);
}


public View getView(final int position, View convertView, ViewGroup parent) {




}
<小时/>
public class TruckDataProvider {
private String des;
private String month;
private String day;
private String year;
private int delete;

//Constructor
public TruckDataProvider(String des, String month, String day, String year, int delete){
    this.des = des;
    this.month = month;
    this.day = day;
    this.year = year;
    this.delete = delete;
}

public String getDes() {
    return des;
}
public String getMonth() {
    return month;
}
public String getDay() {
    return day;
}
public String getYear() {
    return year;
}
public int getDelete() {
    return delete;
}


}

最佳答案

我想我发现了问题,但你仍然应该根据好的例子重写你的代码

我更改了以下内容

Context context;
public TruckAdapter(Context context, int resource) {
super(context, resource);
tList = new TripList();
this.context = context;
 }

调用getback的问题

handler.delete.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

                tList.getBack(position, context.getApplicationContext());

            }
        });

在 TripList 中

 public void getBack(int del , Context ctx){
    String delete = Integer.toString(del);
       new DatabaseHelper(ctx).deleteData(delete);
}

======================

在你的方法中:

public void getBack(int del){
    String delete = Integer.toString(del);
    myDb.deleteData(delete); 
}

变量myDB尚未初始化,因此为空。在尝试使用该变量之前,您应该将其设置为数据处理类的有效实例

关于java - 尝试从 Android 数据库中删除但获得空对象引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32233574/

相关文章:

java - 无法在 Listview android 中拖动或缩放谷歌地图

Java类路径问题

java - 将 DataInput 的字符串编码为 "modified UTF-8"

android - 从服务器获取数据时 Android 中的 Listview

java - Android ListView 不显示内容

android - 如何停止 android Background IntentService?

java - XSD 验证中的 SaxParseException 未提供元素名称

java - 警告 : "sun.reflect.Reflection.getCallerClass is not supported. This will impact performance"

java - Android NDK OpenGL ES 渲染图形到 Java 位图

android - 在 React Native 中使用默认设备应用程序打开 .pdf、.docx、.xlsx 等