how to maintain array list for new added element? - android

Hello every one i am working on app which is similar to the facebook.In that currently i am stuck in one point like we have posts in facebook which shows on our wall in that all the post is shows in bulk like 20 20 fashion that same thing i want to apply in my app. For that thing i use listview which get value form server and create view according to that i also get all value but the problem is that when i add 1st 20 value then it work fine but when i add another 20 value it will delete the previous data in listview.
any idea how i can do this thing in my app and thanks in advance....
my function get value from the server
private void getPostnew(String start) {
String URL = start;
System.out.println("start value new :" + start);
final String usernamefor = "";
aq = new AQuery(getParent());
listitem = new ArrayList<BeanTop>();
aq.ajax(URL, JSONObject.class, 10 * 1000,
new AjaxCallback<JSONObject>() {
#Override
public void callback(String url, JSONObject json1,
AjaxStatus status) {
System.out.println("json " + json1);
if (json1 == null) {
} else {
try {
JSONArray jarray = json1
.getJSONArray("subject");
for (int j = 0; j < jarray.length(); j++) {
try {
JSONObject j1 = jarray.getJSONObject(j);
try {
listcount = j1
.getString("likecount");
} catch (Exception e) {
listcount = "0";
}
AddObject(j1.getString("text"),
j1.getString("leftpic"),
j1.getString("rightpic"),
j1.getString("rightvotecount"),
j1.getString("leftvotecount"),
j1.getString("textleft"),
j1.getString("textright"),
j1.getString("date_created"),
j1.getString("voteid"),
j1.getString("user"),
j1.getString("dom"),
j1.getString("Isvoted"),
j1.getString("Islike"),
j1.getString("profilepic"),
listcount,
j1.getString("commentcount"));
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
FriendlistAdapter ad = new FriendlistAdapter(Top.this,
listitem);
subjectlist.setAdapter(ad);
ad.notifyDataSetChanged();
}
});
}
method for save the data in bean class
private void AddObject(String string1, String string2, String string3,
String string5, String string6, String string7, String string8,
String string9, String string10, String string11,
String usernamefor, String isvoted, String isliked,
String profilepic, String likecount, String commentcount) {
BeanTop ib = new BeanTop();
Date date = null;
try {
System.out.println("date " + string9);
date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(string9);
} catch (Exception e) {
e.printStackTrace();
}
ib.setText(string1);
ib.setLeftpic(string2);
ib.setRightpic(string3);
ib.setRightVote(string5);
ib.setLeftVote(string6);
ib.setLefttext(string7);
ib.setRighttext(string8);
ib.setDate(string9);
ib.setDate1(date);
ib.setVoteid(string10);
ib.setUsername(string11);
ib.setDom(usernamefor);
ib.setIsvoted(isvoted);
ib.setIsliked(isliked);
ib.setProfilepic(profilepic);
ib.setLikecount(likecount);
ib.setCommentcount(commentcount);
List<BeanTop> bookingList = new ArrayList<BeanTop>();
bookingList.addAll(listitem);
Collections.sort(bookingList, new Comparator<BeanTop>() {
public int compare(BeanTop m1, BeanTop m2) {
return m1.getDate().compareTo(m2.getDate());
}
});
Collections.reverse(bookingList);
try {
listitem.clear();
} catch (Exception e) {
e.printStackTrace();
}
listitem.addAll(bookingList);
try {
bookingList.clear();
} catch (Exception e) {
e.printStackTrace();
}
listitem.add(ib);
}

Cant say without seeing your code, but I can show you general way of doing this...
First you should maintain a list, say at class level like...
List<MyPost> posts = ArrayList<MyPost>();
Then you can create you adapter by passing 'posts' list in it.
And just call '.addAll(xxx)' to you 'posts' list everytime you get items from server like,
posts.addAll(newItems);
and right after that, call yourAdapter.notifyDatasetChanged(); so that list can redraw/update its views...
And in you code...use,
if (listitem == null) {
listitem = new ArrayList<BeanTop>();
}
in you getPostnew() instead of only listitem = new ArrayList<BeanTop>();.
Hope this helps...

You are re-initializing listitem = new ArrayList<BeanTop>(); eveytime the getPostnew methood is called. This is why your old posts are lost. Try change that line to:
if (listitem == null) {
listitem = new ArrayList<BeanTop>();
}

you should use a global variable to store the data which you get from server ,in your method
getPostnew(String start) every time you execute it ,the listitem will be recreated;so the last data will be lost.

Related

black screen while parsing local JSON file android

I'm trying to parse a Large JSON file that contains 24,000 lines(it contains regular Expressions to detect sms from sms provider) , the file is locally stored in assets folder here's the code of my class
public class SmsActivity extends AppCompatActivity {
ListView lv;
ArrayList<String> msg;
ArrayAdapter<String> adapter;
JSONObject obj;
JSONArray rules_array;
JSONObject rule_object = null;
String body, address, smsDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sms);
lv = (ListView) findViewById(R.id.list);
permission();
}
void permission() {
// first check for permissions
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_SMS},
10);
} else {
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, Inbox());
lv.setAdapter(adapter);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[], #NonNull int[] grantResults) {
switch (requestCode) {
case 10: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, Inbox());
lv.setAdapter(adapter);
Toast.makeText(this, "Permission is granted",
Toast.LENGTH_SHORT).show();
} else {//If permission is not granted,then it will ask for permission .
permission();
}
}
}
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("sms_formats.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
//Arraylist is used to create dynamic array.The size can be varried .
public ArrayList<String> Inbox() {
msg = new ArrayList<>();
try {
//A Uri object is usually used to tell a ContentProvider what we want to access by reference.In this ,we are accessing inbox.
Uri uri = Uri.parse("content://sms/inbox");
//ContentResolver is used to request the content.
//cursor object gets the data.
Cursor cursor = getContentResolver().query(uri, new String[]{"_id", "address", "date", "body"}, null, null, null);
obj = new JSONObject(loadJSONFromAsset());
if (!obj.isNull("rules")) {
rules_array = obj.getJSONArray("rules");
//It checks whether there is any messages in inbox.If there is no message then the following if statement will not be executed.
if (cursor != null) {
while (cursor.moveToNext()) {
address = cursor.getString(1);
body = cursor.getString(3);
String date = cursor.getString(cursor.getColumnIndex("date"));
Long timestamp = Long.parseLong(date);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timestamp);
Date finaldate = calendar.getTime();
smsDate = finaldate.toString();
for (int i = 0; i < rules_array.length(); i++) {
rule_object = rules_array.getJSONObject(i);
if (!rule_object.isNull("name")) {
// you have a name for the rule
Log.e("NO", "error");
}
if (!rule_object.isNull("patterns")) {
JSONArray pattern_array = rule_object.getJSONArray("patterns");
for (int j = 0; j < pattern_array.length(); j++) {
JSONObject pattern_obj = pattern_array.getJSONObject(j);
if (!pattern_obj.isNull("regex")) {
String type = pattern_obj.getString("sms_type");
if (type.equals("transaction")) {
String regex = pattern_obj.getString("regex");
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(body);
if (matcher.find()) {
msg.add("\nSender=>" + address + "\n" + "Message=>" + body + "\n" + "Date and Time=>" + smsDate + "\n");
}
}
}
}
}
}
}
cursor.close();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return msg;
}
}
The problem here is when i use Android studio debugger i can see that all JSON objects and JSONArrays have the values they are supposed to have.But when i run the app on the phone it gives me black screen with no output.
I tried to implement AsyncTask cause I thought the black screen was due the large amount of data it was processing on the main thread from the JSON file, but it didn't help either. Can Someone please point me in the right direction.
Ps-I'm a beginner in Android Development
edit added AsyncTask.
public class LoadData extends AsyncTask<String, Void, JSONObject> {
String bodyData;
#Override
protected JSONObject doInBackground(String... body) {
bodyData = body.toString();
if (!obj.isNull("rules")) {
try {
rules_array = obj.getJSONArray("rules");
for (int i = 0; i < rules_array.length(); i++) {
rule_object = rules_array.getJSONObject(i);
if (!rule_object.isNull("name")) {
// you have a name for the rule
Log.e("NO", "error");
}
if (!rule_object.isNull("patterns")) {
JSONArray pattern_array = rule_object.getJSONArray("patterns");
for (int j = 0; j < pattern_array.length(); j++) {
JSONObject pattern_obj = pattern_array.getJSONObject(j);
if (!pattern_obj.isNull("regex")) {
return pattern_obj;
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(JSONObject pattern_obj) {
super.onPostExecute(pattern_obj);
String type = null;
try {
type = pattern_obj.getString("sms_type");
if (type.equals("transaction")) {
String regex = pattern_obj.getString("regex");
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(bodyData);
if (matcher.find()) {
msg.add("\nSender=>" + address + "\n" + "Message=>" + body + "\n" + "Date and Time=>" + smsDate + "\n");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Parsing a large JSON file that contains 24,000 lines is complex work. Using AsynTask to perform that stuff in worker thread, then publish result in UI thread
When your app performs intensive work in response to user interaction, this single thread model can yield poor performance unless you implement your application properly. Specifically, if everything is happening in the UI thread, performing long operations such as network access or database queries will block the whole UI. When the thread is blocked, no events can be dispatched, including drawing events. From the user's perspective, the application appears to hang. Even worse, if the UI thread is blocked for more than a few seconds (about 5 seconds currently) the user is presented with the infamous "application not responding" (ANR) dialog. The user might then decide to quit your application and uninstall it if they are unhappy.
This stuff below could be done in worker thread, so you don't have to put it into onPostExecute() which runs on UI thread (That's the reason your UI had been blocking)
String type = null;
try {
type = pattern_obj.getString("sms_type");
if (type.equals("transaction")) {
String regex = pattern_obj.getString("regex");
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(bodyData);
if (matcher.find()) {
msg.add("\nSender=>" + address + "\n" + "Message=>" + body + "\n" + "Date and Time=>" + smsDate + "\n");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
So it could be something like this
public class LoadData extends AsyncTask<String, Void, JSONObject> {
#Override
protected JSONObject doInBackground(String... body) {
// do your complex work
// This run on Worker Thread
return aJsonObject;
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
// Doing anything with your view
// This run on UI Thread
}
}

json listview delete not working android studio

I am loading some json into a list view and want to delete items from the list on click and for the item to be deleted from the json. The delete functionality seems to be working. The method delete is called, the items are removed on click and debugging shows the item being removed. However after going to another activity and viewing the list again, the deleted items come back. what am i doing wrong? This is my class:
public class edit extends AppCompatActivity
{
public ListView pizzaList;
ListView addicList;
ArrayAdapter<String> arrayAdapter;
String appreciations;
String currentPizza;
ArrayList<String> list = new ArrayList<String>();
private String name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_activity);
pizzaList = (ListView) findViewById(R.id.pizzas);
registerForContextMenu(pizzaList);
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
pizzaList.setAdapter(arrayAdapter);
pizzaList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
delete(view,position);
arrayAdapter.notifyDataSetChanged();
}
});
try {
FileManager fileManager = new FileManager();
String str = fileManager.ReadFile(this);
if (str != null) {
JSONArray jarray = new JSONArray(str);
String outputText = "";
for (int i = 0; i < jarray.length(); i++) {
JSONObject jsonObject = jarray.getJSONObject(i);
String pizzaName = jsonObject.getString("name");
int price = jsonObject.getInt("price");
outputText = outputText + " " + pizzaName + " " + " $" + price + "\n";
appreciations = outputText;
list.add(appreciations);
arrayAdapter.notifyDataSetChanged();
outputText = "";
}
} else {
Toast to = Toast.makeText(getApplicationContext(), "No saved Pizzas", Toast.LENGTH_LONG);
to.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void delete(View view, int pos)
{
try {
FileManager fileManager = new FileManager();
String str = fileManager.ReadFile(this);
if (str != null)
{
JSONArray jarray = new JSONArray(str);
JSONObject jsonObject = jarray.getJSONObject(pos);
jarray.remove(pos);
list.remove(pos);
arrayAdapter.notifyDataSetChanged();
JSONArray jsArray = new JSONArray(jarray);
arrayAdapter.notifyDataSetChanged();
} else {
Toast to = Toast.makeText(getApplicationContext(), "No saved Pizzas", Toast.LENGTH_LONG);
to.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
You would need to remove the item from the database, use asynchronous request such as volley or robospice for it. Then instead of making the request when coming back you would use the data stored on the cache the second time and only make the request again when data has been changed. You can create your cache logic in your application class to make it visible throughout your app.

Comparing 2 JSONObjects

My question was like this: https://stackoverflow.com/questions/20919343/php-getting-count-of-how-many-x-and-y-in-a-row-then-getting-other-data-of-x-and
But then i thought about doing the job from Android Part. So i have 2 JSONObjects which generated from php. First object has "value" and "total" arrays. Second one has "name", "surname" and "number" and a few more arrays. Now i need to compare number from second JSONObject and value from first. I tried some loops, but it creates double as expected. Here is my onPostExecute method:
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
pDialog.dismiss();
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject jsonObj2 = new JSONObject(jsonStr);
// Getting JSON Array node
sonuc = jsonObj.getJSONArray(TAG_BASLIK);
// looping through All Contacts
for (int i = 0; i < sonuc.length(); i++) {
JSONObject c = sonuc.getJSONObject(i);
AdayNumara = c.getString(TAG_OY);
ToplamOy = c.getString(TAG_TOPLAM);
Log.i("Aday Numaraları", AdayNumara);
Log.i("Oy Sayısı", ToplamOy);
pie.addItem(AdayNumara,Float.valueOf(ToplamOy), pRenk.get(i));
adaylar = jsonObj2.getJSONArray(TAG_ADAYLAR);
for(int j=0; j< adaylar.length(); j++){
JSONObject c2 = adaylar.getJSONObject(j);
String no = c2.getString(TAG_NO);
String ad = c2.getString(TAG_AD);
String soyad = c2.getString(TAG_SOYAD);
String resim = c2.getString(TAG_RESIM);
HashMap<String, String> aday = new HashMap<String, String>();
do{
aday.put(TAG_AD, ad);
aday.put(TAG_SOYAD, soyad);
aday.put(TAG_RESIM, resim);
aday.put(TAG_NO, no);
aday.put(TAG_TOPLAM, ToplamOy);
adayList.add(aday);} while(AdayNumara == no);
}
adapter=new LazyAdapter2(SecimSonuclari.this, adayList);
lv.setAdapter(adapter);
}
}catch (JSONException e) {
e.printStackTrace();
}
}
Code is probably has wrong approachs since I'm new to Android.
What I am getting now is for value in listview. There must be 2. The first two has same value like 1 and 1 on their number line. The second couple has the other number, lets say 2.
I found my problem. It appears to using "==" is wrong.
if(AdayNumara.equals(no)){
aday.put(TAG_AD, ad);
aday.put(TAG_SOYAD, soyad);
aday.put(TAG_RESIM, resim);
aday.put(TAG_NO, no);
aday.put(TAG_TOPLAM, ToplamOy);
adayList.add(aday);
}
I know this question in a year old, but anyway...
I needed to compare two JSONObject values without internal JSONObject/JSONArray. Most SO solutions recommend a 3-rd party java library, which would be a bit too heavy.
First of all, the Android's built-in JSONObject does not define hashCode() and equals() in any sensible way. I used a wrapper class with a JSONObject inside.
The below functions are placed in some utility class, it is a trivial exercise to use them to define hashCode() and equals().
public static int jsonHashCode(JSONObject j) {
if (j == null) {
return 0;
}
int res = 0;
for (String s : new AsIterable<String>(j.keys())) {
res += s.hashCode();
}
return res;
}
public static boolean comparesEqual(JSONObject x, JSONObject y, Collection<String>only, Collection<String>except) {
Set<String> keys = keySet(x);
keys.addAll(keySet(y));
if (only != null) {
keys.retainAll(only);
}
if (except != null) {
keys.removeAll(except);
}
for (String s : keys) {
Object a = null, b = null;
try {
a = x.get(s);
} catch (JSONException e) {
}
try {
b = x.get(s);
} catch (JSONException e) {
}
if (a != null) {
if (!a.equals(b)) {
return false;
}
} else if (b != null) {
if (!b.equals(a)) {
return false;
}
}
}
return true;
}
public static Set<String> keySet(JSONObject j) {
Set<String> res = new TreeSet<String>();
for (String s : new AsIterable<String>(j.keys())) {
res.add(s);
}
return res;
}
where AsIterable lets us use the for(:) loop with an iterator and is defined as:
public class AsIterable<T> implements Iterable<T> {
private Iterator<T> iterator;
public AsIterable(Iterator<T> iterator) {
this.iterator = iterator;
}
public Iterator<T> iterator() {
return iterator;
}
}
You are welcome to write and post the recursive version of this code, supporting JSONObject/JSONArray values.
For my use case, I ended up iterating over the keys of the first json object and checked to see if the value matched what was in the second json object.
JSONObject obj = new JSONObject("some json string");
JSONObject comparison = new JSONObject("some other json string with the same data but different key order");
boolean equal = true;
for (Iterator<String> iterator = obj.keys(); iterator.hasNext(); ) {
String curKey = iterator.next();
if(!obj.getString(curKey).equals(comparison.getString(curKey))){
equal = false;
break;
}
}
if(equal){
// do the thing that i want to do if the two objs are equal
}

Fragment spinner doesn't stop in Android

I use this code to load the nearby places of any particular location by setting the** data using an Array Adapter. There are two issues that I face:
1. The spinner doesn't stop even after the data is loaded. (There should be no spinner. But I am not sure how does Fragment when it comes to this.)
I'm going to implement AsyncTask to get the places so that it doesn't slow down the Activity. The mini problem I face is this: How do I notify the user (update the view) with new date when he/she has changed his location. Let's assume that that the user is walking. Thus the lat/lon will change. So, how can I use onChangeNotify() and change the value of the List.
public class FragmentMap extends ListFragment {
ArrayList<Place> places = new ArrayList<Place>();
//List<String> val = new List<String>()
//#InjectView(R.id.explorePlacesListView) ListView placesListView;
ListView listView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ListView listView = (ListView) getActivity().findViewById(R.id.explorePlacesListView);
getPlaces();
PlacesAdapter placesAdapter = new PlacesAdapter(getActivity(),R.layout.user_list_item, places);
listView.setAdapter(placesAdapter);
}
public void getPlaces(){
URL yahoo;
String key,latitude,longitude;
key = "AIzaSyAZgD01sj3jssaYCmkLL8c7Z4qPTEdt6xU";
latitude = "37.77264";
longitude ="-122.409915";
try {
yahoo = new URL("https://maps.googleapis.com/maps/api/place/search/json?location=-33.8670522,151.1957362&radius=500&sensor=false&key=AIzaSyB2SGEmOLDGB_f0bp1PGTjQqTw2VuDcaM8");
URLConnection yc = yahoo.openConnection();
BufferedReader in = new BufferedReader(
new InputStreamReader(
yc.getInputStream()));
String inputLine;
String jsonLine = new String();
while ((inputLine = in.readLine()) != null) {
Log.d("inputLine",inputLine);
jsonLine = jsonLine + inputLine;
}
in.close();
Object jsonResponse = parseResponse(jsonLine);
parseJSONPlaces((JSONObject)jsonResponse);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected Object parseResponse(String responseBody) throws JSONException {
return new JSONTokener(responseBody).nextValue();
}
private void parseJSONPlaces(JSONObject json){
try {
JSONArray jsonArray = json.getJSONArray("results");
for (int j = 0; j < json.length(); j++) {
Place place = new Place();
place.name = jsonArray.getJSONObject(j).getString("name");
place.icon = jsonArray.getJSONObject(j).getString("icon");
// JSONObject locationObject = jsonArray.getJSONObject(j).getJSONObject("location");
// place.latitude = locationObject.getString("latitude");
// place.longitude = locationObject.getString("longitude");
Log.d("name",place.name);
places.add(place);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(json.optJSONObject("results") != null){
}
}
There are a few things in your code that looks a bit strange to me.
You never call setListAdapter() which binds an adapter to the internal ListView of the ListFragment. Instead, you are fetching another ListView and set an adapter to that one. That is probably why no data gets displayed in the list, and you will instead se a progress indicator.
I'm not sure I understand your second question, but you should put your UI updates in the onPostExecute method of AsychTask.

nested AsyncTask and onPostExecute

I am using a AsyncTask (1) in another AsyncTask (2).
AsyncTask 1 fetches online user data, counts the number of entries in the response and for each entry, in onPostExecute displays a username and runs a new AsyncTask (2) to fetch a image from a server and load it into a ImageView. This all happens in onPostExecute.
This is working flawlessly, the user data is fetched and shown, and the images are shown one by one for each entry.
However, the itteration through the array and the updating of the TextView in AsyncTask 1's onPostExecute happens so fast, it basically only shows the last user name in the array, the other ones are loaded, but impossible to detect with the human eye :)
Meanwhile, AsyncTask 2 is still fetching images from online, and showing profile images for the wrong users.
The problem I have here obviously, is these 2 need to be in sync.
So I thought I just wait for the output in AsyncTask 2 with the get() method, but now nothing is updated at all anymore, no TextView...this is unexpected behaviour for me.
So, the question is how to sync the 2 AsyncTasks?
bit of code to clarify, if it's still needed
//instantiate first AsyncTask
new AsyncRequest().execute(bundle);
private class AsyncRequest extends AsyncTask<Bundle, Void, String> {
protected String doInBackground(Bundle... bundle) {
String data = null;
try {
data = request(null, bundle[0]); //request the data
return data;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}// end method
protected void onPostExecute(String response) {
JSONArray data = null;
try {
JSONObject response2 = Util.parseJson(response);
data = response2.optJSONArray("data");
int amount = data.length();
TextView s1 = (TextView) findViewById(R.id.some_id);
s1.setText("" + amount); //displays number of items
//display the data
for(int i=0; i<amount; i++){
String email = "";
String id = "";
JSONObject json_obj = data.getJSONObject(i);
Log.d("JSONObject ", ""+json_obj);
String name = json_obj.getString("name");
if (json_obj.has("email")){
email = json_obj.getString("email");
}
if (json_obj.has("id")){
id = json_obj.getString("id");
}
String picture = "http://www.domain.com/"+id+"/picture";
TextView s2 = (TextView) findViewById(R.id.name_placeholder);
s2.setText(name);
//here we do a new AsynTask for each entry and wait until the data is fetched
new DownloadProfileImageTask().execute(picture, name).get();
}
} catch (JSONException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}// end method
It is not quite clear why you are calling setText of the single TextView with the name of multiple names. As you have mentioned, although you had setText of all the names, you only see a single name. May be you need to use a ListView or something like that.
Now regarding your question: probably you don't need two AsyncTasks. You can do everything in a single AsyncTask. The code will be something like below:
//Create a Holder class as a data holder.
//For simplicity, public attributes are used
class Holder{
public String name;
public String email;
public String id;
public BitmapDrawable imageDrawable;
}
//instantiate the AsyncTask
new AsyncRequest().execute(bundle);
private class AsyncRequest extends AsyncTask<Bundle, Holder, Integer> {
protected Integer doInBackground(Bundle... bundle) {
int amount = 0;
try {
data = request(null, bundle[0]); //request the data
JSONArray data = null;
JSONObject response2 = Util.parseJson(response);
data = response2.optJSONArray("data");
amount = data.length();
//display the data
for(int i=0; i<amount; i++){
Holder holder = new Holder();
holder.email = "";
holder.id = "";
JSONObject json_obj = data.getJSONObject(i);
Log.d("JSONObject ", ""+json_obj);
holder.name = json_obj.getString("name");
if (json_obj.has("email")){
holder.email = json_obj.getString("email");
}
if (json_obj.has("id")){
holder.id = json_obj.getString("id");
}
String picture = "http://www.domain.com/"+id+"/picture";
//Fetch the image and create a Drawable from it - Synchronously
holder.imageDrawable = getImageDrawable(picture, name);
publishProgress(holder);
}
} catch (Exception e) {
e.printStackTrace();
}
return amount;
}// end method
protected void onProgressUpdate(Holder... holder) {
//Update the user name and image
TextView s2 = (TextView) findViewById(R.id.name_placeholder);
s2.setText(holder[0].name);
ImageView imgView = (ImageView) findViewById(R.id.imageViewId);
imgView.setImageDrawable(holder[0].imageDrawable);
}
protected void onPostExecute(Integer amount) {
TextView s1 = (TextView) findViewById(R.id.some_id);
s1.setText(amount.toString()); //displays number of items
}// end method

Categories

Resources