我有2个android sqlite数据库,我试图在同一个列表视图中看到它们,但只显示其中一个。
这是我的MainActivity,它显示了listview。
public class MainActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.tubapps.accountdb.MESSAGE";
private ListView obj, obj1;
DBHelper mydb;
DBHelperExpense mydb1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb = new DBHelper(this);
ArrayList array_list = mydb.getAllIncomes();
mydb1 = new DBHelperExpense(this);
ArrayList array_list1 = mydb1.getAllExpenses();
ArrayAdapter arrayAdapter =
new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list);
ArrayAdapter arrayAdapter1 =
new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list1);
//adding it to the list view.
obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
obj1 = (ListView)findViewById(R.id.listView1);
obj1.setAdapter(arrayAdapter1);
obj.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
int id_To_Search = arg2 + 1;
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id_To_Search);
Intent intent = new Intent(getApplicationContext(), tubapps.datepickerdb.IncomeActivity.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
});
obj1.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
int id_To_Search = arg2 + 1;
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id_To_Search);
Intent intent = new Intent(getApplicationContext(),tubapps.datepickerdb.ExpenseActivity.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
Intent intent = null;
switch(item.getItemId())
{
case R.id.income_id:
Bundle dataBundle_Income = new Bundle();
dataBundle_Income.putInt("id", 0);
intent = new Intent(getApplicationContext(),tubapps.datepickerdb.IncomeActivity.class);
intent.putExtras(dataBundle_Income);
startActivity(intent);
return true;
case R.id.expense_id:
Bundle dataBundle_Expense = new Bundle();
dataBundle_Expense.putInt("id", 0);
intent = new Intent(getApplicationContext(),tubapps.datepickerdb.ExpenseActivity.class);
intent.putExtras(dataBundle_Expense);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public boolean onKeyDown(int keycode, KeyEvent event) {
if (keycode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keycode, event);
}
}
这是我的收入数据库。
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "MyDBIncome.db";
public static final String INCOME_TABLE_NAME = "incomes";
public static final String INCOME_COLUMN_ID = "id";
public static final String INCOME_COLUMN_AMOUNT = "amount";
public static final String INCOME_COLUMN_PAYER = "payer";
public static final String INCOME_COLUMN_DATE = "date";
public static final String INCOME_COLUMN_PAYMENTS = "payments";
public static final String INCOME_COLUMN_CATEGORY = "category";
private HashMap hp;
public DBHelper(Context context)
{
super(context, DATABASE_NAME , null, 8);
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table incomes " +
"(id integer primary key, amount text, payer text, date text, payments text, category text)"
);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS incomes");
onCreate(db);
}
public boolean insertIncome (String amount, String payer, String date, String payments, String category)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("amount", amount);
contentValues.put("payer", payer);
contentValues.put("date", date);
contentValues.put("payments", payments);
contentValues.put("category", category);
db.insert("incomes", null, contentValues);
return true;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from incomes where id="+id+"", null );
return res;
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, INCOME_TABLE_NAME);
return numRows;
}
public boolean updateIncome (Integer id, String amount, String payer, String date, String payments, String category)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("amount", amount);
contentValues.put("payer", payer);
contentValues.put("date", date);
contentValues.put("payments", payments);
contentValues.put("category", category);
db.update("incomes", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Integer deleteIncome (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("incomes",
"id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList getAllIncomes()
{
ArrayList array_list = new ArrayList();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from incomes", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(INCOME_COLUMN_PAYER)));
res.moveToNext();
}
return array_list;
}
}
这是我的费用数据库。
public class DBHelperExpense extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "MyDBExpense.db";
public static final String EXPENSE_TABLE_NAME = "expenses";
public static final String EXPENSE_COLUMN_ID = "id";
public static final String EXPENSE_COLUMN_AMOUNT = "amount";
public static final String EXPENSE_COLUMN_PAYEE = "payee";
public static final String EXPENSE_COLUMN_DATE = "date";
public static final String EXPENSE_COLUMN_PAYMENTS = "payments";
public static final String EXPENSE_COLUMN_CATEGORY = "category";
private HashMap hp;
public DBHelperExpense(Context context)
{
super(context, DATABASE_NAME , null, 8);
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table expenses " +
"(id integer primary key, amount text, payee text, date text," +
" payments text, category text)"
);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS expenses");
onCreate(db);
}
public boolean insertExpense (String amount, String payee, String date, String payments, String category)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("amount", amount);
contentValues.put("payee", payee);
contentValues.put("date", date);
contentValues.put("payments", payments);
contentValues.put("category", category);
db.insert("expenses", null, contentValues);
return true;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from expenses where id="+id+"", null );
return res;
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, EXPENSE_TABLE_NAME);
return numRows;
}
public boolean updateExpense (Integer id, String amount, String payee, String date, String payments, String category)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("amount", amount);
contentValues.put("payee", payee);
contentValues.put("date", date);
contentValues.put("payments", payments);
contentValues.put("category", category);
db.update("expenses", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Integer deleteExpense (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("expenses",
"id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList getAllExpenses()
{
ArrayList array_list1 = new ArrayList();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from expenses", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list1.add(res.getString(res.getColumnIndex(EXPENSE_COLUMN_PAYEE)));
res.moveToNext();
}
return array_list1;
}
}
当我尝试保存收入时,它没有显示在列表视图中,它甚至没有在logcat中出错。
这是LogCat。
02-10 07:02:04.597 2264-2264/tubapps.datepickerdb W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40a13300)
02-10 07:02:04.697 2264-2264/tubapps.datepickerdb E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{tubapps.datepickerdb/tubapps.datepickerdb.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at tubapps.datepickerdb.MainActivity.onCreate(MainActivity.java:57)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
现在我有这个错误。这是LogCat。
02-10 07:10:54.328 2382-2382/tubapps.datepickerdb E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{tubapps.datepickerdb/tubapps.datepickerdb.ExpenseActivity}: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:418)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
at tubapps.datepickerdb.ExpenseActivity.onCreate(ExpenseActivity.java:76)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
这是费用活动。
public class ExpenseActivity extends ActionBarActivity {
int from_Where_I_Am_Coming = 0;
private DBHelperExpense mydb;
TextView payee;
TextView expense_amount;
Spinner payments_expense;
Spinner expense_category;
int id_To_Update = 0;
private Calendar calendar;
private TextView dateView;
private int year, month, day;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_expense);
payee = (TextView) findViewById(R.id.input_payee);
expense_amount = (TextView) findViewById(R.id.input_expense);
dateView = (TextView) findViewById(R.id.input_date);
dateView = (TextView) findViewById(R.id.input_date);
calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
showDate(year, month+1, day);
payments_expense = (Spinner) findViewById(R.id.expenseNumber);
ArrayAdapter<CharSequence> payments_expense_adapter = ArrayAdapter.createFromResource(this,
R.array.recurring_expense, android.R.layout.simple_spinner_item);
payments_expense_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
payments_expense.setAdapter(payments_expense_adapter);
expense_category = (Spinner) findViewById(R.id.expenseCategory);
ArrayAdapter<CharSequence> category_expense_adapter = ArrayAdapter.createFromResource(this,
R.array.category_expense, android.R.layout.simple_spinner_item);
category_expense_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
expense_category.setAdapter(category_expense_adapter);
mydb = new DBHelperExpense(this);
Bundle extras = getIntent().getExtras();
if (extras != null) {
int Value = extras.getInt("id");
if (Value > 0) {
Cursor rs = mydb.getData(Value);
id_To_Update = Value;
rs.moveToFirst();
String amo = rs.getString(rs.getColumnIndex(DBHelperExpense.EXPENSE_COLUMN_AMOUNT));
String pye = rs.getString(rs.getColumnIndex(DBHelperExpense.EXPENSE_COLUMN_PAYEE));
String dat = rs.getString(rs.getColumnIndex(DBHelperExpense.EXPENSE_COLUMN_DATE));
String pym = rs.getString(rs.getColumnIndex(DBHelperExpense.EXPENSE_COLUMN_PAYMENTS));
String cat = rs.getString(rs.getColumnIndex(DBHelperExpense.EXPENSE_COLUMN_CATEGORY));
if (!rs.isClosed()) {
rs.close();
}
Button save = (Button) findViewById(R.id.btn_save);
save.setVisibility(View.INVISIBLE);
Button cancel = (Button) findViewById(R.id.btn_cnc);
cancel.setVisibility(View.INVISIBLE);
expense_amount.setText(amo);
expense_amount.setFocusable(false);
expense_amount.setClickable(false);
payee.setText(pye);
payee.setFocusable(false);
payee.setClickable(false);
dateView.setText(dat);
dateView.setFocusable(false);
dateView.setClickable(false);
payments_expense.setSelection(getIndex(payments_expense, pym));
payments_expense.setFocusable(false);
payments_expense.setClickable(false);
expense_category.setSelection(getIndex(expense_category, cat));
expense_category.setFocusable(false);
expense_category.setClickable(false);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
Bundle extras = getIntent().getExtras();
if (extras != null) {
int Value = extras.getInt("id");
if (Value > 0) {
getMenuInflater().inflate(R.menu.menu_expense, menu);
} else {
getMenuInflater().inflate(R.menu.menu_main, menu);
}
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
switch (item.getItemId()) {
case R.id.Edit_Expense:
Button save = (Button) findViewById(R.id.btn_save);
save.setVisibility(View.VISIBLE);
Button cancel = (Button) findViewById(R.id.btn_cnc);
cancel.setVisibility(View.VISIBLE);
expense_amount.setEnabled(true);
expense_amount.setFocusableInTouchMode(true);
expense_amount.setClickable(true);
payee.setEnabled(true);
payee.setFocusableInTouchMode(true);
payee.setClickable(true);
dateView.setEnabled(true);
dateView.setFocusableInTouchMode(true);
dateView.setClickable(true);
payments_expense.setEnabled(true);
payments_expense.setFocusableInTouchMode(true);
payments_expense.setClickable(true);
expense_category.setEnabled(true);
expense_category.setFocusableInTouchMode(true);
expense_category.setClickable(true);
return true;
case R.id.Delete_Expense:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.deleteIncome)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mydb.deleteExpense(id_To_Update);
Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(), tubapps.datepickerdb.MainActivity.class);
startActivity(intent);
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
AlertDialog d = builder.create();
d.setTitle("Are you sure");
d.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void run(View view) {
Bundle extras = getIntent().getExtras();
if (extras != null) {
int Value = extras.getInt("id");
if (Value > 0) {
if (mydb.updateExpense(id_To_Update, expense_amount.getText().toString(), payee.getText().toString()
, dateView.getText().toString(), payments_expense.getSelectedItem().toString(),
expense_category.getSelectedItem().toString())) {
Intent intent = new Intent(getApplicationContext(), tubapps.datepickerdb.MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show();
}
} else {
if (mydb.insertExpense(expense_amount.getText().toString(), payee.getText().toString()
, dateView.getText().toString(), payments_expense.getSelectedItem().toString(),
expense_category.getSelectedItem().toString())) {
} else {
}
Intent intent = new Intent(getApplicationContext(), tubapps.datepickerdb.MainActivity.class);
startActivity(intent);
}
}
}
@SuppressWarnings("deprecation")
public void setDate(View view) {
showDialog(999);
}
@Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
if (id == 999) {
return new DatePickerDialog(this, myDateListener, year, month, day);
}
return null;
}
private DatePickerDialog.OnDateSetListener myDateListener
= new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
// arg1 = year
// arg2 = month
// arg3 = day
showDate(arg1, arg2+1, arg3);
}
};
private void showDate(int year, int month, int day) {
dateView.setText(new StringBuilder().append(day).append("/")
.append(month).append("/").append(year));
}
private int getIndex(Spinner spinner, String myString){
int index = 0;
for (int i=0;i<spinner.getCount();i++){
if (spinner.getItemAtPosition(i).equals(myString)){
index = i;
}
}
return index;
}
}
答案 0 :(得分:0)
您正在使用两个适配器和两个ArrayLists,您可以只使用其中一个。数据库代码似乎有效,但不是使用泛型类的最佳方法。
编辑:
尝试改变这一点:
mydb = new DBHelper(this);
ArrayList array_list = mydb.getAllIncomes();
mydb1 = new DBHelperExpense(this);
ArrayList array_list1 = mydb1.getAllExpenses();
ArrayAdapter arrayAdapter =
new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list);
ArrayAdapter arrayAdapter1 =
new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list1);
与此:
mydb = new DBHelper(this);
mydb1 = new DBHelperExpense(this);
ArrayList array_list = mydb.getAllIncomes();
array_list.addAll(mydb1.getAllExpenses());
ArrayAdapter arrayAdapter =
new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list);
希望有所帮助