So i have a problem with my listview when i delete data from my database.
The problem is that some other items in my list view get mest up
i have noted that when i delete the second from the bottom the problem occurs
Database
//getRowRevers
public Cursor getAllRowre(){
String where=null;
String orderBy = ID_KEY + " DESC";
Cursor cursor=db.query(true, DATABASE_TABLE, ALL_KEY, where, null, null, null,ID_KEY + " DESC", null);
if(cursor!=null){
cursor.moveToFirst();
}
return cursor;
}
//delete
public boolean deleatRow(String idRow){
String where=ID_KEY+"="+idRow;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleatAll(){
Cursor cursor=getAllRowre();
long idRow=cursor.getColumnIndexOrThrow(ID_KEY);
if(cursor.moveToFirst()){
do{
deleatRow(cursor.getString((int) idRow));
}while(cursor.moveToNext());
}
}
So here is how i managed to get the list view working i think this method is not the best and maybe this is the reason and i don't know how to do it in a different way
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
int mySuperInt=dbJ.countCases()+ 1 -position-2;
Intent myIntent = new Intent(getActivity(), JornalListViewClick.class);
myIntent.putExtra("intVariableName",mySuperInt);
startActivity(myIntent);
}
});
PS the list view is always changing when the user pass data
Related
As the title, I'm trying to get values from a SQLite Database clicking on an Item of a ListView. This ListView shows every value of the database in a DESC order. After clicked on it a Dialog is supposed to appear showing a summary of that value.
this is the onItemClick method:
Val_List.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int pos = position + 1;
String[] projection2 = {
_ID,
DiabeticContract.DiabeticEntry.COLUMN_GLYCAEMIA_VALUES,
DiabeticContract.DiabeticEntry.COLUMN_DATES,
};
Cursor cursor2 = db2.query(
DiabeticContract.DiabeticEntry.TABLE_NAME, // The table to query
projection2, // The columns to return
null, // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // Don't group the rows
null, // Don't filter by row groups
null); // The sort order
cursor2.move(pos);
String date, notes;
int g_val = 0;
g_val = cursor2.getInt(cursor2.getColumnIndexOrThrow(DiabeticContract.DiabeticEntry.COLUMN_GLYCAEMIA_VALUES));
date = cursor2.getString(cursor2.getColumnIndexOrThrow(DiabeticContract.DiabeticEntry.COLUMN_DATES));
//notes = cursor2.getString(cursor2.getColumnIndexOrThrow(DiabeticContract.DiabeticEntry.COLUMN_NOTES));
customDialog(DIALOG_TITLE, date, "");
cursor2.close();
}
});
The problem is that if i click on the first item in the listview the position is equal 1 and it takes the values in the first row of the Database, instead of the last one.
How can i solve that?
Thank you very much!
EDIT:
public class DiabeticCursorAdapter extends CursorAdapter
{
private ImageView check;
public int glyc_value;
public String glyc_date;
public DiabeticCursorAdapter(Context context, Cursor c) {
super(context, c,0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.gly_item_list, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor)
{
TextView glycaemia_value = (TextView) view.findViewById(R.id.Glyc_value);
TextView test_date = (TextView) view.findViewById (R.id.Date_time);
check = (ImageView) view.findViewById(R.id.check_view);
glyc_value = cursor.getInt(cursor.getColumnIndexOrThrow(DiabeticContract.DiabeticEntry.COLUMN_GLYCAEMIA_VALUES));
glyc_date = cursor.getString(cursor.getColumnIndexOrThrow(DiabeticContract.DiabeticEntry.COLUMN_DATES));
checkVal(glyc_value);
glycaemia_value.setText("Glycaemia Value : " + glyc_value + " mg/dl");
test_date.setText("Added : " + glyc_date);
}
private void checkVal(int n)
{
if (n< 75 || n >= 125)
{
check.setImageResource(R.drawable.check_red);
} else
if (n >= 75 && n <100)
{
check.setImageResource(R.drawable.check_green);
} else
if (n >= 100 && n < 125)
{
check.setImageResource(R.drawable.check_yellow);
}
}
}
EDIT 2: the display on listview method
private void DisplayDataValues() {
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String[] projection = {
_ID,
DiabeticContract.DiabeticEntry.COLUMN_GLYCAEMIA_VALUES,
DiabeticContract.DiabeticEntry.COLUMN_DATES,
DiabeticContract.DiabeticEntry.COLUMN_NOTES,
};
// Perform a query on the pets table
Cursor curs = db.query(
DiabeticContract.DiabeticEntry.TABLE_NAME, // The table to query
projection, // The columns to return
null, // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // Don't group the rows
null, // Don't filter by row groups
_ID + " DESC"); // The sort order
DiabeticCursorAdapter adapter = new DiabeticCursorAdapter(this, curs);
Val_List.setAdapter(adapter);
}
EDIT 3: this is the solution: (thanks to #Mike M.)
Val_List.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int pos = position;
curs.moveToPosition(pos);
String date, notes;
int g_val;
g_val = curs.getInt(curs.getColumnIndexOrThrow(DiabeticContract.DiabeticEntry.COLUMN_GLYCAEMIA_VALUES));
date = curs.getString(curs.getColumnIndexOrThrow(DiabeticContract.DiabeticEntry.COLUMN_DATES));
notes = curs.getString(curs.getColumnIndexOrThrow(DiabeticContract.DiabeticEntry.COLUMN_NOTES));
customDialog(DIALOG_TITLE, date, g_val, notes, "");
}
});
I Need to get the id of a selected spinner value from sqlite database in android
public void onItemSelected(AdapterView<?> parent, View view, int position,long id) {
String label = parent.getItemAtPosition(position).toString();
Log.d("label:", label);
}
I need to return the id of the id of the selected value
Try this code
int getId(String label)
{
SqliteDatabase db=this.getWritableDatabase();
Cursor cur=db.rawQuery("SELECT ID FROM TABLENAME WHERE NAME=\""+label+"\"");
cur.moveToFirst();
String ID=cur.getString(0);
return Integer.valueOf(ID);
}
In your MAin activity try this code for your spinner
spin_category.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3)
{
category_id=arg2;
int my_id=db.getID(category_id);
}
public void onNothingSelected(AdapterView<?> arg0)
{
}
});
In You Database class write this function
public int getID(int id)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME, new String[] { KEY_ID, KEY_NAME}, KEY_ID+"=?",
new String[] { String.valueOf(id) }, null);
if(cursor!=null)
if (cursor.getCount() > 0)
{
cursor.moveToFirst();
}
int s = cursor.getInt(cursor.getColumnIndex(KEY_ID));
cursor.close();
db.close();
return s;
}
The first function will get id of selected item in spinner and will pass it to database method and second function will search for that id and return id of that id. As I am not very clear with your requirement. Please comment if you want it in different way.
If your adapter is a SimpleCursorAdapter, you already have the id of the selected one provided by the parameter 'id'. If it is a custom adapter, override the adapter's getItemId() method to return the correct id for a selected row.
You don't really need to do this either:
String label = parent.getItemAtPosition(position).toString();
...since the parameter 'view' already provides the selected item within the parent, i.e. you can do this instead:
String label = view.toString();
public void onItemSelected(AdapterView<?> parent, View view, int position,long id) {
String label = parent.getItemAtPosition(position).toString();
Log.d("label:", label);
}
spinner_referrer_to_type.getSelectedItem().toString();
I have a SQLite database that I am saving user selected data to. This data will be visible in a listview and if you long click on the data it will delete that item. This is working as I see the item disappear from the listview, but when I restart the application and all the listview items are brought back in from the database, everything that was deleted is coming back. I am using this statement:
public void deleteAlarmEntry(int pos){
Log.i("Deleting item from pos: ", String.valueOf(pos));
db.delete(MySQLHelper.TABLE_NAME, MySQLHelper.ID_COL + "='" + pos + "'", null);
}
I can see the statement being called in the logs. Is there a better way to make sure that the statement is executing correctly? Is something wrong here?
Here is my removeItem method called in the MainActivity on long click of the listview item:
public void removeItem(int position) {
alarmItemArray.remove(position);
dataSource.deleteAlarmEntry(position);
alarmAdapter.notifyDataSetChanged();
}
The dataSource.deleteAlarmEntry() calls the above database remove.
Also, on application startup I am bringing the entries into a temp arraylist and then parsing the time to get the adapter arraylist like so:
dataSource = new WeatherDataSource(this);
dataSource.open();
ArrayList<AlarmEntry> alarmEntries = (ArrayList<AlarmEntry>) dataSource.getAllWeatherEntries();
alarmItemArray = getTimeFromEntries(alarmEntries);
alarmAdapter = new ArrayAdapter<String>(this,
R.layout.activity_alarm_item, R.id.time, alarmItemArray);
lv = (MyListView) findViewById(R.id.listview);
lv.setAdapter(alarmAdapter);
Here is the database's getAllWeatherEntries:
public List<AlarmEntry> getAllWeatherEntries(){
List<AlarmEntry> weatherEntry = new ArrayList<AlarmEntry>();
Cursor cursor = db.query(MySQLHelper.TABLE_NAME, cols, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
AlarmEntry m = cursorToEntry(cursor);
weatherEntry.add(m);
Log.i("Get all weather entries", m.getTime());
cursor.moveToNext();
}
cursor.close();
return weatherEntry;
}
You're just passing everything from that item to your query.
In OnContextMenuItemSelected you will need to do something similar to the below; you will need to change the parameters of your deleteAlarmEntry to receive a string instead of an int.
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
String selectedID;
// adapter is the Adapter from creating the listview
selectedID = String.valueOf(adapter.getItemId(info.position));
deleteAlarmEntry(selectedID);
}
You will also need to modify the db.delete to return a number, ie int result = db.delete() per the function. http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
EDIT:
you may want to use OnItemLongClickListener instead of OnLongClickListener
http://developer.android.com/reference/android/widget/AdapterView.OnItemLongClickListener.html
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
String id = String.valueOf(alarmAdapter.getItemId(position);
removeItem(id);
}
});
SECOND EDIT:
Try this for cursoradapter, i'd recommend using a simple cursor adapter:
http://developer.android.com/reference/android/widget/SimpleCursorAdapter.html
String[] from = new String[]{"time"}; //enter your time column name here
int[] to = new int[]{R.id.time};
Cursor cursor = db.query(MySQLHelper.TABLE_NAME, cols, null, null, null, null, null);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,R.layout.activity_alarm_item, cursor, from, to);
lv.setAdapter(adapter);
use,
public void deleteAlarmEntry(int pos) {
db.delete(MySQLHelper.TABLE_NAME, MySQLHelper.ID_COL + "=?", new String[]{pos + ""});
}
I want that as I click on list item the application should load another class and then display the required data on textview by retrieving the data from sqlite database
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Intent intent = new Intent(DictionaryActivity.this,
WordDetails.class);
// Cursor cursor = (Cursor) adapter.getItem(position);
id = wordList.getItemIdAtPosition(position);
intent.putExtra("Word_ID", id);
// cursor.getInt(cursor.getColumnIndex("_id"));
startActivity(intent);
}
this code is in WordDetails class
wordId = getIntent().getIntExtra("WORD_ID", -1);
if (wordId == -1) {
mean = (TextView) findViewById(R.id.mean);
mean.setText("Error");
} else {
SQLiteDatabase db = (new DatabaseHelper(this))
.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT _id ,word, mean FROM Meanings WHERE _id = ?",
new String[] { "" + wordId });
if (cursor.getCount() == 1) {
cursor.moveToFirst();
mean = (TextView) findViewById(R.id.mean);
mean.setText(cursor.getString(cursor.getColumnIndex("mean")));
}
}
When I click on an item "Error" word is being displayed which is supposed to show, but wordTd equals -1. Why this wordId is not getting correct value? Thanks for your help.
The 'keys' used when putting Intent extras are case sensitive. You are putting the id as...
intent.putExtra("Word_ID", id);
...but then trying to get it with...
wordId = getIntent().getIntExtra("WORD_ID", -1);
In other words you're putting Word_ID and trying to get WORD_ID. Change the code so they're both the same and it should work.
The id passed by default to the OnItemClickListener is the row's unique id from the database, there is no need to get it in this manner:
id = wordList.getItemIdAtPosition(position);
Change your OnItemClickListener to this:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(DictionaryActivity.this, WordDetails.class);
intent.putExtra("Word_ID", id);
startActivity(intent);
}
I tried to make an android app, that populate some data from sqlite database to a list view
using ArrayAdapter.
The list where I store data is like this:
private String[] allUserColumns = { MySQLiteHelper.COLUMN_USERID,
MySQLiteHelper.COLUMN_USERNAME };
I want to move to another activity passing the ID related to user name by click at a listview item.
I know that I should use setOnItemClickListener method
but actually I don't know how to do that.
I mean how to get the ID, and how to set the setOnItemClickListener Method to make such task.
please any one can help me with a specific code ?
i have done this with this way
first fire query like
public Cursor columnValues() throws SQLException{
Cursor mCursor = db.query(Player_Table,
new String[] {Player_Name,_id},null,null, null, null, null);
//Cursor mCursor = mDb.rawQuery("Select",null);
if (mCursor != null)
{
mCursor.moveToFirst();
}
return mCursor;
}
then receive like this
ArrayList<String> first = new ArrayList<String>();
ArrayList<String> id_list = new ArrayList<String>();
cursor = dbm.columnValues();
cursor.moveToFirst();
startManagingCursor(cursor);
for(int i=0;i<cursor.getCount();i++){
// Received values of player name
// from player table
String reciv = cursor.getString(cursor.getColumnIndex(DBManager.Player_Name));
String P_id= cursor.getString(cursor.getColumnIndex(DBManager._id));
first.add(reciv);
id_list.add(P_id);
cursor.moveToNext();
}
//ARRAY OF ID
String[] _id = id_list.toArray(new
String[id_list.size()]);
player.setAdapter(new ArrayAdapter<String>
(this,android.R.layout.simple_list_item_1 , first));
player.setOnItemClickListener(Activity.this);
and then the click listener
#Override
public void onItemClick(AdapterView arg0, View arg1, int position,
long id) {
i = new Intent(Add_Modify_Delete_Player.this,
ModifyDeletePlayer.class);
System.out.println(_id[position]);
i.putExtra("Id", _id[position]);
startActivity(i);
}