JSONArray Parsing and Value Mapping with Same Field Names in Android - android

I have a JSONArray which I am able to parse, but due to the structure of the array, I am having difficulties mapping the values extracted from fields with the same names. Instead of the for loop assigning values one after the other, the assignment looks at the last instance of the field name. So the values from the second JSONObject are assigned twice.
"Group": [
{
"-Type": "Mouldings",
"CurTier": "BRZ",
"NxtTier": "SIL",
"CurTierFrom": "$4,000",
"CurTierTo": "$9,999",
"NxtTierFrom": "$10,000",
"NxtTierTo": "$14,999",
"CurSales": "$2,107",
"ReqSales": "$7,893"
},
{
"-Type": "Accessories",
"CurTier": "BAS",
"NxtTier": "GLD",
"CurTierFrom": "$0",
"CurTierTo": "$1,499",
"NxtTierFrom": "$1,500",
"NxtTierTo": "$4,999",
"CurSales": "$693",
"ReqSales": "$807"
}
]
Code:
try {
JSONObject reader = new JSONObject(JSON_DATA);
JSONObject PricingTier = reader.getJSONObject("PricingTier");
JSONArray Group = PricingTier.getJSONArray("Group");
for (int i = 0; i < Group.length(); i++) {
JSONObject g = Group.getJSONObject(i);
final String Type = g.getString("#Type");
final String CurTier = g.getString("CurTier");
final String NxtTier = g.getString("NxtTier");
final String CurTierFrom = g.getString("CurTierFrom");
final String CurTierTo = g.getString("CurTierTo");
final String NxtTierFrom = g.getString("NxtTierFrom");
final String NxtTierTo = g.getString("NxtTierTo");
final String CurSales = g.getString("CurSales");
final String ReqSales = g.getString("ReqSales");
final String TypeA = g.getString("#Type");
final String CurTierA = g.getString("CurTier");
final String NxtTierA = g.getString("NxtTier");
final String CurTierFromA = g.getString("CurTierFrom");
final String CurTierToA = g.getString("CurTierTo");
final String NxtTierFromA = g.getString("NxtTierFrom");
final String NxtTierToA = g.getString("NxtTierTo");
final String CurSalesA = g.getString("CurSales");
final String ReqSalesA = g.getString("ReqSales");
fragment.getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
tvType.setText(Type);
tvCurTier.setText(CurTier);
tvNxtTier.setText(NxtTier);
tvCurTierFrom.setText(CurTierFrom);
tvCurTierTo.setText(CurTierTo);
tvNxtTierFrom.setText(NxtTierFrom);
tvNxtTierTo.setText(NxtTierTo);
tvCurSales.setText(CurSales);
tvReqSales.setText(ReqSales);
tvTypeA.setText(TypeA);
tvCurTierA.setText(CurTierA);
tvNxtTierA.setText(NxtTierA);
tvCurTierFromA.setText(CurTierFromA);
tvCurTierToA.setText(CurTierToA);
tvNxtTierFromA.setText(NxtTierFromA);
tvNxtTierToA.setText(NxtTierToA);
tvCurSalesA.setText(CurSalesA);
tvReqSalesA.setText(ReqSalesA);
}
});
}
Result:
"-Type": "Accessories",
"CurTier": "BAS",
"NxtTier": "GLD",
"CurTierFrom": "$0",
"CurTierTo": "$1,499",
"NxtTierFrom": "$1,500",
"NxtTierTo": "$4,999",
"CurSales": "$693",
"ReqSales": "$807"
"-Type": "Accessories",
"CurTier": "BAS",
"NxtTier": "GLD",
"CurTierFrom": "$0",
"CurTierTo": "$1,499",
"NxtTierFrom": "$1,500",
"NxtTierTo": "$4,999",
"CurSales": "$693",
"ReqSales": "$807"

You're getting array(i = 0) and writing in all the 18 variables then taking the value 1 and overwriting this same 18 variables.
You have to separate this variables from same for looping. for example: when Group.getObj(i = 0).
final String Type = g.getString("#Type");
and then when Group.getObj(i = 1):
final String TypeA = g.getString("#Type");

Create a class with getter and setter for your JSONArray Keys.
Use a for loop to read the Values, Refer the code.
for (int i = 0; i < Group.length(); i++) {
JSONObject g = Group.getJSONObject(i);
Actors actors = new Actors();
actors.setType(g.getString("#Type"));
......//your remaining code
arrayList.add(actors);
}
}
Actors is the class name.
Use an adapter class to show the list in ListView.
public class yourAdapter extends ArrayAdapter<Actors> {
LayoutInflater vi;
ViewHolder holder;
int resource;
private final Activity context;
private final ArrayList<Actors> details;
public WifiAdapter(Activity context, int resource , ArrayList<Actors> details) {
super(context, resource, details);
vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.context = context;
this.resource = resource;
this.details = details;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null){
holder = new ViewHolder();
v = vi.inflate(resource, null);
holder.Type = (TextView) v.findViewById(R.id.type);
.......//your remaining code
v.setTag(holder);
}
else {
holder =(ViewHolder) v.getTag();
}
holder.Name.setText(details.get(position).getType());
..........//ur remaining code
return v;
}
static class ViewHolder {
public TextView Type;
//your remaing code
}
}

Related

How to set color code as per Json Object

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

custom Listview data is overriding while fetching json data setting on adapter

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.

How to add two textViews to custom adapter?

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

Android Custom ArrayAdapter does not take an array

I correctly fill an array? NewsData_data cannot be resolved to a variable.
NewsData NewsData_data[] = new NewsData[]
{
new NewsData(header[i], short_text[i], team[i], datatime[i], photo_url[i])
};
Problem in:
NewsDataAdapter adapter = new NewsDataAdapter(this,
R.layout.news_details, NewsData_data);
NewsData_data cannot be resolved to a variable. How to fix this error?
public void ListDrwaer() {
String[] header;
String[] short_text;
String[] team;
String[] datatime;
String[] photo_url;
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("news");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
header[i] = jsonChildNode.optString("header");
short_text[i] = jsonChildNode.optString("short_text");
team[i] = jsonChildNode.optString("team");
datatime[i] = jsonChildNode.optString("datatime");
photo_url[i] = jsonChildNode.optString("photo_url");
NewsData NewsData_data[] = new NewsData[]
{
new NewsData(header[i], short_text[i], team[i], datatime[i], photo_url[i])
};
}
} catch (JSONException e) {
Toast.makeText(getActivity(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
NewsDataAdapter adapter = new NewsDataAdapter(this,
R.layout.news_details, NewsData_data);
View header1 = getActivity().getLayoutInflater().inflate(R.layout.news_details, null);
listView.addHeaderView(header1);
listView.setAdapter(adapter);
}
public class NewsData {
public String header;
public String short_text;
public String team;
public String datatime;
public String photo_url;
public NewsData(){
super();
}
public NewsData(String header,
String short_text,
String team,
String datatime,
String photo_url) {
super();
this.header = header;
this.short_text = short_text;
this.team = team;
this.datatime = datatime;
this.photo_url = photo_url;
}
}
public class NewsDataAdapter extends ArrayAdapter<NewsData>{
Context context;
int layoutResourceId;
NewsData data[] = null;
public NewsDataAdapter(Context context, int layoutResourceId, NewsData[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
NewsDataHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new NewsDataHolder();
holder.img_news = (ImageView)row.findViewById(R.id.img_news);
holder.header = (TextView)row.findViewById(R.id.header);
holder.short_text = (TextView)row.findViewById(R.id.short_text);
holder.team = (TextView)row.findViewById(R.id.team);
holder.datatime = (TextView)row.findViewById(R.id.datatime);
row.setTag(holder);
}
else
{
holder = (NewsDataHolder)row.getTag();
}
NewsData NewsData = data[position];
Picasso.with(context).load(NewsData.photo_url).into(holder.img_news);
holder.header.setText(NewsData.header);
holder.short_text.setText(NewsData.short_text);
holder.team.setText(NewsData.team);
holder.datatime.setText(NewsData.datatime);
return row;
}
class NewsDataHolder
{
ImageView img_news;
TextView header;
TextView short_text;
TextView team;
TextView datatime;
}
}
Problem in:
NewsDataAdapter adapter = new NewsDataAdapter(this,
R.layout.news_details, NewsData_data);
NewsData_data cannot be resolved to a variable
You need to declare your array outside of the try block so that it is visible to the ArrayAdapter constructor.
As corsair922 mentioned, you'll want to declare your NewsData_data array outside your try catch block, otherwise you won't have access to it from outside the block. Additionally, you want to initialize your array once, and populate the array elements as you go as opposed to reinitializing your array each time:
Edit, I would also recommend you spend some time getting familiar with the Java coding conventions. They will make your code easier to maintain/tidier and will allow other people to better understand your code (http://www.oracle.com/technetwork/java/codeconv-138413.html).
public void ListDrwaer() {
String[] header;
String[] short_text;
String[] team;
String[] datatime;
String[] photo_url;
NewsData NewsData_data[];
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("news");
NewsData_data = new NewsData[jsonMainNode.length()];
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
header[i] = jsonChildNode.optString("header");
short_text[i] = jsonChildNode.optString("short_text");
team[i] = jsonChildNode.optString("team");
datatime[i] = jsonChildNode.optString("datatime");
photo_url[i] = jsonChildNode.optString("photo_url");
NewsData_data[i] = new NewsData(header[i], short_text[i], team[i], datatime[i], photo_url[i]);
}
} catch (JSONException e) {
Toast.makeText(getActivity(), "Error" + e.toString(), Toast.LENGTH_SHORT).show();
}
NewsDataAdapter adapter = new NewsDataAdapter(this, R.layout.news_details, NewsData_data);
View header1 = getActivity().getLayoutInflater().inflate(R.layout.news_details, null);
listView.addHeaderView(header1);
listView.setAdapter(adapter);
}

change the text of the button which was clicked in a getView function android

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

Categories

Resources