My Listview gets information saved on a local database and displays the information. I am having altering what happens when my listview items are clicked. I want to delete them, can anybody assist me with this matter, while using my code? Thank you in Advance!
public class Notepad extends ListActivity {
public static final int INSERT_ID = Menu.FIRST;
EditText notes;
Button add;
ListView lv;
String currentDateTimeString = DateFormat.getDateInstance().format(
new Date());
private NotesDbAdapter mDbHelper;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notepad_list);
mDbHelper = new NotesDbAdapter(this);
mDbHelper.open();
fillData();
Button add = (Button) findViewById(R.id.addNote);
// ListView lv = (ListView) findViewById(R.id.list);
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
createNote();
}
});
// lv.setOnItemClickListener(new OnItemClickListener() {
//
// public void onItemClick(AdapterView<?> parent, View view,
// int position, long id) {
// // When clicked, show a toast with the TextView text
//
// try {
// Toast.makeText(getApplicationContext(),
// ((TextView) view).getText(), Toast.LENGTH_SHORT)
// .show();
//
// } catch (ClassCastException e) {
// Toast.makeText(getApplicationContext(), "Error",
// Toast.LENGTH_SHORT).show();
// }
//
// };
//
// });
}
private void createNote() {
EditText notes = (EditText) findViewById(R.id.note);
String noteName = notes.getText().toString();
Calendar c = Calendar.getInstance();
int seconds = c.get(Calendar.SECOND);
int minutes = c.get(Calendar.MINUTE);
int hour = c.get(Calendar.HOUR);
mDbHelper.createNote(noteName + " Entered at " + hour + ":" + minutes
+ ":" + seconds, "");
fillData();
}
private void fillData() {
// Get all of the notes from the database and create the item list
Cursor c = mDbHelper.fetchAllNotes();
startManagingCursor(c);
String[] from = new String[] { NotesDbAdapter.KEY_TITLE };
int[] to = new int[] { R.id.text1 };
// Now create an array adapter and set it to display using our row
SimpleCursorAdapter notes = new SimpleCursorAdapter(this,
R.layout.notes_row, c, from, to);
setListAdapter(notes);
}
}
My ListView:
<ListView
android:id="#id/android:list"
android:layout_width="wrap_content"
android:layout_height="402dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_below="#+id/note" >
</ListView>
onListItemClick you Got Position and Remove it from Dynamic Array (Vector or List) Like vector.remove(position);.if you want to remove it from Database ,Also remove from Database.After this You just write .....
adapter.notifyDataSetChanged();
What I do in my Apps, is override the SimpleCursorAdapter.setViewBinder() to set the Tag of Views inside the ListView with the ID (_ID) from the DB and delete this ID from the DB in the setOnItemClickListener() and refresh the Adapter. Something like this:
SimpleCursorAdapter notes = new SimpleCursorAdapter(this,
R.layout.notes_row, c, from, to);
notes.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
public boolean setViewValue(View view, Cursor cursor, int column)
{
TextView tv = (TextView) view;
view.setTag=cursor.getInt(cursor.getColumnIndex ("_id")); // You need to include the _id in the query
tv.setText(String.Valueof(cursor.getInt(cursor.getColumnIndex (NotesDbAdapter.KEY_TITLE ))));
return true;
}
});
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
TextView tv=(TextView) view;
String ID=view.getTag();
// Delete ID from the DB
notes.notifyDataSetChanged();
};
});
setListAdapter(notes);
}
}
You an add an onItemClickListener on your ListView just as you added on the button.
If they click an item you delete that item in the local database using an sql query. I assume since you can select data you can delete it using SQL.
After that just reinitialize the list.
That's the easiest way:)
Although I think you could better use a longpress then a normal press.
Just that items won't be deleted by accident
Related
When I click on items listed in the AlertDialog, I want the Clicked Item to appear with Toast. But whatever I did, it didn't happen. Nothing happens when clicking the Item. thank you
This is the main file. I'm getting the data from the database.
MainActivity.class
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
List<NuriClass> nurList;
public void favori_listele_class (String getir_kategori){
SQLiteDatabase db = veritabanim.getReadableDatabase();
String[] getColumnName={"_id,kategori,bilmece,cevap,favori"};
String[] arananDegerler={"1",getir_kategori};
Cursor imlec=db.query("bilmecebulmaca_tablosu", getColumnName, "favori=? And kategori=?",arananDegerler , null, null, null);
//Cursor imlec=db.query("bilmecebulmaca_tablosu", getColumnName, "kategori=?",arananDegerler1 , null, null, null);
final ArrayList<Integer> favori_listesi_id = new ArrayList<Integer>();
final ArrayList<String> favori_listesi = new ArrayList<String>();
nurList = new ArrayList<>();
while(imlec.moveToNext()){
int dizi_id=imlec.getInt(imlec.getColumnIndex("_id"));
String dizi_bilmece=imlec.getString(imlec.getColumnIndex("bilmece"));
String dizi_cevap=imlec.getString(imlec.getColumnIndex("cevap"));
int dizi_favori=imlec.getInt(imlec.getColumnIndex("favori"));
String dizi_soru= dizi_bilmece+ " "+dizi_cevap+ " "+dizi_favori;
favori_listesi.add(dizi_soru);
favori_listesi_id.add(dizi_id);
nurList.add(new NuriClass(dizi_id, getir_kategori, dizi_bilmece, dizi_cevap,dizi_favori,R.mipmap.ic_launcher));
}
ListeGoster((ArrayList<NuriClass>) nurList);
I call the bottom one with ListeGoster at the top.
I get the data from the database here
private void ListeGoster(final ArrayList<NuriClass> ssss){
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this,R.style.AlertDialogCustom);
LayoutInflater inflater = getLayoutInflater();
final View convertView = inflater.inflate(R.layout.nuri_list, null);
alertDialog.setView(convertView);
alertDialog.setTitle("FAVORİLER");
alertDialog.setIcon(R.drawable.uygulama_8);
alertDialog.setCancelable(true); //Tıkladığında PENCERE KAPANSIN MI?
final ListView listViewNur = convertView.findViewById(R.id.listViewNuri);
final NuriAdaptor adapter = new NuriAdaptor(this, R.layout.nuri_modelim, ssss);
if (listViewNur != null) {
listViewNur.setAdapter(adapter);
}
alertDialog.setPositiveButton("KAPAT", null);
alertDialog.setPositiveButtonIcon(getResources().getDrawable(android.R.drawable.ic_delete, getTheme()));
listViewNur.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(), "The program does not show this toast when clicking on items. it never gets to this point.", Toast.LENGTH_SHORT).show();
}
});
alertDialog.show();
Nuriadaptor.java
public class NuriAdaptor extends ArrayAdapter<NuriClass>{
List<NuriClass> nuriList; //KisilerCLASS türü Listedeki liste değerleri
Context context;
int resource; //liste öğeleri için düzen kaynak dosyası, the layout resource file for the list items
//yapıcı değerleri başlatıyor, constructor initializing the values
public NuriAdaptor(Context context, int resource, List<NuriClass> nuriList) {
super(context, resource, nuriList);
this.context = context;
this.resource = resource;
this.nuriList = nuriList;
}
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(resource, null, false); //getting the view
ImageView imageView = view.findViewById(R.id.imageView);
TextView textKategori = view.findViewById(R.id.textViewKategori);
TextView textSoru = view.findViewById(R.id.textViewSoru);
FloatingActionButton favSil = view.findViewById(R.id.floating_sil_FAV);
NuriClass nuri = nuriList.get(position);
textKategori.setText(nuri.getKategori());
textSoru.setText(nuri.getSoru());
//öğeyi listeden kaldırmak için düğmeye bir tıklama dinleyicisi ekleme, adding a click listener to the button to remove item from the list
favSil.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//seçilen değeri listeden çıkarmak için bu yöntemi arayacağız, we will call this method to remove the selected value from the list
//yöntemde kaldırılacak pozisyonu geçiyoruz, we are passing the position which is to be removed in the method
removeKisiler(position);
}
});
//finally returning the view
return view;
}
//this method will remove the item from the list
private void removeKisiler(final int position) {
//Silme işlemini onaylamak için bir uyarı iletişim kutusu oluşturma, Creating an alert dialog to confirm the deletion
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Silmek istediğinizden EMİNMİSİNİZ?");
builder.setPositiveButton("EVET", new DialogInterface.OnClickListener() { //uyarıdaki yanıt olumluysa, if the response is positive in the alert
#Override
public void onClick(DialogInterface dialogInterface, int i) {
nuriList.remove(position); //öğeyi kaldırmak, removing the item
notifyDataSetChanged(); //listeyi yeniden yüklemek, reloading the list
}
});
//cevap olumsuz ise hiçbir şey yapılmıyor, if response is negative nothing is being done
builder.setNegativeButton("HAYIR", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
//uyarı iletişim kutusunu oluşturma ve görüntüleme, creating and displaying the alert dialog
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
enter image description here
enter image description here
I get the data from the database here
public void favori_listele_class (String getir_kategori){
SQLiteDatabase db = veritabanim.getReadableDatabase();
String[] getColumnName={"_id,kategori,bilmece,cevap,favori"};
String[] arananDegerler={"1",getir_kategori};
Cursor imlec=db.query("bilmecebulmaca_tablosu", getColumnName, "favori=? And kategori=?",arananDegerler , null, null, null);
//Cursor imlec=db.query("bilmecebulmaca_tablosu", getColumnName, "kategori=?",arananDegerler1 , null, null, null);
final ArrayList<Integer> favori_listesi_id = new ArrayList<Integer>();
final ArrayList<String> favori_listesi = new ArrayList<String>();
nurList = new ArrayList<>();
while(imlec.moveToNext()){
int dizi_id=imlec.getInt(imlec.getColumnIndex("_id"));
String dizi_bilmece=imlec.getString(imlec.getColumnIndex("bilmece"));
String dizi_cevap=imlec.getString(imlec.getColumnIndex("cevap"));
int dizi_favori=imlec.getInt(imlec.getColumnIndex("favori"));
String dizi_soru= dizi_bilmece+ " "+dizi_cevap+ " "+dizi_favori;
favori_listesi.add(dizi_soru);
favori_listesi_id.add(dizi_id);
nurList.add(new NuriClass(dizi_id, getir_kategori, dizi_bilmece, dizi_cevap,dizi_favori,R.mipmap.ic_launcher));
}
ListeGoster((ArrayList<NuriClass>) nurList);
I have two spinner.
First spinner value is Kathmandu and Bhaktapur and depending on first spinner value, second spinner value is filled up.
My problem is when I select Kathmandu and select first item from second spinner I get the first item of second spinner which is what i expect.
But when I select Bhaktapur or any item below Kathmandu from Spinner first, Then on Selecting first item position from second spinner I get first spinner value itself which Is Bhaktapur instead of "Bageswori"
But if I select second item position then there is no problem i.e I get the "Balkot" which is expected outcome.
So problem lies when I select any item below first item position from First spinner and first item position form second spinner.It returns first item value of First spinner instead of selected value from Second spinner.
My Code is
public class UploadBook extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
String item = "start";
String condition = "start"; // for spinner
FirebaseStorage storage;
public Books b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_book);
getSupportActionBar().setTitle("Upload Room Info");
getSupportActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#8abe50")));
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP)
ActivityCompat.requestPermissions(UploadBook.this, new String[]{android.Manifest.permission.CAMERA, android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 11);
database = FirebaseDatabase.getInstance();
dbreference = database.getReference();
fauth = FirebaseAuth.getInstance();
mStorageRef = FirebaseStorage.getInstance().getReference();
b1 = (Button) findViewById(R.id.buttonPost);
spinnerCountry = (Spinner) findViewById(R.id.spinnerCountry);
//implementing OnItemSelectedListener (need to override the method)
countryArray = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
countryArray.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerCountry.setAdapter(countryArray);
countryArray.add("Kathmandu");
countryArray.add("Bhaktapur");
countryArray.add("Lalitpur");
countryArray.setNotifyOnChange(true);
spinnerCountry.setSelection(0);
spinnerDivision = (Spinner) findViewById(R.id.spinnerDivision);
//implementing OnItemSelectedListener (need to override the method)
spinnerDivision.setOnItemSelectedListener(this);
spinnerCountry.setOnItemSelectedListener(this);
divisionArray = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
divisionArray.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerDivision.setAdapter(divisionArray);
postButtonClick();
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
item = parent.getItemAtPosition(position).toString();
//first spinner item position
int countrySpinnerPosition = spinnerCountry.getSelectedItemPosition();
switch (countrySpinnerPosition){
case 0:
//fill data for second spinner
fillKathmanduDivision();
break;
case 1:
//fill data for second spinner
fillBhaktapurDivision();
break;
}
//first spinner item position
}
private void fillKathmanduDivision() {
divisionArray.clear();
divisionArray.add("Anamnagar");
divisionArray.add("Balaju");
divisionArray.notifyDataSetChanged();
}
private void fillBhaktapurDivision() {
divisionArray.clear();
divisionArray.add("Bageswori");
divisionArray.add("Balkot");
divisionArray.notifyDataSetChanged();
}
b1.setOnClickListener(new View.OnClickListener() {
}
void postButtonClick() {
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(this, item, Toast.LENGTH_SHORT).show();
}
}
}
Please use this code below :
private String country_id = "", city_id = "";
private ArrayList<String> country_array;
and to fill your array with data :
for (int i = 0; i < items.getResponse().size(); i++) {
String get_country_name = items.getResponse().get(i).getCode();
country_array.add(get_country_name);
}
Now for your first spinner adapter :
ArrayAdapter<String> country_spinnerArrayAdapter = new adapter_spinner(getActivity(), R.layout.spinner_header, country_array);
country_spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_item);
binding.etCountry.setAdapter(country_spinnerArrayAdapter);
binding.etCountry.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selectedItemText = parent.getSelectedItem().toString();
if (position > 0) {
country_id = selectedItemText;
city_id = "";
Load_City(position - 1); // -1 to remove postion of the static country text
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Now your City (2nd spinner) method :
private void Load_City(int postion) {
ArrayList<String> city_array = new ArrayList<String>();
city_array.add(getString(R.string.city));
for (int i = 0; i < items.getResponse().get(postion).getCities().size(); i++) {
String get_city_name = items.getResponse().get(postion).getCities().get(i).getName();
city_array.add(get_city_name);
}
ArrayAdapter<String> country_spinnerArrayAdapter = new adapter_spinner(getActivity(), R.layout.spinner_header, city_array);
country_spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_item);
binding.etCity.setAdapter(country_spinnerArrayAdapter);
binding.etCity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selectedItemText = parent.getSelectedItem().toString();
if (position > 0) {
city_id = selectedItemText;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
i hope this helped
You have taken wrong reference of first spinner.
in below line
int countrySpinnerPosition = spinnerCountry.getSelectedItemPosition();
you have taken spinnerCountry instead of spinnerFirst.
And you have initially set spinnerFirst to first postion that is A and When you change it-to select B its value not taken in onItemSelected method ,intend of takes country selected that is probably on first (0) position of spinner so you second spinner always set to Three instead of Four.
I am having trouble with my programming project. I am creating a shopping application and all I need is deleting the selected data from listview and mysqlite database with a click of a button. I also created a query on my sqlite where it will delete primary key autoincrement integer.
Here is my class:
public class CartPage extends AppCompatActivity {
DatabaseHelper myDB;
public Button button_delete;
public Button button_home;
public TextView textView_totalAmount;
public TextView textView_PK;
public ListView listView_datas;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cart_page);
myDB = new DatabaseHelper(this);
listView_datas = (ListView) findViewById(R.id.listView_ShoppingData);
button_delete = (Button) findViewById(R.id.button_deleteData);
button_home = (Button) findViewById(R.id.button_HomePage);
textView_totalAmount = (TextView) findViewById(R.id.textView_DisplayTotalAmount);
int total = myDB.addPrice();
textView_totalAmount.setText("$" + Integer.toString(total));
final ArrayList<String> list_cart = new ArrayList<>();
final Cursor data = myDB.getPrice_cart();
if (data.getCount() == 0) {
Toast.makeText(CartPage.this, "The Database is empty..", Toast.LENGTH_LONG).show();
} else {
while (data.moveToNext()) {
list_cart.add(data.getString(1) + "\n" +
data.getString(2) + "\n");
ListAdapter listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_multiple_choice, list_cart);
listView_datas.setAdapter(listAdapter);
}
}
button_home.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent goHome = new Intent(CartPage.this, FirstPage.class);
startActivity(goHome);
}
});
}
}
Here is my database helper query for deleting the data by primary key
public int deleteSelectedItem(String number){
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(table_Cart,"number = ?" , new String[] {number} );
}
For this scenario I was thinking on using but I am not sure how to do it.
listView_datas.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
});
I also saw where when you hold the selected item it would get deleted. I don't mind that as long as it deletes the data.
Thank you!
I would suggest you implement a long click listener in your ListView and on long click on the item in your list, it will show an option to delete the corresponding item in your list. Here's a sample code that can help you.
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View view, final int position, long arg3) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(RecipeList.this);
alertDialog.setTitle("Delete");
alertDialog.setMessage(yourList.get(position));
alertDialog.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
deleteSelectedItem(yourList.get(position))
}
});
alertDialog.show();
return true;
}
});
And yes, you need to call notifyDataSetChanged() in your deleteSelectedItem() function to see the effect of the delete in your list.
public int deleteSelectedItem(String number){
SQLiteDatabase db = this.getWritableDatabase();
int result = db.delete(table_Cart,"number = ?" , new String[] {number} );
// Update your list here
// Remove the deleted item from the list that you have passed to the adapter. Then call notifyDataSetChanged
updateYourListCart();
myAdapter.notifyDataSetChanged();
}
I'm having a problem with this. I am using cursor adaptor. What my problem is when the checkbox is checked it will get the value and then when a button is clicked the data will be deleted. By the way I am displaying the checkbox with listview.
public class ListViewAdapter extends CursorAdapter {
SparseBooleanArray sba = new SparseBooleanArray();
public ListViewAdapter (Context context, Cursor c) {
super(context, c);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// when the view will be created for first time,
// we need to tell the adapters, how each item will look
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.custom_dialog_box, parent, false);
ViewHolder holder = new ViewHolder();
holder.textView = (TextView) retView.findViewById(R.id.number);
holder.cb = (CheckBox) retView.findViewById(R.id.checkBox1);
retView.setTag(holder);
return retView;
}
private static class ViewHolder {
TextView textView;
CheckBox cb;
}
#Override
public void bindView(View view, final Context context, Cursor cursor) {
// here we are setting our data
// that means, take the data from the cursor and put it in views
final int position = cursor.getPosition();
final CheckBox CheckBoxPersonName = (CheckBox) view.findViewById(R.id.checkBox1);
CheckBoxPersonName.setTag(cursor);
CheckBoxPersonName.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked) {
sba.put(position, true);
}
else {
sba.put(position, false);
}
}
});
CheckBoxPersonName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
TextView textViewPersonPIN = (TextView) view.findViewById(R.id.number);
textViewPersonPIN.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(2))));
}
}
Here is my mainActivity where the button will be clicked.
public class TemplateActivity extends Activity {
CheckBox cb;
Button btnSort, btnDel;
private ListViewAdapter listAdapter;
private RetailerDatabaseHelper dbHelper;
private ListView listView;
private static final String TAG = TemplateActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_template);
btnSort = (Button) findViewById(R.id.btnSort);
btnDel = (Button) findViewById(R.id.btnDelete);
dbHelper = new RetailerDatabaseHelper(this);
listView = (ListView) findViewById(R.id.listViewData);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
System.out.println("Control: " + listView.getCheckedItemPositions());
Cursor c = (Cursor) parent.getAdapter().getItem(position);
String name = c.getString(1);
String number = c.getString(2);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(TemplateActivity.this);
alertDialog.setTitle("RETAILER");
alertDialog.setMessage("Are you sure you want to send " + name + " load to " + number + " ?");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//insertData(textVal, value);
dialog.dismiss();
}
});
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
});
btnDel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int count = listView.getAdapter().getCount();
SparseBooleanArray array = listView.getCheckedItemPositions(); /* 11/07/15 */
System.out.println("Count: "+ count);
/* 11/07/15 */
for(int x = 0; x < array.size(); x++)
{
if(array.get(x)) /* 11/07/15 */
{
Log.d(TAG, "Checked: " + listView.getTag());
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_SHORT).show();
}
listAdapter.notifyDataSetChanged();
}
}
});
It is working but when the listview data is not clicked the checkbox value is not displaying.
You are declaring SparseBooleanArray as null here:
SparseBooleanArray array = null;
and no assignment to array.. and you are using it in for loop, then it will definitely give you null reference error.
I have a listview that have buttons in every row and is connected to my SQLite database.
Here's the code:
public class UpdateActivity extends Activity implements AdapterView.OnItemClickListener, View.OnClickListener {
ListView listView;
SimpleCursorAdapter dataAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
listView = (ListView)findViewById(R.id.listView1);
Appliances db = new Appliances(getApplicationContext());
Cursor cursor = db.getAllApp();
// The desired columns to be bound
String[] columns = new String[] { Appliances.KEY_APPNAME,Appliances.KEY_ONOFF };
// the XML defined views which the data will be bound to
int[] to = new int[] { R.id.text, R.id.right};
// create the adapter using the cursor pointing to the desired data
// as well as the layout information
dataAdapter = new SimpleCursorAdapter(this, R.layout.row_view,
cursor, columns, to, 0) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = super.getView(position, convertView, parent);
View right = row.findViewById(R.id.right);
right.setTag(position);
right.setOnClickListener(UpdateActivity.this);
return row;
}
};
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(this);
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) {
Appliances db = new Appliances(getApplicationContext());
return db.getAppliancesByName(constraint.toString());
}
});
}
public void onClick(View v) {
switch(v.getId()) {
case R.id.right:
Button tog = (Button)findViewById(R.id.right);
Appliances db = new Appliances(getApplicationContext());
Toast.makeText(this, "Right Accessory "+v.getTag(), Toast.LENGTH_SHORT).show();
Integer i = (Integer) v.getTag();
if(tog.getText().toString().equals("ON")){
//db.update_on(i, "ON");
tog.setText("OFF");
}else if(tog.getText().toString().equals("OFF")){
// db.update_on(i, "OFF");
tog.setText("ON");
}
break;
default:
break;
}
}
Whenever I click the Button in the second row in my listview, the button in the first row changes its text. In short, The if-condition is only applicable in the first row.
Every button must change its text into "ON" or "OFF" everytime I click them AND saves their texts in the SQLite database in their corresponding row.
Screenshot:
I may be entirely wrong ..but I strongly guess that it is because of Id.
Repalce this Code :
Button tog = (Button)findViewById(R.id.right);
With
Button tog = (Button)v
Becuase you have already assigned the id to that view and passed that to the onClick Method and When you reassign then it refers to the Button from your main layout.