i tried to add two textViews to list item.that data get from list. when the list print, it display correctly. But in list view its not print correctly. Can anyone help me?
This is the custom adapter class.
#Override
public View getView(int arg0, View convertView, ViewGroup arg2) {
// TODO Auto-generated method stub
final String text1 = listData.get(0);
final String text2 = listData.get(1);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.ratings_list, null);
}
TextView lblListHeader1 = (TextView) convertView.findViewById(R.id.textView1);
lblListHeader1.setText(text1);
TextView lblListHeader2 = (TextView) convertView.findViewById(R.id.textView2);
lblListHeader2.setText(text2);
return convertView;
}
This is the activity code.
public void ListDrwaer() {
try {
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("ratings");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String restName = jsonChildNode.optString("rest_name");
listData = new ArrayList<String>();
if (restName.equalsIgnoreCase(name)) {
String userName = jsonChildNode.optString("user_name");
String rate = jsonChildNode.optString("rate");
String ratOut = "Rate : " + rate;
listData.add(userName);
listData.add(ratOut);
Log.d("Data", userName + rate);
}
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error..." + e.toString(),
Toast.LENGTH_LONG).show();
}
RatingsAdapter adapter = new RatingsAdapter(getApplicationContext(),
listData);
listView.setAdapter(adapter);
}
I want to add user name, below of that it's rate.
This is should be the output list.
01-23 11:59:09.102: D/Data(4873): omali 3.5
01-23 11:59:09.102: D/Data(4873): sunil 2
01-23 11:59:09.102: D/Data(4873): kuma#fh.com 1.5
01-23 11:59:09.102: D/Data(4873): fhhhy#ghj.com 0.5
First of all, the way you are building the list, it will never work, since you are deleting it and creating a new one in every iteration, so when you create the adapter, in the listyou only have the last item.
I would do:
ArrayList<Pair<String,String>> listData = new ArrayList<Pair<String,String>>(); //added
public void ListDrwaer() {
try {
JSONObject jsonResponse = new JSONObject(strJson1);
JSONArray jsonMainNode = jsonResponse.optJSONArray("ratings");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String restName = jsonChildNode.optString("rest_name");
//removed listData = new ArrayList<String>();
if (restName.equalsIgnoreCase(name)) {
String userName = jsonChildNode.optString("user_name");
String rate = jsonChildNode.optString("rate");
String ratOut = "Rate : " + rate;
listData.add(new Pair<String,String>(userName,ratOut ));//added
//removed listData.add(userName);
//removed listData.add(ratOut);
Log.d("Data", userName + rate);
}
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error..." + e.toString(),
Toast.LENGTH_LONG).show();
}
RatingsAdapter adapter = new RatingsAdapter(getApplicationContext(),
listData);
listView.setAdapter(adapter);
}
Then, in the custom adapter class, you retrieve that data simply by
#Override
public View getView(int arg0, View convertView, ViewGroup arg2) {
// TODO Auto-generated method stub
//only this 3 lines change
Pair<String,String> item= listData.get(arg0);
final String text1 = item.first;
final String text2 = item.second;
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.ratings_list, null);
}
TextView lblListHeader1 = (TextView) convertView.findViewById(R.id.textView1);
lblListHeader1.setText(text1);
TextView lblListHeader2 = (TextView) convertView.findViewById(R.id.textView2);
lblListHeader2.setText(text2);
return convertView;
}
You are always printing the wrong data, regardless of the position of the item
final String text1 = listData.get(0);
final String text2 = listData.get(1);
So Better take the Different lists of the username and ratOut and display the data
final String text1 = userNameListData.get(arg0);
final String text2 = ratOutListData.get(arg0);
Here arg0 is the position
Replace this:
final String text1 = listData.get(0);
final String text2 = listData.get(1);
with:
final String text1 = listData.get(2*arg0);
final String text2 = listData.get((2*arg0)+1);
change to:
final String text1 = listData.get(arg0*2);
final String text2 = listData.get(arg0*2+1);
and override:
#Override
public int getCount() {
// TODO Auto-generated method stub
return listData.size()/2;
}
As you are adding both the text in one arraylist 0,1 belong to first item and 2,3 belong to 2nd and so on.
Also size of the list view item would be half of the size of arraylist.
Try this.
also change this:
listData = new ArrayList<String>();//<--out side for loop
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String restName = jsonChildNode.optString("rest_name");
if (restName.equalsIgnoreCase(name)) {
String userName = jsonChildNode.optString("user_name");
String rate = jsonChildNode.optString("rate");
String ratOut = "Rate : " + rate;
listData.add(userName);
listData.add(ratOut);
Log.d("Data", userName + rate);
}
}
Related
its is working fine but its taking too much time for arraylist size 7000 . is there any other way to display this report in fast way.to display 1000 row its taking 3 minutes which very huge time .can we use another way to make this report instead of uving view inflate with layout which will work fast.Thank in advance
spinner=(Spinner)findViewById(R.id.searchableSpinnerLedgerReport);
spinner.setAdapter(new ArrayAdapter<>(LedgerReportActivity.this,R.layout.support_simple_spinner_dropdown_item,numberlist));
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(position==-1){
Toast.makeText(getApplicationContext(), "plz select number", Toast.LENGTH_SHORT).show();
}
else {
String snumber= parent.getItemAtPosition(position).toString();
ArrayList<HashMap<String, String>> myList=ledgerReportDataCon.getSelectedReport(snumber); //size of comming data is 7000
Log.d("size of report list", String.valueOf(myList.size()));
// Log.d("name",snumber);
if(Float.parseFloat (myList.get(0).get(ConstLedgerReport.key_cLOSING))>0)
{
tclosingblnc.setText(myList.get(0).get(ConstLedgerReport.key_cLOSING));
}
else {
tclosingblnc2.setText(myList.get(0).get(ConstLedgerReport.key_cLOSING));
}
if(Float.parseFloat(myList.get(0).get(ConstLedgerReport.key_oPENING))>0)
{
topeningblnc.setText(myList.get(0).get(ConstLedgerReport.key_oPENING));
}
else {
topeningblnc2.setText(myList.get(0).get(ConstLedgerReport.key_oPENING));
}
for(int i=0;i<myList.size();i++) {
String ledgertype=myList.get(i).get(ConstLedgerReport.key_lEDGERTYPE);
String narration=myList.get(i).get(ConstLedgerReport.key_nARRATION);
final View partyView = getLayoutInflater().inflate(R.layout.ledger_report_item, null, false);
LinearLayout headerLayout=(LinearLayout) partyView.findViewById(R.id.headder);
TextView particular = (TextView) partyView.findViewById(R.id.particular);
TextView vchType = (TextView) partyView.findViewById(R.id.vchType);
TextView debit = (TextView) partyView.findViewById(R.id.debit);
TextView credit = (TextView) partyView.findViewById(R.id.credit);
TextView date = (TextView) partyView.findViewById(R.id.date);
TextView vchno = (TextView) partyView.findViewById(R.id.vchno);
particular.setText( myList.get(i).get(ConstLedgerReport.key_pARTICULARS));
vchType.setText( myList.get(i).get(ConstLedgerReport.key_vCHTYPE));
date.setText( myList.get(i).get(ConstLedgerReport.key_vCHDATE));
vchno.setText( myList.get(i).get(ConstLedgerReport.key_vCHNUM));
if (ledgertype.equalsIgnoreCase("Dr"))
{
debit.setText( myList.get(i).get(ConstLedgerReport.key_lEDGERAMT));
totaldebit=totaldebit+Float.parseFloat( myList.get(i).get(ConstLedgerReport.key_lEDGERAMT));
}
else if (ledgertype.equalsIgnoreCase("Cr"))
{
credit.setText( myList.get(i).get(ConstLedgerReport.key_lEDGERAMT));
totalcredit=totalcredit+Float.parseFloat( myList.get(i).get(ConstLedgerReport.key_lEDGERAMT));
}
listViewLayout.addView(partyView);
String[] itemArr=narration.split("~");
// Log.d("first array is ....: ", Arrays.toString(itemArr));
headerLayout.setVisibility(View.INVISIBLE);
if(!narration.equalsIgnoreCase("Array")) {
for (int j = 0; j < itemArr.length; j++) {
headerLayout.setVisibility(View.VISIBLE);
final View itemListView = getLayoutInflater().inflate(R.layout.ledger_report_itemlist, null, false);
TextView iname = (TextView) itemListView.findViewById(R.id.iname);
TextView iqty = (TextView) itemListView.findViewById(R.id.iqty);
TextView iunit = (TextView) itemListView.findViewById(R.id.iunit);
TextView irate = (TextView) itemListView.findViewById(R.id.irate);
TextView itotal = (TextView) itemListView.findViewById(R.id.itotal);
String temp1 = itemArr[j].replace("]][[", ",");
String temp2 = temp1.replace("[[", "");
String temp3 = temp2.replace("]]", "");
String[] itemArrList = temp3.split(",");
// Log.d("second array is ....: ", Arrays.toString(itemArrList));
iname.setText(itemArrList[0]);
iqty.setText(itemArrList[4]);
iunit.setText(itemArrList[1]);
irate.setText(itemArrList[5]);
itotal.setText(itemArrList[7]);
listViewLayout.addView(itemListView);
// Log.d("created view msz", String.valueOf(j));
}
}
}
tdebit.setText(String.valueOf(totaldebit));
tcredit.setText(String.valueOf(totalcredit));
}
}
enter image description here
I have following Json Response,I am trying to set color as per DisplyText,but it only set last color code to whole String,
JSON Response
JAVA Code
ch_list = new ArrayList<String>();
color_list=new ArrayList<String>();
try {
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
System.out.println("person"+person);
String searchcode = person.getString("searchCode");
System.out.println("searchcode"+searchcode);
JSONArray ja = person.getJSONArray("itemList");
for (int j = 0; j < ja.length(); j++) {
JSONObject jo = ja.getJSONObject(j);
SearchResultModel ch = new SearchResultModel();
ch.setSearch_Name(jo.getString("productName"));
ch.setSearch_Img(jo.getString("productImage"));
ch.setSearch_ImgLoc(jo.getString("productImageLoc"));
ch.setSearch_Price(jo.getString("productSP"));
ch.setSearch_RatingImg(jo.getString("pRatingImgName"));
ch.setSearch_RatingImgPath(jo.getString("pRatingImgPath"));
JSONArray txtdetail=jo.getJSONArray("productOfferText");
System.out.println("txtdetailarray"+txtdetail);
StringBuilder sb = new StringBuilder();
for(int k=0;k<txtdetail.length();k++)
{
JSONObject jdetail=txtdetail.getJSONObject(k);
disptext=jdetail.getString("displayText");
dispclr=jdetail.getString("displayColor");
ch_list.add(disptext);
color_list.add(dispclr);
sb.append(disptext);
System.out.println("clr" + color_list.get(k).toString());
colors=color_list.get(k);
String string = colors;
String[] parts = string.split("\\*");
int part1 = Integer.parseInt(parts[0]);
int part2 = Integer.parseInt(parts[1]);
int part3 = Integer.parseInt(parts[2]);
hex = String.format("#%02X%02X%02X", part1, part2, part3);
System.out.println("hexa"+hex);
// System.out.println("textnames" + ch_list.get(k).toString());
}
detailtext=sb.toString().replaceAll("\\\\n", "\n");
// System.out.println("gh"+sb.toString()+detailtext);
System.out.println("Output: " + sb.toString().replaceAll("\\\\n", "\n"));
searchlist.add(ch);
}
}
Adapter
public class CustomListAdapterCountry extends BaseAdapter {
private AQuery aQuery;
private Activity activity;
private LayoutInflater inflater;
private List<SearchResultModel> movieItems;
private List<String> DispItems;
ImageLoader imageLoader = MyApplication.getInstance().getImageLoader();
public CustomListAdapterCountry(Activity activity, List<SearchResultModel> movieItems,ArrayList<String> DispItems) {
this.activity = activity;
this.movieItems = movieItems;
this.DispItems = DispItems;
aQuery = new AQuery(this.activity);
}
#Override
public int getCount() {
return movieItems.size();
}
#Override
public Object getItem(int location) {
return movieItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_item_searchresult, null);
if (imageLoader == null)
imageLoader = MyApplication.getInstance().getImageLoader();
NetworkImageView iv = (NetworkImageView) convertView
.findViewById(R.id.search_image);
ImageView ratingiv = (ImageView) convertView
.findViewById(R.id.search_rating);
TextView title = (TextView) convertView.findViewById(R.id.search_title);
TextView price = (TextView) convertView.findViewById(R.id.search_price);
TextView dettext = (TextView) convertView.findViewById(R.id.search_detailtext);
// getting movie data for the row
SearchResultModel m = movieItems.get(position);
iv.setImageUrl(m.getSearch_ImgLoc() + m.getSearch_Img(), imageLoader);
aQuery.id(ratingiv).image(m.getSearch_RatingImgPath() + m.getSearch_RatingImg(), true, true, 0, R.mipmap.ic_launcher);
//Log.d("searchimgs", joined);
// title
title.setText(m.getSearch_Name());
price.setText("$"+m.getSearch_Price());
dettext.setText(detailtext);
dettext.setTextColor(Color.parseColor(hex));
return convertView;
}
}
You can try the following method. Format your text as HTML and use it for the display.
private String addColor(String str, String hexColor)
{
String html = "";
if(str.contains("\\\\n"))
{
html = "</br>";
str.replaceAll("\\\\n", "");
}
html = html + "<font color='"+hexColor+"'>"+str+"</font>";
return html;
}
Delete sb.append(disptext); from where it is right now and add sb.append(addColor(disptext, hex)); after hex = String.format("#%02X%02X%02X", part1, part2, part3);
Replace dettext.setText(detailtext); with dettext.setText(Html.fromHtml(detailtext)); and delete dettext.setTextColor(Color.parseColor(hex));.
This should do the job.
Also, you are not using your ArrayLists ch_list and color_list which can also be used for this task.
To change color of prticular words in textview and not change the whole color you will have to use
String noColor = "I like the ";
String redColor = "<font color='#EE0000'>color red</font>";
yourTextView.setText(Html.fromHtml(noColor + redColor));
Just use this and change to your needs. Split your string into smaller strings and appy color to each as need then merge them using Html.fromHtml
i am using volley library for web api call and retrieving json data using for loop and setting that data on custom listview but listview only show two values of that data like if my loop run for 4 times only 2 or 4 numbered value is shown on listview .
Below is my code for fetching values from json data.
details=new ArrayList();
depart_adapter = new Result_dep_adapter(Result.this, android.R.layout.simple_list_item_2, details);
return_adapter = new Result_ret_adapter(Result.this, android.R.layout.simple_list_item_2, details);
departlist.setAdapter(depart_adapter);
returnlist.setAdapter(return_adapter);
try {
for (int k = 0; k < response.length(); k++) {
custom_result=new Custom_Result();
Log.i("response",","+ response.length());
JSONObject obj = response.getJSONObject(k);
JSONObject flight = obj.getJSONObject("Flights");
JSONArray array = flight.getJSONArray("Segments");
for (int i = 0; i < array.length(); i++) {
JSONObject depart = (JSONObject) array.get(i);
String departdate_time = depart.getString("DepartureTime");
String arrivedate_time = depart.getString("ArrivalTime");
Boolean returnflight=depart.getBoolean("IsReturnFlight");
duration=depart.getString("FlightDuration");
Log.i("segments",","+returnflight);
JSONObject Airline=depart.getJSONObject("Airline");
String Airline_code=Airline.getString("Name");
JSONObject Airlinename=depart.getJSONObject("MarketingCarrier");
String name=Airlinename.getString("Name");
Log.i("Airline code", Airline_code);
String[] departtime = departdate_time.split("T");
String[] arrivetime = arrivedate_time.split("T");
if (!returnflight) {
String ddate = departtime[0];
String dtime = departtime[1].substring(0, 5);
Log.i("time", dtime);
String duration = depart.getString("FlightDuration");
String Adate = arrivetime[0];
String Atime = arrivetime[1].substring(0, 5);
custom_result.setDepart_date(ddate);
custom_result.setDepart_time(dtime);
custom_result.setArrive_date(Adate);
custom_result.setArrive_time(Atime);
custom_result.setDep_duration(duration);
custom_result.setDep_Airline_name(name);
custom_result.setDep_Airline_code(Airline_code);
}else{
String Rdate = departtime[0];
String Rtime = departtime[1].substring(0, 5);//return depart time
Log.i("time", Rtime);
String return_duration = depart.getString("FlightDuration");
String ARdate = arrivetime[0];
String ARtime = arrivetime[1].substring(0, 5);
custom_result.setRet_arr_date(ARdate);
custom_result.setRet_arr_time(ARtime);
custom_result.setRet_dep_date(Rdate);
custom_result.setRet_dep_time(Rtime);
custom_result.setRet_duration(return_duration);
custom_result.setRet_Airline_name(name);
custom_result.setRet_Airline_code(Airline_code);
}
}
String stops = flight.getString("Stops");
JSONObject Fare = flight.getJSONObject("Fare");
String published_fare = Fare.getString("PublishedFare");
custom_result.setStops(stops);
custom_result.setPrice(published_fare);
details.add(custom_result);
}
I am new to android please help me ..
Thank you
This my adpater code
private class ViewHolder
{
ImageView Airline_logo;
TextView Airline_code,dep_time,dep_arr_time,dep_stops,dep_duration,
dep_price;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder=null;
// custom_result=Custom_Result.getCustom_result();
custom_result=getItem(position);
LayoutInflater inflater=(LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if(convertView==null)
{
convertView=inflater.inflate(R.layout.result_listview,null);
holder=new ViewHolder();
holder. Airline_logo=(ImageView) convertView.findViewById(R.id.dep_airlines_image);
holder.Airline_code=(TextView) convertView.findViewById(R.id.dep_airline_code);
holder.dep_time=(TextView) convertView.findViewById(R.id.dep_depart_time);
holder.dep_arr_time=(TextView) convertView.findViewById(R.id.dep_arrive_time);
holder.dep_stops=(TextView) convertView.findViewById(R.id.dep_stops_info);
holder.dep_duration=(TextView) convertView.findViewById(R.id.dep_duration);
holder.dep_price=(TextView) convertView.findViewById(R.id.dep_airline_price);
convertView.setTag(holder);
}else
{
holder=(ViewHolder)convertView.getTag();
}
String imagename=custom_result.getDep_Airline_code().toLowerCase();
String path="drawable/"+imagename;
// String logo=path.toLowerCase();
// String PACKAGE_name=getContext().getPackageName();
int imageresource=context.getResources().getIdentifier(path, null, context.getPackageName());
if(imageresource==0)
{
imageresource=R.drawable.flight_icon;
}
Drawable image=context.getResources().getDrawable(imageresource);
// holder. Airline_logo.setImageBitmap(BitmapFactory.decodeResource(getContext().getResources(),image));
holder.Airline_logo.setImageDrawable(image);
holder.Airline_code.setText(custom_result.getDep_Airline_name());
holder.dep_time.setText(custom_result.getDepart_time());
holder.dep_arr_time.setText(custom_result.getArrive_time());
holder.dep_stops.setText(custom_result.getStops());
holder.dep_duration.setText(custom_result.getDep_duration());
holder.dep_price.setText(custom_result.getPrice());
return convertView;
}
You are using android.R.layout.simple_list_item_2 as the layout for the row.
That layout only has 2 textviews so it cant show more than 2 values.
If you need to show more things you need to create your custom adapter from the BaseAdapter Class.
Then in the getView() method you can draw the row with anything you need.
Hope this helps.
I'm working on a chat app. I want to create a cool design for my listview. My code is working but I want to add some design similar to the design of Facebook, but I have a problem.
I can't do this: i.e one user has an ID=52 and the other has=5293. If the user has Id=52, the textarea gravity in the left and the other in the right, and here my code it doesn't see my if statement every time print the else statement I don't know why really I put my ID in an array but really this is the same result.
public void LoadMessage() {
// TODO Auto-generated method stub
DatabseHandler d = new DatabseHandler(EchangingMessage.this);
String me = d.getData();
TextView you_id = (TextView) findViewById(R.id.you_id);
String you = you_id.getText().toString().trim();
Log.i("ID :", me + " : " + you);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("me", me));
params.add(new BasicNameValuePair("you", you));
JSONObject json = jParser.makeHttpRequest(url_daftar_rs, "POST",
params);
try {
int success = json.getInt(TAG_SUCCESS);
Log.i("success :", "" + success);
if (success == 1) {
daftar_rs = json.getJSONArray(TAG_DAFTAR_RS);
for (int i = 0; i < daftar_rs.length(); i++) {
JSONObject c = daftar_rs.getJSONObject(i);
String id_rs = c.getString(TAG_ID_RS);
String nama_rs = c.getString(TAG_NAMA_RS);
String link_image_rs = "http://10.0.2.2/www/Android_Login_Secure/Images/upload/big/"
+ c.getString(TAG_LINK_IMAGE_RS);
String message_rs = c.getString(TAG_MESSAGE_RS);
String time_rs = c.getString(TAG_TIME_RS);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID_RS, id_rs);
map.put(TAG_NAMA_RS, nama_rs);
map.put(TAG_LINK_IMAGE_RS, link_image_rs);
map.put(TAG_MESSAGE_RS, message_rs);
map.put(TAG_TIME_RS, time_rs);
DaftarRS.add(map);
}
} else {
finish();
}
} catch (Exception e) {
Log.e("Error", "COnnection:" + e.toString());
}
runOnUiThread(new Runnable() {
public void run() {
// updating listview
SetListViewAdapter(DaftarRS);
}
});
}
public class ListAdapterSendMessage extends BaseAdapter {
public String POST_TEXT;
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
public ImageLoader imageLoader;
public final static String you_id = null;
int count = 0;
public ListAdapterSendMessage(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() {
// TODO Auto-generated method stub
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.item_list_send, null);
}
HashMap<String, String> daftar_rs = new HashMap<String, String>();
daftar_rs = data.get(position);
String me = daftar_rs.get(MyMessages.TAG_LINK_IMAGE_RS);
if (me == "52") {
vi = inflater.inflate(R.layout.list_row_even, null);
TextView name_rs = (TextView) vi.findViewById(R.id.senderMessage);
TextView Des_rs = (TextView) vi.findViewById(R.id.message);
ImageView thumb_image = (ImageView) vi
.findViewById(R.id.imageSender);
TextView Time_rs = (TextView) vi.findViewById(R.id.senderTime);
name_rs.setText(daftar_rs.get(MyMessages.TAG_NAMA_RS));
// link_image_rs.setText(daftar_rs.get(MainActivity.TAG_LINK_IMAGE_RS));
// alamat_rs.setText(daftar_rs.get(MainActivity.TAG_ALAMAT_RS));
Des_rs.setText(daftar_rs.get(MyMessages.TAG_MESSAGE_RS));
Time_rs.setText(daftar_rs.get(MyMessages.TAG_TIME_RS));
imageLoader.DisplayImage(
daftar_rs.get(MyMessages.TAG_LINK_IMAGE_RS), thumb_image);
} else {
vi = inflater.inflate(R.layout.list_row_odd, null);
TextView name_rs = (TextView) vi.findViewById(R.id.senderMessage);
TextView Des_rs = (TextView) vi.findViewById(R.id.message);
ImageView thumb_image = (ImageView) vi
.findViewById(R.id.imageSender);
TextView Time_rs = (TextView) vi.findViewById(R.id.senderTime);
name_rs.setText(daftar_rs.get(MyMessages.TAG_NAMA_RS));
// link_image_rs.setText(daftar_rs.get(MainActivity.TAG_LINK_IMAGE_RS));
// alamat_rs.setText(daftar_rs.get(MainActivity.TAG_ALAMAT_RS));
Des_rs.setText(daftar_rs.get(MyMessages.TAG_MESSAGE_RS));
Time_rs.setText(daftar_rs.get(MyMessages.TAG_TIME_RS));
imageLoader.DisplayImage(
daftar_rs.get(MyMessages.TAG_LINK_IMAGE_RS), thumb_image);
}
return vi;
}
}
for this question we assume that my id =1 and you id =2
if (id==1) {
inflater.inflate(R.layout.item_list_right, parent, false);
else
{
inflater.inflate(R.layout.item_list_left, parent, false);
}
here you have to different layout one of them item_list_right and the other one is item_list_left
I solved this problem like this
I want to the change the text of the button which was clicked in a getView function. The text is changed but when the view is scrolled the text of other buttons which the same id is also changed. I don't want that. I want only the text of the button which was clicked to be changed.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final int i=position;
List dialog = DialogList.get(i);
final Object memid = dialog.get(2).toString();
final String dialogid = dialog.get(3).toString();
final String dialogtype = dialog.get(4).toString();
ImageView imageViews;
if (convertView == null) {
LayoutInflater layoutInflator = LayoutInflater.from(getContext());
convertView = layoutInflator.inflate(R.layout.invite_friends_list, null);
holder = new ViewHolder();
holder.friendsname = (TextView) convertView.findViewById(R.id.friendsname);
holder.profimage = (ImageView) convertView.findViewById(R.id.member_image);
holder.assign = (Button) convertView.findViewById(R.id.btnInvite);
convertView.setTag(holder);
}
holder = (ViewHolder) convertView.getTag();
holder.friendsname.setText(user_name);
holder.assign.setTag(holder);
holder.assign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("assigntext", holder.assign.getText().toString());
SharedPreferences prfs = _context.getSharedPreferences("MyPref",
Context.MODE_PRIVATE);
String token = prfs.getString("apptoken", "");
String url = null;
if(dialogtype.equals("V"))
{
url = "http://www.jjhjjkh.com/index.php?/alkjlkjlk/dialog/invjlkjlkjklialogmember?apptoken="
+ token + "&dialogid=" + dialogid+"&mid="+memid.toString();
}
if(dialogtype.equals("P"))
{
url = "http://www.ckjhuihiuhiu.com/index.php?/kjij/dialog/inviuhuihuihuimember?apptoken="
+ token + "&dialogid=" + dialogid+"&mid="+memid.toString();
}
List<String> urlList = new ArrayList<String>();
Log.d("cat",url.toString());
// JSON Node names
String TAG_DETAILS = "invitemembers";
String TAG_MSG = "msg";
// contacts JSONArray
JSONArray dialogpublish = null;
JSONArray dialogs = null;
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
// Log.d("cat",json.toString());
try {
dialogpublish = json.getJSONArray(TAG_DETAILS);
// Log.d("apptoken",login.toString());
for (int i = 0; i < dialogpublish.length(); i++) {
JSONObject d = dialogpublish.getJSONObject(i);
String msg = d.getString(TAG_MSG);
//dialogs = d.getJSONArray("updatedialog");
if (msg.equals("success")) {
// ViewHolder mH = (ViewHolder)view.getTag();
//Integer currentPos = view.getTag();
String mem_id= view.getTag().toString();
if(mem_id.equals(memid))
{
Toast.makeText(_context, "Member invited Succesfully",Toast.LENGTH_LONG).show();
ViewHolder mH = (ViewHolder)view.getTag();
mH.assign.setText("Invited");
}
//view.setText("Invited");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I guess that is happenning because you are using the viewholder pattern. The viewholder pattern tends to cache views for performance optimization. try to write the adapter without using viewholder. If the list view items arent large in numbers.
Create a new HashMap in Adapter :
private HashMap<Integer, String> buttonTitleMap=new HashMap<Integer, String>();
Create a function getButtonTitle as below in Adapter :
private String getButtonTitle(int position){
if(buttonTitleMap.containsKey(position)){
return buttonTitleMap.get(position);
}else{
return "Your Normal Button text";
}
}
Then in getView() of Adapter, befor returning convertView, call :
....
holder.assign.setText(getButtonTitle(position));
holder.friendsname.setTag(position);
return convertView;
}
When the Button is clicked, you can get the list item position of the button. So what you need to do is to change the button title as you do before and also update the hashmap with the same value :
holder.assign.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
....
mH.assign.setText("Invited");
int position = (int)mH.friendsname.getTag();
buttonTitleMap.put(position,"Invited");
....
}
}
You are done.
Try
String mem_id= view.getTag().toString();
if(mem_id.equals(memid))
{
Toast.makeText(_context, "Member invited Succesfully",Toast.LENGTH_LONG).show();
((Button)view).setText("Invited");
}