Originally, I'm using hashmap using SimpleAdapter, like this:
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
int leng = nodes.getLength();
for (int i = 0; i < leng; i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nodes.item(i);
map.put("nama", parser.getValue(e, "nama"));
map.put("in", parser.getValue(e, "in"));
mylist.add(map);
}
// Adding myList to ListView
ListAdapter adapter = new SimpleAdapter(LihatFarmasiObat.this, mylist,
R.layout.list_farmasi_obat, new String[] { "nama", "in" },
new int[] {R.id.txtListFarmasiNama, R.id.txtListFarmasiIn});
listFarmasiObat.setAdapter(adapter);
But now I'm trying to put a EditText inside ListView, and I got this code from here.
I tried that code and it works, (I need to change some but the code is working).
and but when I tried to combine it with my own code, I got an error Cannot cast from HashMap to LihatFarmasiObat.ListItem on these line:
holder.caption.setText(((ListItem)mylist.get(position)).caption);
//It got an error on mylist
holder.caption.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus){
final int position = v.getId();
final EditText Caption = (EditText) v;
((ListItem)mylist.get(position)).caption = Caption.getText().toString();
// it also got same error on mylist.
}
}
});
return convertView;
class ListItem {
String caption;
//this is the problem (I think) I don't know how to make this hashmap
}
I already try to change it to any other way but it's not working.
and this is my full code:
public class MyAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public MyAdapter() {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
new LoadFarmasi().execute(); // This is for filling mylist with hashmap
notifyDataSetChanged();
}
public int getCount() {
return mylist.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.list_farmasi_obat, null);
holder.caption = (EditText) convertView.findViewById(R.id.editText1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//Fill EditText with the value you have in data source
holder.caption.setText(((ListItem)mylist.get(position)).caption);
holder.caption.setId(position);
//we need to update adapter once we finish with editing
holder.caption.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus){
final int position = v.getId();
final EditText Caption = (EditText) v;
((ListItem)mylist.get(position)).caption = Caption.getText().toString();
}
}
});
return convertView;
}
}
class ViewHolder {
EditText caption;
}
class ListItem {
String caption;
}
Can someone help me? I'm struggle with this for a few days
In getView you need to use
HashMap<String,String> map =mylist.get(position);
// position gives you the index
String value = map.get("nama");
String value2 = map.get("in");
Now use the String's and set it to views accordingly
You have arraylist of hashmap.
Related
I'm trying to show json data in listview in android. I'm getting json data perfectly but when i'm trying to show it in listview just getting only one row.
And i want to show data of each row in an activity as per item click. Here i'm not understanding how to pass the data from json depending on which item is clicked.
here is my code:
public class CustomAdapter extends ArrayAdapter {
List list = new ArrayList();
public CustomAdapter(Context context, int resource) {
super(context, resource);
}
public void add(DataProvider dataProvider) {
super.add(dataProvider);
list.add(dataProvider);
}
#Override
public int getCount() {
return list.size();
}
#Nullable
#Override
public Object getItem(int position) {
return list.get(position);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View row = convertView;
dataProviderHolder holder;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.custom_list, parent, false);
holder = new dataProviderHolder();
holder.name = (TextView) row.findViewById(R.id.name);
holder.subject = (TextView) row.findViewById(R.id.subject);
holder.date = (TextView) row.findViewById(R.id.date);
holder.time = (TextView) row.findViewById(R.id.tim);
row.setTag(holder);
} else {
holder = (dataProviderHolder) row.getTag();
}
DataProvider provider = (DataProvider) this.getItem(position);
holder.name.setText(provider.getName());
holder.subject.setText(provider.getSubject());
holder.date.setText(provider.getDate());
holder.time.setText(provider.getTime());
return row;
}
static class dataProviderHolder {
TextView name, subject, date, time;
}
}
Json parsing :
listView = (ListView) findViewById(R.id.list);
sessionManager = new SessionManager(this);
listView.setAdapter(customAdapter);
HashMap<String, String> user = sessionManager.getUserDetails();
json_string = user.get(SessionManager.JSON_STRING);
try {
String name, subject, message, date, time;
jsonObject = new JSONObject(json_string);
jsonArray = jsonObject.getJSONArray("message");
int count = 0;
while (count < jsonObject.length()) {
JSONObject object = jsonArray.getJSONObject(count);
name = object.getString("name");
subject = object.getString("subject");
message = object.getString("message");
date = object.getString("date");
time = object.getString("time");
sessionManager.getJsonMesssage(message);
DataProvider dataProvider = new DataProvider(name, subject, date, time);
customAdapter.add(dataProvider);
count++;
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HashMap<String, String> user = sessionManager.getUserDetails();
String message = user.get(SessionManager.JSON_MESSAGE);
Intent i = new Intent(MessageList.this, MessageDetails.class);
i.putExtra("message", message);
startActivity(i);
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
First of all, do not put listview.setOnItemClickListener in a loop. That does nothing. Instead add it in your getView() method of adapter.`
row.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HashMap<String, String> user = sessionManager.getUserDetails();
String message = user.get(SessionManager.JSON_MESSAGE);
Intent i = new Intent(context, MessageDetails.class);
i.putExtra("message", message);
startActivity(i);
}
});
Then, set your adapter after adding all the list items in while loop.
Continue from my post about how can I use HashMap for BaseAdapter, I have another problem here. How can I insert or replace the value on arraylist hashmap?
I tried using mylist.set(position, map); but it's not working
my full code:
This code is to get data from database and put it on mylist
class LoadFarmasi extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(LihatFarmasiObat.this);
pDialog.setMessage(Html.fromHtml("Ambil Data Farmasi..."));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Places XML
* */
protected String doInBackground(String... args) {
String xml;
try {
// ----------------------------Make data Parameter for query-----------------
List<BasicNameValuePair> postsku = new ArrayList<BasicNameValuePair>(0);
postsku.add(new BasicNameValuePair("noregis", noregis));
parser = new XMLParser();
xml = parser.getXmlFromUrlWithPost(URL_FARMASI,postsku); // getting XML
Document doc = parser.getDomElement(xml); // getting DOM element
nodes = doc.getElementsByTagName("result");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* and show the data in UI
* Always use runOnUiThread(new Runnable()) to update UI from background
* thread, otherwise you will get error
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all hospitals
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed Places into LISTVIEW
* */
int leng = nodes.getLength();
for (int i = 0; i < leng; i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nodes.item(i);
map.put("nama", parser.getValue(e, "nama"));
map.put("in", parser.getValue(e, "in"));
map.put("id", "");
mylist.add(map);
}
}
});
}
}
This is for insert value on edittext and put the value to mylist
public class MyAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public MyAdapter() {
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0; i < 20; i++) {
new LoadFarmasi().execute();
}
notifyDataSetChanged();
}
public int getCount() {
return mylist.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
HashMap<String,String> map =mylist.get(position);
// position gives you the index
String value = map.get("nama");
String value2 = map.get("in");
String value3 = map.get("id");
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.list_farmasi_obat, null);
holder.caption = (EditText) convertView.findViewById(R.id.editText1);
holder.txtNama = (TextView) convertView.findViewById(R.id.txtListFarmasiNama);
holder.txtIn = (TextView) convertView.findViewById(R.id.txtListFarmasiIn);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//Fill EditText with the value you have in data source
holder.txtNama.setText(value);
holder.txtIn.setText(value2);
holder.caption.setText(value3);
holder.txtNama.setId(position);
holder.txtIn.setId(position);
holder.caption.setId(position);
//we need to update adapter once we finish with editing
holder.caption.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus){
final int position = v.getId();
final EditText Caption = (EditText) v;
HashMap<String, String> map = new HashMap<String, String>();
map.put("id", Caption.getText().toString());
mylist.set(position, map);
}
}
});
return convertView;
}
}
class ViewHolder {
EditText caption;
TextView txtNama;
TextView txtIn;
}
// try this way here i also know what are changes i have done in your code.
please replace your getView() and let me know still have any problem
First of all i have add final keyword to position and hash so it can be access in onFocusChange()
Second one is we direct access position rather getting from view getTag Id.
Third one is i have replace id value in hashmap and notify adapter so update data reflected in list.
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
final HashMap<String,String> map =mylist.get(position);
// position gives you the index
String value = map.get("nama");
String value2 = map.get("in");
String value3 = map.get("id");
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.list_farmasi_obat, null);
holder.caption = (EditText) convertView.findViewById(R.id.editText1);
holder.txtNama = (TextView) convertView.findViewById(R.id.txtListFarmasiNama);
holder.txtIn = (TextView) convertView.findViewById(R.id.txtListFarmasiIn);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//Fill EditText with the value you have in data source
holder.txtNama.setText(value);
holder.txtIn.setText(value2);
holder.caption.setText(value3);
holder.txtNama.setId(position);
holder.txtIn.setId(position);
holder.caption.setId(position);
//we need to update adapter once we finish with editing
holder.caption.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus){
EditText Caption = (EditText) v;
map.put("id", Caption.getText().toString());
notifyDataSetChanged();
}
}
});
convertView.setTag(holder);
return convertView;
}
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.
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();
}
});
I am trying to use secionIndexer with fast scroll in list view.
I have implemented but
on scroll of list it should popup the current letter at which we have scrolled,
but its not showing that.
on debug mode I came to know that getSectipons() and getPositionForSection() are never called in my case ,
but in any other simple example that i tried from web it does make a call to those functions.
Pelase suggest me what to do
//##################
here is code of my adapter
//#######################
public class MyListAdapter extends ArrayAdapter<Object> implements SectionIndexer {
Activity context;
Object[] listData;
HashMap<String, Integer> alphaIndexer;
String[] sections;
public MyListAdapter(Activity context, Object[] objects) {
super(context, R.layout.new_invest_row, objects);
this.context = context;
listData = objects;
alphaIndexer = new HashMap<String, Integer>();
//changes here
ArrayList myArrayList = new ArrayList();
for (int ix=0; ix<objects.length; ix++) {
myArrayList.add(objects[ix]);
}
Collections.sort(myArrayList, new Comparator<HashMap<String, String>>(){
public int compare(HashMap<String, String> one, HashMap<String, String> two) {
return one.get("Name").compareToIgnoreCase(two.get("Name"));
}
});
listData = myArrayList.toArray();
//Arrays.sort(listData);
for (int i = listData.length - 1; i >= 0; i--) {
final HashMap<String, String> obj = (HashMap<String, String>)listData[i];
String element = obj.get("Name");
alphaIndexer.put(element.substring(0, 1).toUpperCase(), i);
}
Set<String> keys = alphaIndexer.keySet(); // set of letters
// Copy into a List for sorting
Iterator<String> it = keys.iterator();
ArrayList<String> keyList = new ArrayList<String>();
while (it.hasNext()) {
String key = it.next();
keyList.add(key);
}
Collections.sort(keyList);
// Convert to array
sections = new String[keyList.size()];
keyList.toArray(sections);
for(int c=0;c < sections.length;c++)Log.e("secction<"+c+">","+"+sections[c]);
Log.e("alphaIndexer","+"+alphaIndexer);
}
static class ViewHolder {
TextView txtName;
TextView txtOwner;
TextView txtStartDate;
TextView txtEndDate;
TextView txtStatus;
ImageView imgIcon;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
View rowView = convertView;
if (rowView == null) {
LayoutInflater inflater = context.getLayoutInflater();
rowView = inflater.inflate(R.layout.new_invest_row, null, true);
holder = new ViewHolder();
**holder.txtName = (TextView) rowView.findViewById(R.id.invest_row_name);**
//my custom code here
rowView.setTag(holder);
} else {
holder = (ViewHolder) rowView.getTag();
}
#SuppressWarnings("unchecked")
final HashMap<String, String> obj = (HashMap<String, String>)listData[position];
String str = obj.get("Name");
if(null == str){
str = "";
}
holder.txtName.setText(str);
//#################
//my custom code here
return rowView;
}
public int getPositionForSection(int section) {
String letter = sections[section];
Log.e("alphaIndexer.get(letter)","+"+alphaIndexer.get(letter));
return alphaIndexer.get(letter);
}
public int getSectionForPosition(int arg0) {
// TODO Auto-generated method stub
return 1;
}
public Object[] getSections() {
return sections;
}
}
//#######################
I assume that in adapter when I am passing the textViewId its not taking the currect textVewId as the sectionIndexer functions are never called.
In the Layout new_invest_row I am getting custom row which have an icon and few textViews.
I am sorting the list on the basis of name of the Object that I am displaying in each row.
i want indexer to work on the name of the object.
Please help me with exact solution