Listview delete item and Refresh - android

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.

Related

Passing checked items in a list view to an arraylist/array

Hey I'm new to android app development and in this situation I'm creating a mobile application which stores data in SQLite database and show it in a list view and the items in the list can be checked by check boxes.
In here I want to get the position of the checked items so I can pass them to the database, and when the application opens again previously checked items will be already checked. I want to save the position when the button is clicked.
I've used a SparseBooleanArray to store the checked items but I've no idea to pass the values of SparseBooleanArray to DB and I'm stuck there.
Help me with this and thanks in advance.
*
public class Subscribe extends AppCompatActivity {
ListView lanList;
DatabaseHelper translateDB;
TextView textView;
Button button;
ArrayList<String> list = new ArrayList<>();
String clicked;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subscribe);
translateDB = new DatabaseHelper(this);
textView = findViewById(R.id.textView);
lanList = findViewById(R.id.listView);
button = findViewById(R.id.subscribeBtn);
showLang();
}
public void showLang(){
final Cursor cursor = translateDB.retriveLang();
System.out.println("1");
if (cursor.getCount() == 0){
Toast.makeText(Subscribe.this, "No data", Toast.LENGTH_LONG).show();
return;
}
System.out.println("2");
while (cursor.moveToNext()) {
list.add(cursor.getString(1));
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_multiple_choice,list);
lanList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lanList.setAdapter(arrayAdapter);
lanList.setItemChecked(1,true); <--- used this to check the functioning
lanList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
clicked = adapterView.getItemAtPosition(i).toString();
Toast.makeText(Subscribe.this,"You selected '"+ clicked+"' " , Toast.LENGTH_LONG).show();
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SparseBooleanArray checkedItems =lanList.getCheckedItemPositions();
System.out.println("1 - " +checkedItems);
if (checkedItems != null) {
for (int i=0; i<checkedItems.size(); i++) {
if (checkedItems.valueAt(i)) {
String item = lanList.getAdapter().getItem(
checkedItems.keyAt(i)).toString();
System.out.println("2 - " +item);
translateDB.subscribedLang(item);
}
}
}
}
});
}
*
SO what I'm planning to do is pass the checked positions to db and get the positions and lanList.setItemChecked(x,true); and pass position values to this code.
Help me with this.

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

Android - ListView layout two line list item

I have a listview with two lines of items: user ID and username. How to retrieve only user ID from the listview when one of the rows is clicked?
public class MainActivity extends AppCompatActivity {
private DatabaseReference mUsers;
String getValue = null;
ListView lvUsers = (ListView) findViewById(R.id.lvUsers);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mUsers = FirebaseDatabase.getInstance.getReference().child(Constants.FIREBASE_USERS);
FirebaseListAdapter<Users> adapter = new FirebaseListAdapter<Users>(
this, Users.class, android.R.layout.two_line_list_item, mUsers
) {
#Override
protected void populateView(View v, Users user, int pos) {
((TextView)v.findViewById(android.R.id.text1)).setText(user.getUserID());
((TextView)v.findViewById(android.R.id.text2)).setText(user.getUsername());
}
};
lvUsers.setAdapter(adapter);
setupListViewMenu();
}
private void setupListViewMenu() {
lvUsers.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter,
View item, int pos, long id) {
// How to retrieve only User ID from here?
getValue = ((TextView)view).getText().toString();
return true;
}
});
}
}
The listview data is from Firebase database. Is retrieving using for loop the only way? I have to loop through two dimensional array? Thanks
Could you please try the code below?
getValue = ((TextView)item.findViewById(android.R.id.text2)).getText().toString();
I believe that android.R.id.text2 is one of the childs of item(View received in the clickListener)
But need to test... Hope it works

Android Studio ListView - null pointer exception when trying to extract text from selected item

I'm trying to save text from the selected item of a ListView in OnItemClick.
I've tried so many different methods to no avail, I think I'm missing something really stupidly obvious here...
SnakesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String choice = SnakesListView.getItemAtPosition(position).toString();
Intent intent = new Intent(SnakeList.this, SnakeProfile.class);
intent.putExtra("SelectedSnakeName", choice);
startActivity(intent);
}
});
The data is being displayed fine, I just can't seem to reference it.
The line causing the exception:
String choice = SnakesListView.getItemAtPosition(position).toString();
Full code for this activity
public class SnakeList extends Activity {
ListView SnakesListView;
Cursor cursor;
Button NewSnakeBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_snake_list);
SnakesListView = (ListView) findViewById(R.id.SnakesListView);
NewSnakeBtn = (Button) findViewById(R.id.NewSnake);
SQLiteDatabase db = openOrCreateDatabase("snakeDB", Context.MODE_PRIVATE, null); // ACCESSES DB
cursor = db.rawQuery("SELECT name FROM snakes", null); // SETS cursor TO RESULTS OF QUERY
List<String> SnakeNamesList = new ArrayList<String>();
ArrayAdapter SnakeNamesAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, SnakeNamesList);
SnakeNamesList.clear(); // REMOVES ANY NAMES CURRENTLY IN NAME ARRAY TO AVOID DUPLICATES
SnakesListView.setAdapter(SnakeNamesAdapter);
if (cursor.moveToFirst()) {
cursor.moveToFirst(); // MOVES CURSOR TO FIRST POSITION
do SnakeNamesList.add(cursor.getString(0)); // RETURNS STRING FROM FIRST COLUMN (NAME)
while (cursor.moveToNext());
}
NewSnakeBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(SnakeList.this, NewSnake.class));
}
});
SnakesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String choice = SnakesListView.getItemAtPosition(position).toString();
Intent intent = new Intent(SnakeList.this, SnakeProfile.class);
intent.putExtra("SelectedSnakeName", choice);
startActivity(intent);
}
});
}
No use of referencing the ListView; you can get the value from adapter itself.
Change
String choice = SnakesListView.getItemAtPosition(position).toString();
to
String choice = SnakeNamesAdapter.getItem(position).toString();
declare the string arraylist(SnakeNamesList) as global variable and
change
String choice = SnakesListView.getItemAtPosition(position).toString();
to
String choice = SnakeNamesList.get(position);

How to set view or Activity for dealing with previous listactivity? for example "see full detail page"

This is my ListActivity after clicking on the list it will start a new activity which shows Full detail of each attraction place. I have no idea how to implement Full detail page. Can you guys show me some code of full detail activity which retrieve data from the previous list?
public class AttractionsListActivity extends ListActivity {
private static MyDB mDbHelper;
String[] from = new String[] { Constants.TITLE_NAME , Constants.ADDRESS_NAME };
int[] to = new int[] {R.id.place_title, R.id.place_address};
private Cursor c;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDbHelper = new MyDB(this);
mDbHelper.open();
c = mDbHelper.getplaces();
setListAdapter(new SimpleCursorAdapter(this,
R.layout.list_place, c,
from, to));
final ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View view,int position, long id) {
Intent newActivity = new Intent(view.getContext(), Place.class);
startActivity(newActivity);
}
});
}
}
I have no idea how to implement this activity to deal with the action from AttractionslistActivity.Class
public class Place extends Activity {
private static final String CLASSTAG = Place.class.getSimpleName();
private TextView title;
private TextView detail;
private TextView location;
private TextView phone;
private ImageView placeImage;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v(Constants.TAG, " " + Place.CLASSTAG + " onCreate");
this.setContentView(R.layout.detail_place);
this.title = (TextView) findViewById(R.id.name_detail);
//title.setText(cursor.getString(Constants.TITLE_NAME));
this.detail = (TextView) findViewById(R.id.place_detail);
this.location = (TextView) findViewById(R.id.location_detail);
this.phone = (TextView) findViewById(R.id.phone_detail);
this.placeImage = (ImageView) findViewById(R.id.place_image);
}
}
Override onListItemClick(...) in your List Activity, using the Cursor get the id of the selected item
Start your Detail Activity passing the id through the intent extras
In your Detail Activity, recover the id and open a cursor to get your data back from the DB.
Fill your view with the data
The Android Notepad Tutorial includes an example of exactly this, if I understand the question correctly.
First of all sorry for the late answer,
in your adapter class you can use item click listener achieve this easily, please do the following steps for achieving this.
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(
AdapterView parent, View view,int position, long id) {
Intent newActivity = new Intent(
view.getContext(), Place.class);
startActivity(newActivity);
}
});
for passing list item details into next screen you can use intent extras.before calling start activity u need pass the extras like below.
newActivity.putExtra("name", c.place);
newActivity.putExtra("description", c.placeDscription);
newActivity.putExtra("distance", c.distance);
after u need to call ---> startActivity(newActivity);
if you want pass string, Integer, float, boolean etc...types of data you can like above code.

Categories

Resources