为什么我无法访问getwritabledatabase
中的public void onActivityResult
,而getWritabledatabase
仍然无法解析dbhelper
。在这里,我编辑代码,并将public class AndroidListViewCursorAdaptorActivity extends Activity {
Button btnimport;
private SimpleCursorAdapter dataAdapter;
public static final int requestcode = 1;
CountriesDbAdapter dbHelper = new CountriesDbAdapter(this);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper = new CountriesDbAdapter(this);
dbHelper.open();
//Clean all data
dbHelper.deleteAllCountries();
//Generate ListView from SQLite Database
displayListView();
btnimport = (Button) findViewById(R.id.btnupload);
btnimport.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder alertdialog = new AlertDialog.Builder(AndroidListViewCursorAdaptorActivity.this);
alertdialog.setTitle("Confirm Import...");
alertdialog.setMessage("Are you sure you want to Import Data?");
alertdialog.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
Intent fileintent = new Intent(Intent.ACTION_GET_CONTENT);
fileintent.setType("gagt/sdf");
try {
startActivityForResult(fileintent, requestcode);
} catch (ActivityNotFoundException e) {
//empty
}
}
});
alertdialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(),"Import Canceled" ,Toast.LENGTH_SHORT ).show();
}
});
alertdialog.show();
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null)
return;
switch (requestCode) {
case requestcode:
String filepath = data.getData().getPath();
dbHelper = new CountriesDbAdapter(getApplicationContext());
SQLiteDatabase db = dbHelper.getWritableDatabase();
String tableName = "Countsheet";
db.execSQL("delete from " + tableName);
try {
if (resultCode == RESULT_OK) {
try {
FileReader file = new FileReader(filepath);
BufferedReader buffer = new BufferedReader(file);
ContentValues contentValues = new ContentValues();
String line = "";
db.beginTransaction();
while ((line = buffer.readLine()) != null) {
String[] str = line.split(",", 5); // defining 5 columns with null or blank field //values acceptance
//Id, category,code,Description,Unit,Quantity
String company = str[0].toString();
String Name = str[1].toString();
String Price = str[2].toString();
String units = str[3].toString();
String quants = str[4].toString();
contentValues.put("Category", company);
contentValues.put("Code", Name);
contentValues.put("Description", Price);
contentValues.put("Unit", units);
contentValues.put("Quantity", quants);
db.insert(tableName, null, contentValues);
// lbl.setText("Successfully Updated Database.");
}
db.setTransactionSuccessful();
db.endTransaction();
} catch (IOException e) {
if (db.inTransaction())
db.endTransaction();
Dialog d = new Dialog(this);
d.setTitle(e.getMessage().toString() + "first");
d.show();
}
} else {
if (db.inTransaction())
db.endTransaction();
Dialog d = new Dialog(this);
d.setTitle("Only CSV files allowed");
d.show();
}
} catch (Exception ex) {
if (db.inTransaction())
db.endTransaction();
Dialog d = new Dialog(this);
d.setTitle(ex.getMessage().toString() + "second");
d.show();
}
}
Toast.makeText(AndroidListViewCursorAdaptorActivity.this,"data Imported",Toast.LENGTH_SHORT).show();
}
private void displayListView() {
Cursor cursor = dbHelper.fetchAllCountries();
// The desired columns to be bound
String[] columns = new String[] {
CountriesDbAdapter.KEY_CAT,
CountriesDbAdapter.KEY_CODE,
CountriesDbAdapter.KEY_DESC,
CountriesDbAdapter.KEY_UNIT,
CountriesDbAdapter.KEY_QUANTITY
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.category,
R.id.code,
R.id.description,
R.id.unit,
R.id.quantity
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(
this, R.layout.country_info,
cursor,
columns,
to,
0);
ListView listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the state's capital from this row in the database.
String countryCode =
cursor.getString(cursor.getColumnIndexOrThrow("Code"));
Toast.makeText(getApplicationContext(),
countryCode, Toast.LENGTH_SHORT).show();
}
});
EditText myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
dataAdapter.getFilter().filter(s.toString());
}
});
dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return dbHelper.fetchCountriesByName(constraint.toString());
}
});
}
}
声明为全局,但我仍然收到错误:
//这里是logcat
异常:尝试调用虚方法 &#39; android.database.sqlite.SQLiteDatabase android.database.sqlite.SQLiteOpenHelper.getWritableDatabase()&#39;在...上 null对象引用
这是我的代码:
public static final String KEY_ROWID = "_id";
public static final String KEY_CAT = "Category";
public static final String KEY_CODE = "Code";
public static final String KEY_DESC = "Description";
public static final String KEY_UNIT = "Unit";
public static final String KEY_QUANTITY = "Quantity";
private static final String TAG = "CountriesDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_NAME = "Count";
private static final String SQLITE_TABLE = "Countsheet";
private static final int DATABASE_VERSION = 1;
private final Context mCtx;
private static final String DATABASE_CREATE =
"CREATE TABLE if not exists " + SQLITE_TABLE + " (" +
KEY_ROWID + " integer PRIMARY KEY autoincrement," +
KEY_CAT + "," +
KEY_CODE + "," +
KEY_DESC + "," +
KEY_UNIT + "," +
KEY_QUANTITY + "," +
" UNIQUE (" + KEY_CODE +"));";
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.w(TAG, DATABASE_CREATE);
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + SQLITE_TABLE);
onCreate(db);
}
}
public CountriesDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public CountriesDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
if (mDbHelper != null) {
mDbHelper.close();
}
}
public long createCountry(String cat, String code, String desk,
String unit, String quantity) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_CAT, cat);
initialValues.put(KEY_CODE, code);
initialValues.put(KEY_DESC, desk);
initialValues.put(KEY_UNIT, unit);
initialValues.put(KEY_QUANTITY, quantity);
return mDb.insert(SQLITE_TABLE, null, initialValues);
}
public boolean deleteAllCountries() {
int doneDelete = 0;
doneDelete = mDb.delete(SQLITE_TABLE, null , null);
Log.w(TAG, Integer.toString(doneDelete));
return doneDelete > 0;
}
public Cursor fetchCountriesByName(String inputText) throws SQLException {
Log.w(TAG, inputText);
Cursor mCursor = null;
if (inputText == null || inputText.length () == 0) {
mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_CAT, KEY_CODE, KEY_DESC, KEY_UNIT,KEY_QUANTITY},
null, null, null, null, null,null);
}
else {
mCursor = mDb.query(true, SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_CAT, KEY_CODE, KEY_DESC, KEY_UNIT,KEY_QUANTITY},
KEY_DESC + " like '%" + inputText + "%'", null,
null, null, null, null);
}
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor fetchAllCountries() {
Cursor mCursor = mDb.query(SQLITE_TABLE, new String[] {KEY_ROWID,
KEY_CAT, KEY_CODE, KEY_DESC, KEY_UNIT,KEY_QUANTITY},
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public void insertSomeCountries() throws IOException {
}
}
这是我的CountriesDbAdapter.class: 公共类CountriesDbAdapter {
public function result(){
// Your variable is here:
var_dump($_POST['data']);
// echo json_encode($_POST['data']);
die();
}