Populating ListView with data saved in sharedPreferences - android

I have save about 6 rows saved in shared preference and each row contains name, description, price etc. I have List in which i have to populate name, description, price in each row retrieved from shared preferences. How to get all data in row and populate list?
I have done
public class LazyAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater=null;
private ArrayList<HashMap<String, Object>> data;
//public ImageLoader imageLoader;
int i=0;
public LazyAdapter(Activity a) {
activity = a;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.order_list, null);
TextView orderDishDescription = (TextView)vi.findViewById(R.id.orderDishDescription);
TextView OrderDishName = (TextView)vi.findViewById(R.id.OrderDishName);
TextView OrderDishPrice = (TextView)vi.findViewById(R.id.OrderDishPrice);
ImageView imageview=(ImageView) vi.findViewById(R.id.list_image_order);
//ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); /
//HashMap<String, Object> song = new HashMap<String, Object>();
// song = data.get(position);
Log.i("iiiiii "," " +i++);
// Log.i("objj.Get_O_Id() ",objj.Get_O_Id());
// Log.i("objj.GetProductName() ",objj.GetProductName());
// Log.i("objj.GetDescription() ",objj.GetDescription());
//
OrderDishPrice.setText(OrderSharedPrefences.getDish_Price(getApplicationContext()));
OrderDishName.setText(OrderSharedPrefences.getUserName(getApplicationContext()));
orderDishDescription.setText(OrderSharedPrefences.getDish_Description(getApplicationContext()));
//imageview.setImageBitmap(objj.GetImage());
return vi;
}
}

Your Adapter is Okay just make set data from your Activity class, something like that-
First get data from preference in set and set into array-list then set into list-view.
EDIT
Set prefrence as like that-
SharedPreferences.Editor sEdit = sPrefs
.edit();
sEdit.putString("NAME", content);
sEdit.putStringSet("args", listArraySet);
sEdit.commit();
And get any where like that-
sPrefs=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
listArraySet=new HashSet<String>();
listArraySet=sPrefs.getStringSet(name1,new HashSet<String>());
list=new ArrayList<String>(listArraySet);
ArrayAdapter<String> ao=new ArrayAdapter<String>(this, R.layout.songs_list_item, R.id.songTitle, list);
lv.setAdapter(ao);
whole code for set into listview-
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.songs_list);
list = new ArrayList<String>();
lv=(ListView)findViewById(R.id.listView1);
sPrefs=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
listArraySet=new HashSet<String>();
listArraySet=sPrefs.getStringSet(name1,new HashSet<String>());
list=new ArrayList<String>(listArraySet);
ArrayAdapter<String> ao=new ArrayAdapter<String>(this, R.layout.songs_list_item, R.id.songTitle, list);
lv.setAdapter(ao);
//-------------------------CLICK ON LIST ITEM_-----------------------
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int index = parent.getPositionForView(view);
String filename = list.get(index);
}
});
}
}

Related

Set row id of listview as primary key column from database in android

I have a listview in android which shows list of data from database when i select any row it shows the data which is clicked but instead of data i want primary key id of that data
ListView should show list bt onclick it should fetch primary key id of that data clicked
public void onClick(View v) {
Cursor c = db.rawQuery("SELECT * FROM Deltas", null);
values=new ArrayList<String>();
while(c.moveToNext()){
String uname = c.getString(c.getColumnIndex("delta"));
if(uname!="")
values.add(uname);
System.out.println("data"+uname);
}
//fetch all data one by one
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_activated_1, values);
listView.setAdapter(adapter);
}
This is how i create listview how to tag primary key id to row in listview
You will need to build a custom adapter. Try this one:
public class CustomAdapter extends BaseAdapter {
private Context mContext;
private List<Pair<Integer, String>> mData;
public CustomAdapter(Context context, List<Pair<Integer, String>> data) {
this.mContext = context;
this.mData = data;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public Pair<Integer, String> getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if(view == null)
view = LayoutInflater.from(mContext).inflate(android.R.layout.simple_list_item_activated_1, parent, false);
String text = getItem(position).second;
((TextView) view).setText(text);
return view;
}
}
On your activity do this instead:
List<Pair<Integer, String>> values;
public void onClick(View v) {
Cursor c = db.rawQuery("SELECT * FROM Deltas", null);
values=new ArrayList<Pair<Integer, String>();
while(c.moveToNext()){
String uname = c.getString(c.getColumnIndex("delta"));
int id = c.getInt(c.getColumnIndex("id"));
if(uname!="")
Pair<Integer, String> pair = new Pair<Integer, String>(id, uname);
values.add(pair);
System.out.println("data"+uname);
}
c.close();
//fetch all data one by one
CustomAdapter adapter = new CustomAdapter(MainActivity.this, values);
listView.setAdapter(adapter);
}
Then to get your stuff:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CustomAdapter adapter = (CustomAdapter)parent.getAdapter();
Pair<Integer, String> pair = adapter.getItem(position);
Log.e("the information you want","id:" pair.first + " name:" + pair.second);
}
});

Android Java: Unable to selectively highlight rows in a ListView via onScroll listener

I have another blocker as I study Android Development.
This time my problem is when I wanted to "selectively" highlight a row in a ListView populated by data from an adapter.
This ListView is actually within a dialog, and purpose is to show a list of friends, where user can multi-select and highlight it as he selects.
The selected values by the way, is stored in an ArrayList "arr_FriendsShare" so that the next time he opens the listview, rows will be highlighted (via onScrollListener) for those previously selected.
What is currently happening, only the "recently" or "last" clicked row/item is highlighted; and seems to be clearing all the previously highlighted rows.
I cannot understand why it is behaving that way, as row's value is successfully stored to/removed from arr_FriendsShare ArrayList, as I click on it.
Below is my listener codes, and thanks in advance for the usual help:
//Item click listener for Select Friends ListView
listview_SelectFriends.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
String friends_ListItemSelected = (String)adapter.getItemAtPosition(position);
if(!arr_FriendsShare.contains(friends_ListItemSelected)){
arr_FriendsShare.add(friends_ListItemSelected);
}
else{
removeItemFromArrayListString(Main.this, arr_FriendsShare, friends_ListItemSelected);
}
}
});
listview_SelectFriends.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
for (int i = firstVisibleItem; i < (visibleItemCount + firstVisibleItem); i++) {
String listViewItemText = view.getItemAtPosition(i).toString();
if(arr_FriendsShare.contains(listViewItemText)){
ColorDrawable cd = new ColorDrawable(getResources().getColor(R.color.red_light));
view.setSelector(cd);
}
else if(arr_FriendsShare.contains(listViewItemText)){
ColorDrawable cd = new ColorDrawable(Color.TRANSPARENT);
view.setSelector(cd);
}
}
}
});
Additional Code Block:
ArrayList<String> stringArray = new ArrayList<String>();
String jsonURL = <SOME URL HERE>;
stringArray = Global.getStringArrayFromJSON(Main.this, jsonURL, "friends", "FriendUsername");
LayoutInflater inflater = getLayoutInflater();
View convertView = (View) inflater.inflate(R.layout.friends_list_layout, null);
ListView listview_SelectFriends = (ListView) convertView.findViewById(R.id.layout_Friends);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, stringArray);
listview_SelectFriends.setAdapter(adapter);
Change
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, stringArray);
to
// Define this at class level as --> private FriendsAdapter adapter = null;
adapter = new FriendsAdapter(Main.this, stringArray);
add this method in your activity
private void setResetSelection(int index, boolean setSelection){
View v = listview_SelectFriends.getChildAt(index);
if(v != null){
TextView name = (TextView) v.findViewById(R.id.name);
if(setSelection)
name.setBackgroundResource(R.color.red);
else
name.setBackgroundResource(R.color.transparent);
}
}
and create a new class as
public class FriendsAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<String> mFriends;
private ArrayList<String> mSelectedFriends = new ArrayList<String>();
public GoodPeopleAdapter(Context context, ArrayList<String> friends) {
mInflater = LayoutInflater.from(context);
mFriends= friends;
}
public void setSelectedFriends(ArrayList<String> selectedFriends){
mSelectedFriends = selectedFriends;
}
#Override
public int getCount() {
return mFriends.size();
}
#Override
public Object getItem(int position) {
return mFriends.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
ViewHolder holder;
if(convertView == null) {
view = mInflater.inflate(R.layout.row_layout, parent, false);
holder = new ViewHolder();
holder.name = (TextView)view.findViewById(R.id.name);
view.setTag(holder);
} else {
view = convertView;
holder = (ViewHolder)view.getTag();
}
String name = mFriends.get(position);
holder.name.setText(name);
if(mSelectedFriends.contains(name))
holder.name.setBackgroundResource(R.color.red) // red is in color xml by default, change according to your choice
return view;
}
private class ViewHolder {
public TextView name;
}
}
Add following line at the end of method onItemClick
adapter.setSelectedFriends(arr_FriendsShare);
Add this in the if part of onItemClick
setResetSelection(position, true);
and this in else part
setResetSelection(position, false);
Also create a new xml layout with name row_layout with a textview with id name.

custom adapter with ArrayList<HashMap<String, List<String>>>

Its a really complicated question, but I hope someone can help me.
I want to make a custom adapter that can handle
Array List mentioned in the title
Currently I am doing this, but its not even going into getView(...) method.
public class EventsAdapter extends BaseAdapter{
ArrayList<HashMap<String, List<String>>> eventList;
private Context context;
private int resource;
private static final String TAG_TITLE = "e_title";
public EventsAdapter(Context context, int resId,ArrayList<HashMap<String, List<String>>> eventList)
{
this.context = context;
this.resource = resId;
this.eventList = eventList;
Log.v("chk", "1");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View event = convertView;
TextView title, desc, date, time, venue;
HashMap<String, List<String>> hm = eventList.get(position);
List<String> items = hm.get(TAG_TITLE);
Typeface font = Typeface.createFromAsset(context.getAssets(), "Ubahn.ttf");
if( event == null )
{
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
event = inflater.inflate( resource , parent, true );
event.setTag(items.get(position));
}
title = (TextView) event.findViewById( R.id.etitle);
desc = (TextView) event.findViewById( R.id.edesc );
date = (TextView)event.findViewById(R.id.edate);
time = (TextView)event.findViewById(R.id.etiming);
venue = (TextView)event.findViewById(R.id.elocation);
title.setTypeface(font);
System.out.print(items.get(0).toString());
title.setText(items.get(0).toString());
desc.setText(items.get(1).toString());
date.setText(items.get(2).toString());
time.setText(items.get(3).toString());
venue.setText(items.get(4).toString());
return event;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 5;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return eventList.get(position).get(position).get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
}
Any help would be greatly appreciated.
Here is how I am filling the data in the Array List
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String title = c.getString(TAG_TITLE);
String description = c.getString(TAG_DESC);
String date = c.getString(TAG_DATE);
String time = c.getString(TAG_TIME);
String venue = c.getString(TAG_VENUE);
// creating new HashMap
HashMap<String, List<String>> map = new HashMap<String, List<String>>();
List<String> el = new ArrayList<String>();
el.add(title);
el.add(description);
el.add(date);
el.add(time);
el.add(venue);
// adding each child node to HashMap key => value
map.put(TAG_TITLE, el);
// map.put(TAG_DESC, description);
//muap.put(TAG_DATE, date);
// adding HashList to ArrayList
eventList.add(map);
}
and then here I am setting the adapter
EventsAdapter adapter = new EventsAdapter(getActivity(), R.layout.events_list_item, eventList);
lv.setAdapter( adapter);
I think it would be useful to consider when you are filling that list.
a good design pattern is to create the data as an empty hashmap, establish the adapter with that map, declare the listview( or whatever ) and then assign the adapter with the empty data set. later, fill the hashmap, and then adapter.notifydatasetchanged
I declare these feilds:
//array of places filtered by keyword
List<Place> places = new ArrayList<Place>( );
//spinner of places filtered by keyword
Spinner placesSpinner;
//adapter for spinner
private PlacesSpinnerAdapter placesSpinnerAdapter;
in onCreate:
//this is for a spinner, but same difference
placesSpinner = (Spinner)findViewById( R.id.placesSpinner );
placesSpinnerAdapter = new PlacesSpinnerAdapter( this,
android.R.layout.simple_spinner_dropdown_item, places );
placesSpinner.setAdapter( placesSpinnerAdapter );
and somewhere in the onPostExecute method of an AsyncTask you have no interest in
places.clear( );
places.addAll( result.results );
placesSpinnerAdapter.notifyDataSetChanged( );
placesSpinner.performClick( );
and lastly, here's a difference I see: adapters do Lists, I've never had a good time passing them hashmaps... do a map.keySet() or map.values(); as you hand the data over to the adapter; I know for certain the very standard pattern I just described does not work if the data set is hashmaps
gl hf
return list size from getCount method
#Override
public int getCount() {
return eventList.size();
}
As the array list inside the adapter does not have 5 items(it has only one item) so try return the size of the list
simply use this code for custom adapter java
public class CustomAdapter extends SimpleAdapter {
ArrayList<HashMap<String,String>> arrayList;
Context context;
public CustomAdapter(Context context,ArrayList<HashMap<String,String>> arrayList, int resource, String[] from ,int[] to) {
super(context, arrayList, resource, from, to);
this.context = context;
this.arrayList = arrayList;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//return super.getView(position, convertView, parent);
View view = super.getView(position,convertView,parent);
RelativeLayout container = (RelativeLayout)
view.findViewById(R.id.container);
return view;
}
}
and this is WelcomeActivity
ArrayList<HashMap<String, String>> userList = "Define your list here"
String[] from = new String[]{"name","phone"};
int[] to = new int[]{R.id.name,R.id.phone};
ListView lv = (ListView) findViewById(R.id.list);
CustomAdapter customAdapter = new CustomAdapter(this,userList,R.layout.user_list_f,from,to);
lv.setAdapter(customAdapter);
it has been working for me perfectly

Press button in listView adapter to get data in this row

I have a listView that shows data that in sqlite, I'm using baseAdapter.
The list row contains text and button.
I press the button in each row to give me each data of the selected row from the database (not pressing the row itself)
This is code of listView:
tipsList = new ArrayList<HashMap<String, String>>();
list = (ListView) rootView.findViewById(R.id.tipList);
do {
map = new HashMap<String, String>();
map.put(DAO.TIP_ID, c.getString(c.getColumnIndex(c.getColumnName(0))));
map.put(DAO.TIP_CONTENT, c.getString(c.getColumnIndex(c.getColumnName(1))));
map.put(DAO.TIP_FAVORITE, c.getString(c.getColumnIndex(c.getColumnName(2))));
// adding HashList to ArrayList
tipsList.add(map);
} while (c.moveToNext());
tipsAdapter = new TipsAdapter(getActivity(), tipsList, tipType, db);
list.setAdapter(tipsAdapter);
And this is code of TipsAdapter.java
public class TipsAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
Context context;
Typeface tf;
String tipID;
String tipText;
String isFavorite;
DAO db;
HashMap<String, String> quote;
int selectedTipType;
public TipsAdapter(Activity a, ArrayList<HashMap<String, String>> d, int selectedTipType, DAO db) {
activity = a;
data = d;
context = a;
this.selectedTipType = selectedTipType;
this.db = db;
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
// ==============================================================================
public int getCount() {
return data.size();
}
// ==============================================================================
public Object getItem(int position) {
return position;
}
// ==============================================================================
public long getItemId(int position) {
return position;
}
// ==============================================================================
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.tip_list_row, null);
TextView tipContent = (TextView) vi.findViewById(R.id.tip_text); // tip
final ImageView favStar = (ImageView) vi.findViewById(R.id.favorite_star);
tf = Typeface.createFromAsset(activity.getAssets(), "fonts/bauhausm_0.ttf");
tipContent.setTypeface(tf);
quote = new HashMap<String, String>();
quote = data.get(position);
tipText = quote.get(DAO.TIP_CONTENT).trim();
favStar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// I want here get all data like tipId - tipText - tipFavotite of the current row in toast
}
});
return vi;
}
}
How to get the data of the current row when press the button?
Hope anyone got my mean.
Thanks in advance.
Maybe you can set the tag of your button.
favStar.setTag(position);
favStar.setOnClickListener (new OnClickListener()
{
#Override
public void onClick(View view) {
int position = (int) view.getTag();
HashMap<String, String>() quote = data.get(position);
String tipText = qout.get(DAO.TIP_CONTENT);
String tipContent = ......;
}
}
I Solved it by myself by making position as final and put quote = data.get(position); inside the listener of the button.

Listview : Getting the text of the selected row

I have a listview with an image and a textview in each row.
I want to get the value of the text on the clicking of the whole row.
Below code is behaving strange.I am getting the value of random row instead of the one clicked.
I am not getting what is wrong.
Any help would be appreciated.
I am doing this, :
public static class LazyAdapter extends BaseAdapter {
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader=new ImageLoader(activity.getApplicationContext());
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.list_row, null);
title = (TextView)vi.findViewById(R.id.title); // title
ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image
HashMap<String, String> song = new HashMap<String, String>();
song = data.get(position);
// Setting all values in listview
title.setText(song.get(Meida_listActivity.KEY_TITLE));
imageLoader.DisplayImage(song.get(Meida_listActivity.KEY_THUMB_URL), thumb_image);
vi.setOnClickListener( new View.OnClickListener()
{
public void onClick(View v)
{
String listValue = (String) title.getText();
System.out.println("this is value of string ::: :::: " + listValue);
}
});
return vi;
}
}
You can also try implementing click for listview and get text like this!Hope it works..
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
TextView text = (TextView) view.findViewById(R.id.title);
String lst_txt = text.getText().toString().trim();
System.out.println("this is value of string ::: :::: " + lst_txt);
}
});
On your OnClickListener change your code to this:
vi.setOnClickListener( new View.OnClickListener()
{
public void onClick(View v)
{
String listValue = (String) data.get(position).get(Meida_listActivity.KEY_TITLE);
System.out.println("this is value of string ::: :::: " + listValue);
}
});
That way you ensure you are referring the correct row.
type data of variable data is ArrayList
HashMap<String, String> _hashMap = (HashMap<String, String>) data.get(position);
String _test = _hashMap.get("Text").toString();
vi.setOnClickListener( new View.OnClickListener()
{
public void onClick(View v)
{
title = (TextView)v.findViewById(R.id.title);
String listValue = title.getText().toString();
System.out.println("this is value of string ::: :::: " + listValue);
}
});
return vi;
add below line listView.setOnItemClickListener(this); and Override onItemClick method. Retrive object on the basis of position(third parameter).
use this listener into Activity oncreate method
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> av, View arg1, int index,
long arg3) {
// Perform Action here.....
String value = av.getItemAtPosition(index).toString();
}
});

Categories

Resources