Listview only the last date get deleted - android

The following code consist of the listview function for displaying data from sqlite.
The issue is that no matter which data i selected on, it will only delete the last data and not the data being selected. How can i go about solving the issue? please help.
Thank you.
Arealist.java
public class Arealist extends AppCompatActivity {
public static ListView listView;
public static ArrayList<Area> list;
AreaListAdapter adapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
listView = (ListView) findViewById(R.id.listView);
list = new ArrayList<>();
adapter = new AreaListAdapter(this, R.layout.area_items, list);
listView.setAdapter(adapter);
//get all data
Cursor cursor = MainActivity.sqLiteHelper.getData("SELECT * FROM AREA");
list.clear();
while (cursor.moveToNext()) {
int id = cursor.getInt(0);
double area = cursor.getDouble(1);
String date = cursor.getString(2);
list.add(new Area(id, area, date));
}
adapter.notifyDataSetChanged();
}

It seems your problem is in this line MainActivity.sqLiteHelper.deleteData(Area.getId());
Try with this
MainActivity.sqLiteHelper.deleteData(area.getId());

Make Area Object local.
set Area Id in delete buttons as a Tag and get it in onClick().
Add In getView()
holder.btnDelete.setTag(area.getId());
Add In OnClick()
final int areaId = view.getTag();
Add in AlertDialog:
MainActivity.sqLiteHelper.deleteData(areaId);

Related

Items in Spinner visible but onItemSelected Not Working

I am a beginner in Android. I have a spinner in my android code. It takes values from room database and once selected the value will be added to the listview. I have two issues
a) I am seeing values in my Spinner. But I am not able to select it and also onItemSelected for this spinner is not working
b) I would like to add a delete icon in my list view along with these values so that if the user is not interested in the value he can delete it.
Please can someone help me to resolve this?
Code is provided below:
public class MainActivity extends AppCompatActivity
{
private List<String> tasks = new ArrayList<String>();
private ArrayAdapter<String> adapter;
private ListView consultantsList;
private Spinner spinner;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
consultantsRepository consrepo =
new consultantsRepository (getApplicationContext());
ArrayList<String> oncons = consrepo.getConsultants();
ArrayAdapter<String> consarrayadapter =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
oncons);
adapter = new ArrayAdapter<String>
(this,android.R.layout.simple_list_item_1,tasks);
ListView consultantsList = (ListView) findViewById(R.id.ListToSend);
consultantsList.setAdapter(adapter);
spinner = (Spinner) findViewById(R.id.consSpinner);
spinner.setAdapter(consarrayadapter);
consarrayadapter.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
spinner.setOnItemSelectedListener
(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected
(AdapterView<?> parent, View view, int position, long id)
{
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(getApplicationContext(), item,
Toast.LENGTH_LONG).show();
tasks.add(item);
adapter.notifyDataSetChanged();
}
});
}
}
try-
String item=spinner.getSelectedItem().toString();

Is it possible to get data from my listview onclick

Hi I have been working through several different tutorials on getting data from a sql database into a listview. I can add data, get data from database and populate the list view, and have a working onclick listener (will fire off a Toast message). However I can not get any data from the listview when clicked. I have tried different combinations of getitem and getItemAtPosition but they all return a empty string(blank toast). Would someone be kind enough to look at my code and tell me if what I am trying to do is possible. In my listview i have four items in each entry, I would like to either get the fourth item directly or get all the items (as string?) then I can pull out the data I need.
Thanks in advance for your time.
public class ListViewActivity extends Activity {
SQLiteHelper SQLITEHELPER;
SQLiteDatabase SQLITEDATABASE;
Cursor cursor;
SQLiteListAdapter ListAdapter ;
ArrayList<String> ID_ArrayList = new ArrayList<String>();
ArrayList<String> GENRE_ArrayList = new ArrayList<String>();
ArrayList<String> NAME_ArrayList = new ArrayList<String>();
ArrayList<String> URL_ArrayList = new ArrayList<String>();
ListView LISTVIEW;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
LISTVIEW = (ListView) findViewById(R.id.listView1);
SQLITEHELPER = new SQLiteHelper(this);
}
#Override
protected void onResume() {
ShowSQLiteDBdata() ;
super.onResume();
}
private void ShowSQLiteDBdata() {
SQLITEDATABASE = SQLITEHELPER.getWritableDatabase();
cursor = SQLITEDATABASE.rawQuery("SELECT * FROM demoTable1", null);
ID_ArrayList.clear();
GENRE_ArrayList.clear();
NAME_ArrayList.clear();
URL_ArrayList.clear();
if (cursor.moveToFirst()) {
do {
ID_ArrayList.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.KEY_ID)));
GENRE_ArrayList.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.KEY_Genre)));
NAME_ArrayList.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.KEY_Name)));
URL_ArrayList.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.KEY_Url)));
} while (cursor.moveToNext());
}
ListAdapter = new SQLiteListAdapter(ListViewActivity.this,
ID_ArrayList,
GENRE_ArrayList,
NAME_ArrayList,
URL_ArrayList
);
LISTVIEW.setAdapter(ListAdapter);
LISTVIEW.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// String text = (String) LISTVIEW.getAdapter().getItem(position);
String text = (String) LISTVIEW.getItemAtPosition(position);
//String text = (String) lv.getItemAtPosition(0);
// Object item = (Object) LISTVIEW.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
});
cursor.close();
}
}
LISTVIEW.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String value1 = ID_ArrayList.get(position);
String value2 = GENRE_ArrayList.get(position);
String value3 = NAME_ArrayList.get(position);
String value4 = URL_ArrayList.get(position);
Toast.makeText(getApplicationContext(),value1+" "+value2+" "+value3+" "+value4, Toast.LENGTH_SHORT).show();
}
});
try to change the line
String text = (String) LISTVIEW.getItemAtPosition(position);
with
String text = (String) parent.getItemAtPosition(position);
this should be the way ListView works.
Also i suggest you to not use Capital Cases with variables, usually in Java is used a CamelCase convention. And also have a look at RecyclerView, that usually is implemented today much more than ListView, because allow a great level of customization
Pls use below code within listview setOnItemClickListener :-
String genreID = ID_ArrayList.get(position);
String genre = GENRE_ArrayList.get(position);
String genreName = NAME_ArrayList.get(position);
String genreUrl = URL_ArrayList.get(position);
Toast.makeText(getApplicationContext(), genreID+", "+genre+","+genreName+", "+genreUrl+", "+, Toast.LENGTH_SHORT).show();
its return render data of listview.
try this,
ShowSQLiteDBdata() in onCreate() instead of onResume() method

Listview delete item and Refresh

hello i need some help ... i write this code but i am little confused when i add book to my fav it store to fav when i click on un fav there in fav list the book are still there in that activity until i don't close the activity when i reopen that fav activity the book are removed from there i want to add code that can refresh by self at that time when i un fav the book ... please help me out
public class Favrt extends AppCompatActivity implements AdapterView.OnItemClickListener {
ListView viewF;
Books_Adapter fav_adapter;
String[] name, links, author;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favrt);
fetch_fav();
fav_adapter = new Books_Adapter(this, name, links, author);
viewF = (ListView) findViewById(R.id.favView);
viewF.setAdapter(fav_adapter);
viewF.setOnItemClickListener(this);
}
public void fetch_fav(){
SQLiteDatabase database = openOrCreateDatabase("Pdf_books",MODE_PRIVATE,null);
Cursor db_cursor = database.rawQuery("select * from favourite", null);
name = new String[db_cursor.getCount()];
links = new String[db_cursor.getCount()];
author = new String[db_cursor.getCount()];
int i =0;
if (db_cursor.moveToLast()){
do {
name[i] = db_cursor.getString(db_cursor.getColumnIndex("name"));
links[i] = db_cursor.getString(db_cursor.getColumnIndex("links"));
author[i] = db_cursor.getString(db_cursor.getColumnIndex("author"));
i++;
}while (db_cursor.moveToPrevious());
}
database.close();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent web = new Intent(this, web_activity.class);
web.putExtra("url", links[position]);
startActivity(web);
}
#Override
public void onContentChanged() {
super.onContentChanged();
View empty = findViewById(R.id.empty);
ListView list = (ListView) findViewById(R.id.favView);
list.setEmptyView(empty);
}
}
Try fav_adapter.notifyDataSetChanged() after changing your list items (in this case, when your favorites are changed).
You have to update adapter. to do so fav_adapter.notifyDataSetChanged(). which will make changes to listview.
make function in activity where you do such things like remove from db and update list data.

Android, get cheked items on ListActivity

I'm using a ListActivity on wich I get the Access Points in the WIFI range, and list them in a cheking list.
I've been successfull doing this, but I would like to get the cheked items when I click in the footer button. How do I get them to a String array??
This is the code:
public class APselection extends ListActivity {
protected static final String TAG = "teste";
/** Called when the activity is first created. */
private TextView mScanList;
public List<ScanResult> listaAPs;
protected WifiManager wifiManager;
private IntentFilter mWifiStateFilter;
public String SCAN;
public String[] SCANed;
public String scanAP;
public ListView lv;
public ListView lv1;
public List<Long> list = new ArrayList();
public String[] checked;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
View footer = View.inflate(this, R.layout.footer, null);
wifiManager= (WifiManager)getSystemService(Context.WIFI_SERVICE);
int i;
//function to get the APs
SCANed=handleScanResultsAvailable().split("SPl");
lv=getListView();
lv.addFooterView(footer);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, SCANed));
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lv.setTextFilterEnabled(false);
}
}
There are several ways to do this. The easiest is probably to implement the OnClickListener for the ListView. When the user clicks a list item, extract the String from the clicked item. Store the items in an ArrayList. When the user clicks, if the list contains the String, remove it, otherwise add it. Bam. List of all selected items.
I don't think there is a way to directly get the checked item to a String array from the ListView, you have to go through intermediate steps :
You can use ListView.getCheckedItemIds to get an array of the id of the checked items. These id are assigned by your list adapter. Since you're using an ArrayAdapter, position=id, so you can just use ArrayAdapter.getItem() to get the String associated with each checked item id.
This would look like :
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
long ids[] = lv.getCheckedItemIds();
String checkedItems[] = new String[ids.length];
for (int i=0; i<ids.length; i++)
checkedItems[i] = adapter.getItem(i);
//You got your array of checked strings
}
}
Note that this require access to the adapter, so you would have to assign your ArrayAdapter to a variable.

Populating ListView from a SQLite database

public class ConnectDatabase extends Activity {
private SimpleDBAdapter mDbHelper;
private ListView list;
private String[] values;
private String[] list1;
private int i=0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list=(ListView )findViewById(R.id.simpleListView);
mDbHelper = new SimpleDBAdapter(ConnectDatabase.this);
mDbHelper.createDatabase();
mDbHelper.open();
values = mDbHelper.getEditTextValue();
mDbHelper.close();
for(i=0;i<10;i++) {
String tempvalue;
tempvalue=values[i];
list1[i]=tempvalue;
Log.v("log_tag"," tempvalue "+tempvalue);
Log.v("log_tag", "list1 is"+list1[i]);
//Log.v("log_tag"," list1"+list1[i]);
}
list.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, values));
//list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
//list.setTextFilterEnabled(true);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_SHORT).show();
/*for(int i=0;i<values.length;i++) {
String templist=values[i];
list1[i]=templist;
}*/
String fname=values[position];
Log.v("log_tag", "The fname is"+ fname);
Intent intent=new Intent(ConnectDatabase.this, Userinfo.class);
intent.putExtra("FirstName",fname );
startActivity(intent);
}
});
// to remove the last comma
}
}
Here I am doing ListView from SQLite database and want to display in ListView with only the first 10 ListView rows at the time but I get the error at the line list1[i]=tempvalue; so I can't copy array here anyone can help me to do copy the array name values where I get all the Column index values from my SQLite database.
Hope anyone have an idea to do this.
Your post is quite hard to read, but I think the issue is that list1 has not been initialised.
You need to add a line like this:
list1 = new String[10];
before you attempt to set a value within the array.
ps - I picked a value of 10 as your for loop has i<10.

Categories

Resources