DeleteFunction(Long) in DatabaseHelper Cannot be applied to java.lang.String - android

Good Day, I'm new to android development and i practice CRUD operation but i got an error in deleting the the selected item on my List View and i want to Update the list view after deleting.
Here's my code for deleting in Database Helper
public void deletegroce(int groceId){
String groceid[] = {String.valueOf(groceId)};
SQLiteDatabase sqdb = this.getWritableDatabase();
sqdb.delete(TABLE_NAME, KEY_GROCE_ID + " = ?", groceid);
sqdb.close();
}
}
And this is my code for my list
public class Grocery_list extends Activity {
ListView lvGorc;
DatabaseHelper dbhelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grocery_list);
lvGorc = (ListView) findViewById(R.id.lvGroc);
dbhelper = new DatabaseHelper(Grocery_list.this);
final ArrayList<String> aList = dbhelper.getAllGroceries();
ArrayAdapter<String> La = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, aList);
lvGorc.setAdapter(La);
lvGorc.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(final AdapterView<?> adapterView, View view, int i, long l) {
AlertDialog.Builder adb = new AlertDialog.Builder(Grocery_list.this);
adb.setTitle("Option");
adb.setMessage("What do you want to do?");
adb.setPositiveButton("Update", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
adb.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dbhelper.deletegroce(i);
}
});
adb.show();
}
});
La.notifyDataSetChanged();
lvGorc.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder adb = new AlertDialog.Builder(Grocery_list.this);
adb.setTitle("Delete?");
adb.setMessage(aList.get(position));
adb.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dbhelper.deletegroce(aList.get(position));
}
});
adb.show();
return true;
}
});
}
}
THANK YOU SO MUCH

Your deleteGroce() method expects an int (groceId), but your ArrayAdapter get() method will return a String value, you need to use Int.parseInt(aList.get(position)) instead of just aList.get(position) in the call method :)

Related

Remove item list from DB MSSQL using ListView.setOnItemLongClickListener Android

I have created a database which is displayed in a ListView using an SimpleAdapter. Now, I want to show a layout which contain (edit & delete ), so when user longClick on an item of the list it will get a dialog to choose if its want to delete or to edit on this item. Now, I'm focusing on delete statement and
I have tried with this code, but it does not work for me, the program always force close when I use this code.
Thanks
#Override
protected void onCreate(Bundle savedInstanceStates){
super.onCreate(savedInstanceStates);
setContentView(R.layout.activity_user_lstview);
userDataListView = (ListView) findViewById(R.id.ListViewUser);
List<Map<String, String>> data = new ArrayList<Map<String, String>>(
String[] from = {"tvId", "tvUsr", "tvPass", "tvDept","tvAuth"};
int[] to = {R.id.tvId, R.id.tvUsr, R.id.tvPass, R.id.tvDept, R.id.tvAuth};
adapter = new SimpleAdapter(UserListView.this, data, R.layout.userlisttemplate, from, to);
userDataListView.setAdapter(adapter);
userDataListView.setLongClickable(true);
userDataListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(),"Clicked item : " +adapter.getItem(position), Toast.LENGTH_LONG).show();
}
});
userDataListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
final int which_item = position;
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(UserListView.this);
dialogBuilder.setIcon(android.R.drawable.ic_dialog_alert);
dialogBuilder.setTitle("Confirmation");
dialogBuilder.setMessage("Choose an option edit or delete data ?");
dialogBuilder.setPositiveButton("Edit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
// Edit
­­
dialogInterface.dismiss();
}
});
dialogBuilder.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
// Delete
data.remove(which_item);
adapter.notifyDataSetChanged();
Toast.makeText(UserListView.this, "Data has been removed", Toast.LENGTH_SHORT).show();
dialogInterface.dismiss();
}
});
dialogBuilder.create().show();
return true;
}
});
}

Android: Search on ListView

I need a quick solution for my problem. I have a ListView, and I want to search from that. Im a kind a starter with the filtering and the adapters, so this is my Fragment's code:
View v;
DB mydb;
ListView listView;
final ArrayList<String> thelist = new ArrayList<>();
final ArrayList<String> deletelist= new ArrayList<>();
boolean torles=false;
String delete; int id;
private ListAdapter listadapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_numberone, container, false);
listView = (ListView) v.findViewById(R.id.list);
mydb = new DB(getActivity());
loadlist();
EditText filter = (EditText)v.findViewById(R.id.filter);
filter.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
getActivity().listadapter.getFilter().filter(s);
//Here is the problem
}
#Override
public void afterTextChanged(Editable s) {
}
});
listView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
id = Integer.parseInt(deletelist.get(i));
delete=thelist.get(i);
AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
alert.setTitle("Title");
alert.setMessage("Message");
alert.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mydb.grade_delete(id);
listView.removeAllViewsInLayout();
thelist.removeAll(thelist);
deletelist.removeAll(deletelist);
loadlist();
}
});
alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
alert.create().show();
}
}
);
return v;
}
public void loadlist() {
Cursor data = mydb.Jegynevlekerdezes();
if (data.getCount() == 0) {
} else {
while (data.moveToNext()) {
thelist.add(data.getString(0)+": "+data.getString(1));
deletelist.add(data.getString(2));
listadapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, thelist);
listView.setAdapter(listadapter);
}
}
}
}
My problem is with this:
getActivity().listadapter.getFilter().filter(s);
The listadapter is wrong, it's show as red. Like I sad, I'm new with the adapter and the searching.

Object cannot be converted to int

I am going to delete the specific data from list view after building the gradle there's an error says "error: incompatible types: Object cannot be converted to int"
Code of DatabaseHelper
public void deletegroce(int groceId){
String groceid[] = { String.valueOf(groceId) };
SQLiteDatabase sqdb = this.getWritableDatabase();
sqdb.delete(TABLE_NAME, KEY_GROCE_ID + " = ?", groceid);
sqdb.close();
}
And here's my full code of Grocery_List and the error is located at line 65 which is "int dave = aList.get(position); dbhelper.deletegroce(dave);"
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grocery_list);
lvGorc = (ListView) findViewById(R.id.lvGroc);
dbhelper = new DatabaseHelper(Grocery_list.this);
final List aList = dbhelper.getAllGroceries();
final ArrayAdapter<String> La = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, aList);
lvGorc.setAdapter(La);
lvGorc.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(final AdapterView<?> adapterView, View view, int i, long l) {
AlertDialog.Builder adb = new AlertDialog.Builder(Grocery_list.this);
adb.setTitle("Option");
adb.setMessage("What do you want to do?");
adb.setPositiveButton("Update", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
adb.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
adb.show();
}
});
lvGorc.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder adb = new AlertDialog.Builder(Grocery_list.this);
adb.setTitle("Delete?");
adb.setMessage("Are you sure you want to delete the selected item?");
adb.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
int dave = aList.get(position);
dbhelper.deletegroce(dave);
La.notifyDataSetChanged();
}
});
adb.show();
return true;
}
});
}
The aList you have defined is a List of objects. the ArrayAdapter<String> accepts all kind of objects lists and it will call toString() method, which all objects have it, to show it in the ListView.
When you try to get an object of aList it returns an object of that index which can not be cast to int.
I think you can simply take the id of your object and pass it into the dbhelper.deletegroce(dave). if your aList is a List of Integer objects you can simply cast it to int by calling:
int dave = (int) aList.get(position);
Your 5th line in OnCreate method which says
final List aList = dbhelper.getAllGroceries();
it doesn't specify that aList is List of Integer. What does your getAllGroceries return?
You should also define your list as final List aList = dbhelper.getAllGroceries();
and make sure dbhelper.getAllGroceries() return List of Integer data.

Android - spinner position value

Im using a Spinner in an AlertDialog as a Filter. When I reopen the Dialog after selecting an item, I want to select the chosen item from before by default. But some kind of magic is happening and I cant understand why the spinner is selecting the wrong item. The item list for the spinner is a String array with numbers from 4 to 42. {"4","6",.."42"}
When I select the first item "4" the position should be 0 and when I reopen the Dialog the exact item should be displayed. But instead it displays the item "10" on position 4.
Code Dialogfragment:
public class FittingSelectionDialogFragment extends DialogFragment {
private String dTitle;
private String[] list;
private int position;
private String filterItem;
private List<String> chosenFilterItems;
public interface FittingSelectionDialogListener {
public void onChosenDialogItem(String filterStrings,int menuPosition);
}
FittingSelectionDialogListener mListener;
public Dialog onCreateDialog(Bundle savedInstanceState){
final Spinner spinner2 = new Spinner(getActivity());
final TextView label = new TextView(getActivity());
final TextView label2 = new TextView(getActivity());
LinearLayout layout = new LinearLayout(getActivity());
layout.setOrientation(LinearLayout.HORIZONTAL);
layout.setGravity(Gravity.CENTER);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(getContext(), R.layout.support_simple_spinner_dropdown_item, list);
spinner2.setAdapter(adapter2);
if(chosenFilterItems.get(position).equals("")) {
spinner2.setSelection(0);
}
else{
spinner2.setSelection(Integer.valueOf(chosenFilterItems.get(position)));
}
label.setText("Rohr AD:");
label.setTextColor(getResources().getColor(R.color.colorParkerBlack2));
label.setTextSize(16);
label.setPadding(60,0,40,0);
label2.setText("mm");
label2.setTextSize(16);
label2.setTextColor(getResources().getColor(R.color.colorParkerBlack2));
dialog.setTitle(getdTitle());
layout.addView(label);
layout.addView(spinner2);
layout.addView(label2);
dialog.setView(layout);
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int spinner2Position, long id) {
filterItem = list[spinner2Position];
chosenFilterItems.set(position,String.valueOf(spinner2Position));
Toast.makeText(getContext(),chosenFilterItems.get(position),Toast.LENGTH_SHORT).show(); //correct value
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
dialog.setPositiveButton("Bestätigen", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
mListener.onChosenDialogItem(filterItem,position);
Toast.makeText(getContext(),chosenFilterItems.get(position),Toast.LENGTH_SHORT).show();//wrong value
dismiss();
}
});
dialog.setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
filterItem = "";
chosenFilterItems.set(position,"");
mListener.onChosenDialogItem(filterItem, position);
}
});
return dialog.create();
}
}
I made two Toasts inside the Listeners. The crazy thing is that in the OnItemSelectedListener the correct position value is displayed. In the PositiveButton OnClickListener is displaying the wrong value. Have you any idea?
I made a workaround by myself. I did not found the mistake by debugging. So I dont work with the position. I use the value to reselect the chosen Item. Not the best way, but works for this small itemlist.
Code:
if(chosenFilterItems.get(position).equals("")) {
spinner2.setSelection(0);
}
else{
for(int i=0; i<list.length;i++){
if(list[i].equals(chosenFilterItems.get(position))){
spinner2.setSelection(i);
}
}
}
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int spinner2Position, long id) {
filterItem = list[spinner2Position];
}
dialog.setPositiveButton("Bestätigen", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
chosenFilterItems.set(position,filterItem);
mListener.onChosenDialogItem(filterItem,position);
dismiss();
}
});
Use Handler and add some delay
int delay = 1000;
runOnUiThread (new Runnable () {
#Override
public void run () {
if(chosenFilterItems.get(position).equals("")) {
spinner2.setSelection(0);
} else {
Integer.valueOf(chosenFilterItems.get(position)));
}
}
}, delay);

Android: app with tab, database changes can be viewed only when closing and reopening app

i've got an app made with tab. one tab use a method get_data() (called from another class) to take data from db.
it works fine, but the changes made from another tab or in the tab incriminated (changed like DELETE or UPDATE) can't be seen, example:
i go in the tab (with a listview) with the data taken from db, then i delete a record, then i go to another tab and then i return to the tab with the list.
i see the deleted row.
if i close the app and reopen it, i see the changes.
there's a way to "reload the database"?
here's the code (view.class), reader from a tab:
public class Bookmarks extends Activity{
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.bookmarks);
final Database info=new Database(this);
final Timer t = new Timer();
info.open();
String data=info.getData();
final String[] data_array = data.split(",");
info.close();
final ListView listView1 = (ListView) findViewById(R.id.list_mia);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, data_array);
listView1.setAdapter(adapter);
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
listView1.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id){
if(data_array[position].startsWith("http://")){
Uri uri=Uri.parse((String) data_array[position]);
Intent intent=new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}else{
alertDialog.setTitle("Content");
alertDialog.setMessage(data_array[position]);
alertDialog.setIcon(R.drawable.ic_launcher);
alertDialog.show();
}
}
});
listView1.setOnItemLongClickListener(new OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> parent, View v, final int position, long id) {
builder.setTitle("Delete")
.setMessage("Are you sure to remove this entry?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
info.open();
info.deleteEntry(position+1);
info.close();
alertDialog.setTitle("Delete");
alertDialog.setMessage("Item deleted successfully!");
alertDialog.setIcon(R.drawable.ic_launcher);
alertDialog.show();
t.schedule(new TimerTask() {
public void run() {
alertDialog.dismiss();
t.cancel();
}
},2000);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {}
})
.show();
return false;
}
});
}
}
and the method called (in db.class):
public String getData() {
String[] columns=new String[]{KEY_ROWID,KEY_CONTENUTO};
Cursor c=ourDatabase.query(DATABASE_TABLE,columns,null,null,null,null,"id");
String result="";
int iRow=c.getColumnIndex(KEY_ROWID);
int iName=c.getColumnIndex(KEY_CONTENUTO);
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
result=result+c.getString(iName)+',';
}
result=result.substring(0, result.length()-1);
return result;
}
can someone help me?
you should create a method like given below, When you delete or update info in database. call this method within the same activity it will fetch the data and reload list.
setData() {
info.open();
String data=info.getData();
final String[] data_array = data.split(",");
info.close();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, data_array);
listView1.setAdapter(adapter);
}
P.S: above code is to give you just an hint that you can basically reload list on deletion or updation of db. it is not a exact solution.
May I ask why you are doing all that extra processing? You are querying the cursor, concatenating the results, returnng the concatenated results, and then splitting them again. That's a bit intensive on the processor.
Why not just use the cursor directly with a SimpleCursorAdapter? Then you just use requery() to refresh the list.
You can do it with the following changes:
public class Bookmarks extends Activity{
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.bookmarks);
final Database info=new Database(this);
final Timer t = new Timer();
info.open();
Cursor data=info.getData();
final ListView listView1 = (ListView) findViewById(R.id.list_mia);
String[] from = new String[] { db.KEY_CONTENUTO };
int[] to = new int[] { android.R.id.text1 };
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_1, data, from, to);
listView1.setAdapter(adapter);
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
listView1.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id){
if(view.getText().toString().startsWith("http://")){
Uri uri=Uri.parse(view.getText().toString());
Intent intent=new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}else{
alertDialog.setTitle("Content");
alertDialog.setMessage(view.getText().toString());
alertDialog.setIcon(R.drawable.ic_launcher);
alertDialog.show();
}
}
});
listView1.setOnItemLongClickListener(new OnItemLongClickListener(){
#Override
public boolean onItemLongClick(AdapterView<?> parent, View v, final int position, long id) {
long rowId = id;
builder.setTitle("Delete")
.setMessage("Are you sure to remove this entry?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
info.deleteEntry(rowId);
data.requery();
alertDialog.setTitle("Delete");
alertDialog.setMessage("Item deleted successfully!");
alertDialog.setIcon(R.drawable.ic_launcher);
alertDialog.show();
t.schedule(new TimerTask() {
public void run() {
alertDialog.dismiss();
t.cancel();
}
},2000);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {}
})
.show();
return false;
}
});
}
}
public Cursor getData() {
String[] columns=new String[]{KEY_ROWID,KEY_CONTENUTO};
Cursor c=ourDatabase.query(DATABASE_TABLE,columns,null,null,null,null,"id");
return c;
}

Categories

Resources