Android 2 sqlite database tables in the same listview adapter - android

I have made an android SQLite database with two tables, each of them are performing in separate activities. And I'm trying to put them in the same listview.
This is my activity where the listview is.
public class MainActivity extends ActionBarActivity {
ListView lv;
SQLController dbcon;
TextView incomeID_tv, incomePayer_tv, incomeAmount_tv;
TextView incomeDate_tv, incomeCategory_tv, incomePayments_tv;
TextView expenseID_tv, expensePayee_tv, expenseAmount_tv;
TextView expenseDate_tv, expenseCategory_tv, expensePayments_tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbcon = new SQLController(this);
dbcon.open();
lv = (ListView) findViewById(R.id.incomeList_id);
Cursor cursor = dbcon.readIncomeData();
String[] from = new String[] { DBHelper.INCOME_ID, DBHelper.INCOME_AMOUNT, DBHelper.INCOME_PAYER,
DBHelper.INCOME_DATE, DBHelper.INCOME_CATEGORY, DBHelper.INCOME_PAYMENTS};
int[] to = new int[] { R.id.income_id, R.id.income_amount, R.id.income_payer, R.id.income_date,
R.id.income_category, R.id.income_payments};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
MainActivity.this, R.layout.income_entry, cursor, from, to);
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
Cursor ecursor = dbcon.readExpenseData();
String[] efrom = new String[] { DBHelper.EXPENSE_ID, DBHelper.EXPENSE_AMOUNT, DBHelper.EXPENSE_PAYEE,
DBHelper.EXPENSE_DATE, DBHelper.EXPENSE_CATEGORY, DBHelper.EXPENSE_PAYMENTS};
int[] eto = new int[] { R.id.expense_id, R.id.expense_amount, R.id.expense_payee, R.id.expense_date,
R.id.expense_category, R.id.expense_payments};
SimpleCursorAdapter eadapter = new SimpleCursorAdapter(
MainActivity.this, R.layout.expense_entry, ecursor, efrom, eto);
eadapter.notifyDataSetChanged();
lv.setAdapter(eadapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
incomeID_tv = (TextView) view.findViewById(R.id.income_id);
incomeAmount_tv = (TextView) view.findViewById(R.id.income_amount);
incomePayer_tv = (TextView) view.findViewById(R.id.income_payer);
incomeDate_tv = (TextView) view.findViewById(R.id.income_date);
incomeCategory_tv = (TextView) view.findViewById(R.id.income_category);
incomePayments_tv = (TextView) view.findViewById(R.id.income_payments);
String incomeID = incomeID_tv.getText().toString();
String incomeAmount = incomeAmount_tv.getText().toString();
String incomePayer = incomePayer_tv.getText().toString();
String incomeDate = incomeDate_tv.getText().toString();
String incomeCategory = incomeCategory_tv.getText().toString();
String incomePayments = incomePayments_tv.getText().toString();
Intent modify_intent = new Intent(getApplicationContext(),
IncomeEdit.class);
modify_intent.putExtra("incomeID", incomeID);
modify_intent.putExtra("newIncomeAmount", incomeAmount);
modify_intent.putExtra("newIncomePayer", incomePayer);
modify_intent.putExtra("newIncomeDate", incomeDate);
modify_intent.putExtra("newIncomeCategory", incomeCategory);
modify_intent.putExtra("newIncomePayments", incomePayments);
startActivity(modify_intent);
}
});
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
expenseID_tv = (TextView) view.findViewById(R.id.expense_id);
expenseAmount_tv = (TextView) view.findViewById(R.id.expense_amount);
expensePayee_tv = (TextView) view.findViewById(R.id.expense_payee);
expenseDate_tv = (TextView) view.findViewById(R.id.expense_date);
expenseCategory_tv = (TextView) view.findViewById(R.id.expense_category);
expensePayments_tv = (TextView) view.findViewById(R.id.expense_payments);
String expenseID = expenseID_tv.getText().toString();
String expenseAmount = expenseAmount_tv.getText().toString();
String expensePayer = expensePayee_tv.getText().toString();
String expenseDate = expenseDate_tv.getText().toString();
String expenseCategory = expenseCategory_tv.getText().toString();
String expensePayments = expensePayments_tv.getText().toString();
Intent modify_intent = new Intent(getApplicationContext(),
ExpenseEdit.class);
modify_intent.putExtra("expenseID", expenseID);
modify_intent.putExtra("newExpenseAmount", expenseAmount);
modify_intent.putExtra("newExpensePayee", expensePayer);
modify_intent.putExtra("newExpenseDate", expenseDate);
modify_intent.putExtra("newExpenseCategory", expenseCategory);
modify_intent.putExtra("newExpensePayments", expensePayments);
startActivity(modify_intent);
}
});
}
The problem is that it shows just the expenses. I think the problem is from the adapter, but I don't know how to include both of them in the same adapter. :)

set doesn't mean add. If you setAdapter it means the old one (if any) will be replaced. The same goes for the OnItemClickListener.
If the cursors had the same column names, you could combine them however they differ and the adapter has no means to distinguish between the data of the 2 cursors (expenses and incomes).
Furthermore each click listener has type-specific actions like putting specific intent extras. This just means that you want multiple adapters therefore multiple ListView's.
You need to make your table and app design more generic or continue using 2 ListViews.

Related

android how to sync onitemclicklistener listview id and database id

this is a succesor to this question
At first everything worked fine but after 2 deletes the misery starts. The database entries start with ID 1, then 2 and so on. Lets say I have three database entries. The listview IDs for these three entries are 2,1 and 0.
The database entries are 1,2 and 3. 1 and 2 will be deleted with the onitemclicklistener but since the listview doesn´t have an ID 3, the corresponding database entry will never ever be deleted.
So the question is, how can I "sync" those two IDs?
Listview-Class
public class anzeigen extends AppCompatActivity {
private static final String TAG = anlegen.class.getSimpleName();
private static final String FILENAME = TAG + ".kdf";
private List valueList = new ArrayList<String>();
final VorgangDataSource dataSource = new VorgangDataSource(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_anzeigen);
Log.d(TAG,"Die Datenquelle wird geöffnet!");
dataSource.open();
final List<vorgangsdaten> vorgangsdatenList = dataSource.getAllVorgangsDaten();
final ArrayAdapter<vorgangsdaten> VorgangArrayAdapter = new ArrayAdapter<>(
this,
R.layout.mylistlayout,
vorgangsdatenList
);
final ListView lv = (ListView)findViewById(R.id.listView);
lv.setAdapter(VorgangArrayAdapter);
lv.setItemsCanFocus(false);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String s_id = String.valueOf(id);
Log.d(s_id,"id_in_onitem");
String p_id = String.valueOf(position);
Log.d(p_id,"position_on_item");
int pos = position;
vorgangsdatenList.remove(pos);
dataSource.deleteRow(id);
VorgangArrayAdapter.notifyDataSetChanged();
}
});
//ActionBar Costumization
android.support.v7.app.ActionBar ab = getSupportActionBar();
ab.setIcon(R.drawable.search1);
ab.setDisplayShowHomeEnabled(true);
ab.setDisplayUseLogoEnabled(true);
}
#Override
protected void onDestroy() {
super.onDestroy();
dataSource.close();
}
}
deleteRow-Method:
public void deleteRow(long id){
String s_id;
s_id = String.valueOf(id);
Log.d(s_id,"id_value");
database.delete(VorgangDbHelper.TABLE_VORGAENGE_LIST,VorgangDbHelper.COLUMN_ID + " = ?", new String[] {s_id});
long deleteID = database.delete(VorgangDbHelper.TABLE_VORGAENGE_LIST,VorgangDbHelper.COLUMN_ID + " = ?", new String[] {s_id});
String s_del = String.valueOf(deleteID);
Log.d(s_del,"delete_row_value");
}
If you need more code just let me know :)
You have no synchronicity between your Database and the ListView items.
When selecting the data, select the ID from the table, and keep it in memory as well.
Since vorgangsdaten looks german or sweden, I am having trouble understanding the meaning of those words. The ListView has its own "id" for each item, to keep a list of them shown, and the rest "hidden". What you must do is have an Object with details that are syncronized with the database, and when a list item is clicked, the "list id" is used to query an Object and delete from the database.
An example would be:
ArrayList<MyObject> arrayListData = new ArrayList<>();
ArrayList<String> arrayListNames = new ArrayList<>();
MyObject stuffs = database.query(); // In here, fetch the data
/* I am simplifing the MyObject to [String name, String aValue, int aNumber] */
for(MyObject s: stuffs){
arrayListData.add(s);
arrayListNames.add(s.name);
}
arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
arrayListNames
);
listView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MyObject thing = arrayListData.get(position);
database.delete(thing.aNumber);
}
}
);
listView.setAdapter(arrayAdapter);
After trying Bonattis answer and experimenting a little bit I found another answer.
deleteRow-Method
public void deleteRow(long id){
String s_id; //String for long id
s_id = String.valueOf(id); //assign String value of id
String s_rowId = null; //String for rowid
long rowId = 0;
long deleteId = 0;
String s_deleteId = null;
Log.d(s_id,"id_value");
Cursor cursor = database.query(VorgangDbHelper.TABLE_VORGAENGE_LIST,columns,null,null,null,null,null);
if(cursor.moveToFirst()) {
s_rowId = cursor.getString(cursor.getColumnIndex(VorgangDbHelper.COLUMN_ID));
rowId = Long.parseLong(s_rowId);
deleteId = rowId + id;
s_deleteId = String.valueOf(deleteId);
Log.d(s_rowId,"rowID");
Log.d(s_deleteId,"deleteID");
}
database.delete(VorgangDbHelper.TABLE_VORGAENGE_LIST,VorgangDbHelper.COLUMN_ID + " = ?", new String[] {s_deleteId});
}
How does it work now?
So the deleteRow-Method(dRM) gets the id of the first database entry (s_rowId) and converts it to long (rowId).
Now I take the long id passed from the listview and add it to rowId which is my deleteId. With this I have the correct database value to what I clicked in the listview and can pass it over to database.delete

Android: ListView and per list item onClick action

I've populated a Listview, adapting data from database. And of course per list item have same layout. Inside this layout there are some buttons, checkboxs and other widgets.
Now I want to set onClickListenser. How to achieve that?
Here is the overview:
What I have:
private void populateListView(){
DatabaseHandler db = new DatabaseHandler(this);
Cursor alarms = db.getAllAlarms();
startManagingCursor(alarms);
String[] time = new String[]{DatabaseHandler.KEY_TIME};
int[] toViewIDs = new int[]{R.id.timeTitle};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
this,
R.layout.per_alarm_activity,
alarms,
time,
toViewIDs
);
ListView listView = (ListView) findViewById(R.id.allAlarmsView);
listView.setAdapter(adapter);
mTimeView = (TextView) findViewById(R.id.timeTitle);
mAmPmTextView = (TextView) findViewById(R.id.amPmTextView);
mAlarmOnOff = (Switch) findViewById(R.id.alarmOnOff);
mRepeatCheck = (CheckBox) findViewById(R.id.repeatCheckBox);
mDrop = (ImageView) findViewById(R.id.arrowDown);
mUp = (ImageView) findViewById(R.id.arrowUp);
}
Try this
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {
CheckBox mRepeatCheck =((CheckBox)view.findViewById(R.id.repeatCheckBox));
//same code goes for othe buttons, imageview etc
}
});

filling ListView from database in Android

I'm new in Android programming and I'm wondering witch is the most appropriate way to fill a ListView from DataBase.
Here the method I'm using in database to get my items
// Getting All stats
public List<StatParcours> getAllSats() {
List<StatParcours> statList = new ArrayList<StatParcours>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_STATS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
StatParcours stat = new StatParcours();
stat.setID(Integer.parseInt(cursor.getString(0)));
stat.setDate(cursor.getString(1));
stat.setDuration(cursor.getString(2));
stat.setDistance(Double.parseDouble(cursor.getString(3)));
stat.setSpeed(Double.parseDouble(cursor.getString(4)));
stat.setCondition(cursor.getString(5));
// Adding contact to list
statList.add(stat);
} while (cursor.moveToNext());
}
// return contact list
return statList;
}
and in the main activity, I'm using this. I know there is something wrong with the populateMyStatsList method, but I still don't know how to fix it.
public class History extends Activity {
public DatabaseHandler db;
private List<StatParcours> MyStats = new ArrayList<StatParcours>();
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i("oncreate", "ok");
super.onCreate(savedInstanceState);
setContentView(R.layout.history);
populateMyStatsList ();
populateListView();
registerClickCallback();
}
private void populateMyStatsList (){
MyStats = db.getAllSats();
}
private void populateListView() {
ArrayAdapter<StatParcours> adapter = new MyListAdapter();
ListView list = (ListView) findViewById(R.id.HistListView);
list.setAdapter(adapter);
Log.i("Populate", "ok");
}
private void registerClickCallback() {
ListView list = (ListView) findViewById(R.id.HistListView);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked,
int position, long id) {
StatParcours clickedCar = MyStats.get(position);
String message = "You clicked position " + position
+ " Which is car make " + clickedCar.getDate();
Toast.makeText(History.this, message, Toast.LENGTH_LONG).show();
}
});
}
private class MyListAdapter extends ArrayAdapter<StatParcours> {
public MyListAdapter() {
super(History.this, R.layout.item_view, MyStats);
Log.i("MyListAdapter", "ok");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if (itemView == null) {
Log.i("Make sure", "ok");
itemView = getLayoutInflater().inflate(R.layout.item_view, parent, false);
}
Log.i("getview", "ok");
StatParcours currentStat = MyStats.get(position);
TextView makeText = (TextView) itemView.findViewById(R.id.item_txtMake);
makeText.setText(currentStat.getDate());
TextView yearText = (TextView) itemView.findViewById(R.id.item_txtYear);
yearText.setText("" + currentStat.getDistance());
TextView condionText = (TextView) itemView.findViewById(R.id.item_txtCondition);
condionText.setText(currentStat.getCondition());
return itemView;
}
}
}
You need to use a SimpleCursor Adapter. I can't reach the developer site for the documentation but here is an example with your code above.
EDIT: Here is the link to the android developer website.
http://developer.android.com/reference/android/widget/SimpleCursorAdapter.html
SECOND EDIT: This would go in the populateListView()
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_STATS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Set your layout to int[]
int[] to = new int[]{R.id.item_txtMake,R.id.item_txtYear,R.id.item_txtCondition};
//set your columns to string[]; fill in your actual column names
string[] from = new string[]{"make","year","condition"};
//set up adapter
SimpleCursorAdapter adapter = new SimpleCursorAdapter(getActivity(),R.layout.item_view, cursor, from,to,null);
//set adapter to listview
ListView list = (ListView) findViewById(R.id.HistListView);
list.setAdapter(adapter);
Since you only have TextView in your ListView you can just simply use SimpleCursorAdapter.
// Getting All stats
public Cursor getAllSats() {
List<StatParcours> statList = new ArrayList<StatParcours>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_STATS;
SQLiteDatabase db = this.getWritableDatabase();
return db.rawQuery(selectQuery, null);
}
And in your History class
public class History extends Activity {
public DatabaseHandler db;
private List<StatParcours> MyStats = new ArrayList<StatParcours>();
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.i("oncreate", "ok");
super.onCreate(savedInstanceState);
setContentView(R.layout.history);
Cursor c = getAllSats();
String[] fromColumns = {Your database column name for date,
Your database column name for distance,
Your database column name for condition};
int[] toViews = {R.id.item_txtMake,
R.id.item_txtYear,
R.id.item_txtCondition};
adapter = new SimpleCursorAdapter(this, R.layout.item_view,
c, fromColumns, toViews, 0);
ListView list = (ListView) findViewById(R.id.HistListView);
list.setAdapter(adapter);
registerClickCallback();
}

How can i convert this code so i can get the row from list view

I want to be able to fetch a row from a list view and populate textViews in a different activity. I want to be able to do this onclick of an item with the list view..
public class CBFilter extends Activity {
ListView RecipeNames;
Cursor cursor;
SimpleCursorAdapter adapter;
CBDataBaseHelper data;
SQLiteDatabase data2;
TextView RecipeText;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
RecipeNames = (ListView) findViewById(R.id.List1);
RecipeNames.setTextFilterEnabled(true);
RecipeText = (TextView) findViewById(R.id.recipeText);
adapter = new SimpleCursorAdapter (this, 0, cursor, null, null);
data = new CBDataBaseHelper(this);
data.open();
cursor = data.query();
startManagingCursor(cursor);
String[] from = {CBDataBaseHelper.KEY_NAME};
int[] to = { R.id.recipeText};
adapter = new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
RecipeNames.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
public void CreateNew(View view){
Intent myIntent = new Intent(this, CBCreate.class);
startActivity(myIntent);
}
}
How can i convert this code in order to achieve the required functionality.. thanks Stefan
try like this
public void onListItemClick(ListView parent, View v, int position, long id) {
String string = from[position]); // this depends on your Adapter ...
Intent i = new Intent(CheckData.this,ShowData.class);
i.putExtra("SELECTED", string);
startActivity(i);
i got it from this link , it will be use full for you :
Use of SQLite

How to click a ListView item in Android

I'm trying to have another activity launch when a list item gets clicked. Below is my code:
public class AvoidForeclosure extends CustomListTitle {
/** Called when the activity is first created. */
private DbAdapter db;
private SimpleCursorAdapter clients;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView list = getListView();
setContentView(R.layout.main);
this.title.setText("Avoid Foreclosure");
db = new DbAdapter(this);
db.open();
fillData();
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick( AdapterView<?> parent, View view, int position, long id ) {
int viewId = view.getId();
TextView theView = (TextView) findViewById(viewId);
String name = theView.getText().toString();
Cursor clientData = db.getClientByName(name);
Intent intent = new Intent();
intent.setClass(view.getContext(), CurrentMarketValue.class);
intent.putExtra("clientId", clientData.getInt(0));
startActivity(intent);
}
});
}
private void fillData() {
// Get all of the notes from the database and create the item list
Cursor c = db.fetchAllClients();
startManagingCursor(c);
String[] from = new String[] { DbAdapter.KEY_NAME };
int[] to = new int[] { R.id.text1 };
// Now create an array adapter and set it to display using our row
clients = new SimpleCursorAdapter(this, R.layout.clientsrow, c, from, to);
setListAdapter(clients);
}
}
Yet when I click it, nothing happens at all. Any ideas?
Try switching this line:
ListView list = getListView();
to be after this one:
setContentView(R.layout.main);
Otherwise you'll be getting a handle to the ListActivity's default layout's ListView, rather than R.layout.main's listview (which is the one you really want).

Categories

Resources