insert value to arraylist hashmap base on position - android

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;
}

Related

Listview is showing only one row when showing json data in android

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.

how to hide textview whose value is null in customadapter

Please tell me how to hide the textview when it sometimes return null value through custom adapter. Here below is my code.
Android code:
public void showList() {
try {
JSONObject jsonObj = new JSONObject(myJSON);
search = jsonObj.getJSONArray(TAG_RESULT);
for (int i = 0; i < search.length(); i++) {
JSONObject c = search.getJSONObject(i);
String title = c.getString(TAG_TITLE);
String phone = c.getString(TAG_PHONE);
String email = c.getString(TAG_EMAIL);
String description = c.getString(TAG_DESCRIPTION);
String postDate = c.getString(TAG_DATE);
String username=c.getString(TAG_USERNAME);
String city=c.getString(TAG_CITY);
String locality= c.getString(TAG_LOCALITY);
HashMap<String, String> search = new HashMap<String, String>();
search.put(TAG_TITLE, title);
search.put(TAG_PHONE, phone);
search.put(TAG_EMAIL, email);
search.put(TAG_DESCRIPTION, description);
search.put(TAG_DATE, postDate);
search.put(TAG_USERNAME, username);
search.put(TAG_CITY, city);
search.put(TAG_LOCALITY, locality); /* in some case it is null...at that time i want to hide tvlocality textview.*/
searchList.add(search);
}
ListAdapter adapter = new SimpleAdapter(
ResultDetail.this, searchList, R.layout.activity_show__result,
new String[]{TAG_TITLE, TAG_PHONE, TAG_EMAIL, TAG_DESCRIPTION, TAG_DATE, TAG_USERNAME, TAG_CITY, TAG_LOCALITY},
new int[]{R.id.tvTitle, R.id.tvMobile, R.id.tvEmail, R.id.tvDesp, R.id.tvDate, R.id.tvUserName, R.id.tvCityName, R.id.tvLocality}
);
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
i am showing this result in listview .
Or simply override the getView(....) method like below example
ListAdapter adapter = new SimpleAdapter(this, searchList, R.layout.your_adapter_view, new String[]{"city"
}, new int[]{R.id.city}) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if (v == null) {
holder = new ViewHolder();
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.your_adapter_view, null);
holder.textView = (TextView) v.findViewById(R.id.city);
//other stuff
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
Map<String, String> data = searchList.get(position);
if (!TextUtils.isEmpty(data.get("city"))) {
holder.textView.setText(data.get("city"));
holder.textView.setVisibility(View.VISIBLE);
} else {
holder.textView.setVisibility(View.GONE);
}
//do the same thing for other possible views.
return v;
}
class ViewHolder {
TextView textView;
//your other views
}
};
I prefer TextUtils.isEmpty(str) for null and empty check.
Returns true if the string is null or 0-length.
Use below code in Adapter
if(textView.getText().toString()==null || textView.getText().toString().isEmpty() ){
textView.setVisibility(View.GONE);
}
else
{
textView.setText(searchList.get(position).get(TAG_TITLE));
}
You need to create a custom adapter, then inside getView() method you can change the TextView visibility depending on your items value.
public View getView (int position, View convertView, ViewGroup parent){
//...
if( yourItem == null ){
textView.setVisibility(View.INVISIBLE); // or GONE if you want
} else {
textView.setVisibility(View.VISIBLE);
}
//....
}

Android ListView duplicating onclicking an item

I am having a problem in my listview. Actually I have implemented Facebook Like Feed from Facebook Like Custom Feed
which is fetching data from MySQL database. At bottom of every list item I am having a Like Button from this library Material Favourite Button. My Problem is that when i click like on 1st List item, The 5th list item gets automatically liked and if i click on 2nd List item 4th list item gets liked and so on. I tried everything i could do but nothing resolved this problem. I tried to add view holder also to my list adapter class as suggested in various answered questions here but it didn't resolve my issue. Kindly Help! Below is my adapter class:
public class FeedListAdapter extends BaseAdapter {
private Activity activity;
private int lastPosition = -1;
private DatabaseHandler db;
ViewHolder holder;
int id = 0;
String email;
private List<FeedItem> feedItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public FeedListAdapter(Activity activity, List<FeedItem> feedItems) {
this.activity = activity;
this.feedItems = feedItems;
}
#Override
public int getCount() {
return feedItems.size();
}
#Override
public Object getItem(int location) {
return feedItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
if (convertView == null){
LayoutInflater inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.feed_item, parent,false);
holder = new ViewHolder();
holder.materialFavoriteButtonNice =
(MaterialFavoriteButton) convertView.findViewById(R.id.like_anim);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView timestamp = (TextView) convertView
.findViewById(R.id.timestamp);
//get User Email
db = new DatabaseHandler(activity.getApplication());
db = new DatabaseHandler(activity.getApplication());
HashMap<String, String> user = db.getUserDetails();
email = user.get("email").toString();
// End get User Email ID for sending it to db
//Getting Views from Layout
TextView statusMsg = (TextView) convertView
.findViewById(R.id.txtStatusMsg);
TextView url = (TextView) convertView.findViewById(R.id.txtUrl);
final TextView like = (TextView) convertView.findViewById(R.id.like_box_no);
TextView share = (TextView) convertView.findViewById(R.id.share_no);
TextView comment = (TextView) convertView.findViewById(R.id.comment_no);
NetworkImageView profilePic = (NetworkImageView) convertView
.findViewById(R.id.profilePic);
FeedImageView feedImageView = (FeedImageView) convertView
.findViewById(R.id.feedImage1);
//End Getting Views from Layout
final FeedItem item = feedItems.get(position);
name.setText(item.getName());
// Converting timestamp into x ago format
CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
Long.parseLong(item.getTimeStamp()),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
timestamp.setText(timeAgo);
// Check for empty status message
if (!TextUtils.isEmpty(item.getStatus())) {
statusMsg.setText(item.getStatus());
statusMsg.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
statusMsg.setVisibility(View.GONE);
}
// Chcek for empty Like
if (!TextUtils.isEmpty(item.getLike())) {
like.setText(item.getLike());
like.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
like.setText("0");
}
// Chcek for empty Comment
if (!TextUtils.isEmpty(item.getComment())) {
comment.setText(item.getComment());
comment.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
comment.setText("0");
}
// Chcek for empty Share
if (!TextUtils.isEmpty(item.getShare())) {
share.setText(item.getShare());
share.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
share.setText("0");
}
if (item.getFav().equals("1")) {
holder.materialFavoriteButtonNice.setFavorite(true, false);
holder.materialFavoriteButtonNice.setVisibility(View.VISIBLE);
} else {
// status is empty, remove from view
holder.materialFavoriteButtonNice.setFavorite(false, false);
}
// Checking for null feed url
if (item.getUrl() != null) {
url.setText(Html.fromHtml("<a href=\"" + item.getUrl() + "\">"
+ item.getUrl() + "</a> "));
// Making url clickable
url.setMovementMethod(LinkMovementMethod.getInstance());
url.setVisibility(View.VISIBLE);
} else {
// url is null, remove from the view
url.setVisibility(View.GONE);
}
// user profile pic
profilePic.setImageUrl(item.getProfilePic(), imageLoader);
imageLoader.get(item.getProfilePic(), ImageLoader.getImageListener(profilePic, R.drawable._businessman, R.drawable._businessman));
// Feed image
if (item.getImge() != null) {
feedImageView.setImageUrl(item.getImge(), imageLoader);
feedImageView.setVisibility(View.VISIBLE);
feedImageView
.setResponseObserver(new FeedImageView.ResponseObserver() {
#Override
public void onError() {
}
#Override
public void onSuccess() {
}
});
} else {
feedImageView.setVisibility(View.GONE);
}
//Animating the List View
Animation animation = AnimationUtils.loadAnimation(activity.getApplication(), (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
convertView.startAnimation(animation);
lastPosition = position;
//End Animating the List View
//onClick Like
holder.materialFavoriteButtonNice.setOnFavoriteChangeListener(new MaterialFavoriteButton.OnFavoriteChangeListener() {
#Override
public void onFavoriteChanged(MaterialFavoriteButton buttonView, boolean favorite) {
id = item.getId();
Log.d("inFavChngeListner", "Clickd" + item.getId());
Toast.makeText(activity.getApplication(), "Fav Changed : " + item.getId(), Toast.LENGTH_SHORT).show();
if (favorite) {
new send_json().execute();
} else {
holder.materialFavoriteButtonNice.setFavorite(false, true);
new send_json_unlike().execute();
}
}
});
return convertView;
}
static class ViewHolder {
MaterialFavoriteButton materialFavoriteButtonNice;
}
//Sending Likes with email id and feed id to Remote Mysql Db
public class send_json extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
if(!holder.materialFavoriteButtonNice.isFavorite())
holder.materialFavoriteButtonNice.setFavorite(true, true);
}
#Override
protected JSONObject doInBackground(String... params) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.like_func(email, String.valueOf(id));
Log.d("BG Like, Email:" + email + "Id: " + String.valueOf(id), json.toString());
return json;
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
if(!holder.materialFavoriteButtonNice.isFavorite())
holder.materialFavoriteButtonNice.setFavorite(true, true);
}
}
//Sending Likes with email id and feed id to Remote Mysql Db
public class send_json_unlike extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
if(!holder.materialFavoriteButtonNice.isFavorite())
holder.materialFavoriteButtonNice.setFavorite(false, true);
}
#Override
protected JSONObject doInBackground(String... params) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.unlike_func(email, String.valueOf(id));
Log.d("BG UnLike, Email:" + email + "Id: " + String.valueOf(id), json.toString());
return json;
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
if(!holder.materialFavoriteButtonNice.isFavorite())
holder.materialFavoriteButtonNice.setFavorite(false, true);
}
}
}
Dont use ViewHolder instance global . Make it inside function scope . And try to change the logic . Only update the model inside the array and just call notifyDataSetChanged() method. I think it will solve your issue.

How to fetch the image using JSON in ListFragment?

I am new to android development,I am parsing my data using JSON Parsing method,I extend my class with List Fragment and I want my data in list view but the problem is i am getting all the data perfectly except the images,i don't know how to solve it,my response looks like this
{"matching":[{"name":"Monic Dano","profile_id":"GM335695","image":"http://mywebsitename.com/images/Girlnoimage.jpg","cast":"","age":"24","location":"Ivory Coast"}]}
public class HomeFragment extends ListFragment {
//CustomAdapter adapter;
//private List<RowItem> rowItems;
private ProgressDialog pDialog;
//JSON parser class
JSONParser jsonParser = new JSONParser();
JSONArray matching=null;
ArrayList<HashMap<String,String>> aList;
private static String MATCH_URL = null;
private static final String TAG_MATCH="matching";
private static final String TAG_NAME="name";
private static final String TAG_PROFILE="profile_id";
private static final String TAG_IMAGE="image";
private static final String TAG_CAST="cast";
private static final String TAG_AGE="age";
private static final String TAG_LOCATION="location";
private ListView listview;
public HomeFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String strtext = getArguments().getString("user_login_id");
MATCH_URL = "http://mywebsitename.com/webservice/matching?version=apps&user_login_id="+strtext;
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
aList = new ArrayList<HashMap<String,String>>();
// rowItems = new ArrayList<RowItem>();
listview=(ListView)rootView.findViewById(android.R.id.list);
new LoadAlbums().execute();
return rootView;
}
class LoadAlbums extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(HomeFragment.this.getActivity());
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(MATCH_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
matching = jsonObj.getJSONArray(TAG_MATCH);
// looping through All Contacts
for (int i = 0; i < matching.length(); i++) {
JSONObject c = matching.getJSONObject(i);
// Storing each json item values in variable
String user_name = c.getString(TAG_NAME);
String user_profile=c.getString(TAG_PROFILE);
String user_image=c.getString(TAG_IMAGE);
String user_cast=c.getString(TAG_CAST);
String user_age=c.getString(TAG_AGE);
String user_location=c.getString(TAG_LOCATION);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_NAME,user_name);
map.put(TAG_PROFILE, user_profile);
map.put(TAG_IMAGE, user_image);
map.put(TAG_CAST, user_cast);
map.put(TAG_AGE, user_age+" years");
map.put(TAG_LOCATION, user_location);
// adding HashList to ArrayList
aList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
protected void onPostExecute(String file_url) {
super.onPostExecute(file_url);
// dismiss the dialog after getting all albums
if (pDialog.isShowing())
pDialog.dismiss();
// updating UI from Background Thread
/**
* Updating parsed JSON data into ListView
* */
// updating listview
CustomAdapter adapter = new CustomAdapter(getActivity(),aList);
setListAdapter(adapter);
}
}
}
Try to AndroidQuery with custom adapter :
public class CustomAdapter extends BaseAdapter {
private Context context;
private ArrayList<HashMap<String,String>> listData;
private AQuery aQuery;
private static final String TAG_NAME="name";
private static final String TAG_PROFILE="profile_id";
private static final String TAG_IMAGE="image";
private static final String TAG_CAST="cast";
private static final String TAG_AGE="age";
private static final String TAG_LOCATION="location";
public CustomAdapter(Context context,ArrayList<HashMap<String,String>> listData) {
this.context = context;
this.listData=listData;
aQuery = new AQuery(this.context);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.list_item, null);
holder.propic = (ImageView) convertView.findViewById(R.id.propic);
holder.txtproname = (TextView) convertView.findViewById(R.id.txtproname);
holder.txtproid = (TextView) convertView.findViewById(R.id.txtproid);
holder.txtprofilecast = (TextView) convertView.findViewById(R.id.txtprofilecast);
holder.txtprofileage = (TextView) convertView.findViewById(R.id.txtprofileage);
holder.txtprofileplace = (TextView) convertView.findViewById(R.id.txtprofileplace);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.txtproname.setText(listData.get(position).get(TAG_NAME));
holder.txtproid.setText(listData.get(position).get(TAG_PROFILE));
holder.txtprofilecast.setText(listData.get(position).get(TAG_CAST));
holder.txtprofileage.setText(listData.get(position).get(TAG_AGE));
holder.txtprofileplace.setText(listData.get(position).get(TAG_LOCATION));
aQuery.id(holder.propic).image(listData.get(position).get(TAG_IMAGE),true,true,0,R.drawable.ic_launcher);
// image parameter : 1 : memory cache,2:file cache,3:target width,4:fallback image
return convertView;
}
class ViewHolder{
ImageView propic;
TextView txtproname;
TextView txtproid;
TextView txtprofilecast;
TextView txtprofileage;
TextView txtprofileplace;
}
}
How to set adapter to ListView :
CustomAdapter adapter = new CustomAdapter(getActivity(),aList);
setListAdapter(adapter);
You can use universal image loader for viewing images from your server.Z
Just pass the image url and your view and you are good to go.
For your reference here is the link to Universal Image loader with all its documentation.
https://github.com/nostra13/Android-Universal-Image-Loader
Hop it helps you.
I am hardly suggest you to use Android Query for this. Its mind blowing api given by Android itself. You can download image, download bitmap or whatever you wanna do you can.
You can download the jar file from here :here Download the jar file and set jar to your Build Path.
AQuery androidAQuery=new AQuery(this);
As an example to load image directly from url:
androidAQuery.id(YOUR IMAGEVIEW).image(YOUR IMAGE TO LOAD, true, true, getDeviceWidth(), ANY DEFAULT IMAGE YOU WANT TO SHOW);
As an example to get Bitmap from url:
androidAQuery.ajax(YOUR IMAGE URL,Bitmap.class,0,new AjaxCallback<Bitmap>(){
#Override
public void callback(String url, Bitmap object, AjaxStatus status) {
super.callback(url, object, status);
//You will get Bitmap from object.
}
});
It's very fast and accurate, and using this you can find many more features like Animation when loading; getting a bitmap, if needed; etc.
//Declare adapter globally.
private EfficientAdapter adapter;
//Initialize it in onCreate() method
adapter = new EfficientAdapter(this);
//Set your adapter like
listview.setAdapter(adapter);
//Adapter class code
private class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private Context context;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
this.context = context;
}
#Override
public int getCount() {
return aList.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.YOUR ITEM LAYOUT, null);
holder = new ViewHolder();
holder.txtName = (TextView) convertView.findViewById(R.id.txtName);
holder.txtProfile = (TextView) convertView.findViewById(R.id.txtProfile);
holder.txtCast = (TextView) convertView.findViewById(R.id.txtCast);
holder.txtAge = (ImageView) convertView.findViewById(R.id.txtAge);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtName.setText(aList.get(position).get(TAG_NAME));
holder.txtProfile.setText(aList.get(position).get(TAG_PROFILE));
holder.txtCast.setText(aList.get(position).get(TAG_CAST));
holder.txtAge.setText(aList.get(position).get(TAG_AGE));
aQuery.id(holder.imgUser).image(data.get(position).get(TAG_IMAGE), true, true);
return convertView;
}
class ViewHolder {
TextView txtName;
TextView txtProfile;
TextView txtCast;
TextView txtAge;
ImageView imgUser;
}
}
In source code of SimpleAdapter:
private void bindView(int position, View view) {
final Map dataSet = mData.get(position);
if (dataSet == null) {
return;
}
final ViewBinder binder = mViewBinder;
final String[] from = mFrom;
final int[] to = mTo;
final int count = to.length;
for (int i = 0; i < count; i++) {
final View v = view.findViewById(to[i]);
if (v != null) {
final Object data = dataSet.get(from[i]);
String text = data == null ? "" : data.toString();
if (text == null) {
text = "";
}
boolean bound = false;
if (binder != null) {
bound = binder.setViewValue(v, data, text);
}
if (!bound) {
if (v instanceof Checkable) {
if (data instanceof Boolean) {
((Checkable) v).setChecked((Boolean) data);
} else if (v instanceof TextView) {
// Note: keep the instanceof TextView check at the bottom of these
// ifs since a lot of views are TextViews (e.g. CheckBoxes).
setViewText((TextView) v, text);
} else {
throw new IllegalStateException(v.getClass().getName() +
" should be bound to a Boolean, not a " +
(data == null ? "<unknown type>" : data.getClass()));
}
} else if (v instanceof TextView) {
// Note: keep the instanceof TextView check at the bottom of these
// ifs since a lot of views are TextViews (e.g. CheckBoxes).
setViewText((TextView) v, text);
} else if (v instanceof ImageView) {
if (data instanceof Integer) {
setViewImage((ImageView) v, (Integer) data);
} else {
setViewImage((ImageView) v, text);
}
} else {
throw new IllegalStateException(v.getClass().getName() + " is not a " +
" view that can be bounds by this SimpleAdapter");
}
}
}
}
}
You can see if your view is ImageView , the code will use the url String be the resId in
/**
* Called by bindView() to set the image for an ImageView but only if
* there is no existing ViewBinder or if the existing ViewBinder cannot
* handle binding to an ImageView.
*
* By default, the value will be treated as an image resource. If the
* value cannot be used as an image resource, the value is used as an
* image Uri.
*
* This method is called instead of {#link #setViewImage(ImageView, int)}
* if the supplied data is not an int or Integer.
*
* #param v ImageView to receive an image
* #param value the value retrieved from the data set
*
* #see #setViewImage(ImageView, int)
*/
public void setViewImage(ImageView v, String value) {
try {
v.setImageResource(Integer.parseInt(value));
} catch (NumberFormatException nfe) {
v.setImageURI(Uri.parse(value));
}
}
And your error is here , so you need Override the getView function of SimpleAdapter.Here is code:
Uri uri = Uri.parse("http://gujjumatch.com/images/Girlnoimage.jpg");
image.setImageURI(uri);
You need to create adapter and extend it to BaseAdapter and add all your items and call it in your AsyncTask's method and it will return your output as said by Haresh Chellana.

how can I use HashMap for BaseAdapter

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.

Categories

Resources