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

时间:2015-08-26 18:01:11

标签: java android listview

TripList.java类中,我有一个listView,其中填充了我的旅行目的地和日期到这些单独的数组中。现在在listView中的每个项目上我都有一个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循环,从TripList.java回到TruckAdapter.java就是问题所在。我尝试过创建另一个类并在那里传递数据,但是因为其中一些类扩展了其他类,所以当我尝试这样做时,它会给我带来错误。如果有人请告诉我如何做对。非常感谢,我的课程如下。

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;
}


}

1 个答案:

答案 0 :(得分:1)

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

我更改了以下内容

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尚未初始化,因此为空。在尝试使用它之前,应该将变量设置为数据处理类的有效实例