OnPostExecute item to ListView - android

Here is OnPostExecute That retuns Listitem [name1,name2,name3]:
#Override
protected void onPostExecute(JSONObject json) {
try {
if (json.getString(KEY_SUCCESS) != null) {
String result = json.getString(KEY_SUCCESS);
if (Integer.parseInt(result) == 1) {
pDialog.setMessage("Loading View");
pDialog.setTitle("Getting Friends");
//JSONArray root = new JSONArray(json);
JSONArray friend = json.getJSONArray("users");
List<String> item = new ArrayList<String>();
for (int i = 0; i < friend.length(); i++) {
JSONObject att = (JSONObject) friend.getJSONObject(i);
String res = att.getString("username");
item.add(res);
}
SharedPreferences FriendList = getSharedPreferences("FriendList", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = FriendList.edit();
edit.putString("KEY_FRIENDS", item.toString());
edit.commit();
} else {
pDialog.dismiss();
}
}else {
pDialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
}
pDialog.dismiss();
}
I want it In List View but im stucked, because i cant use ListAdapter in OnPostExecute.
public class FriendList extends ListActivity { ...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_friend_list);
// listt = (TextView) findViewById(R.id.testyL);
// list = (TextView) findViewById(R.id.textView4);
// list = (ListView) findViewById(R.id.label);
try {
new GetFriends().execute();
}catch (Exception e) {
e.printStackTrace() ;
Log.e("ERR ", "AsyncTASK" + e.toString());
}
SharedPreferences FriendList = getSharedPreferences("FriendList", Context.MODE_PRIVATE);
String u = FriendList.getString("KEY_FRIENDS", "0");
I tried to put item to SharedPref but it seems i dont know how to properly retrevie it and conter to variable that can be used by Array/List Adapter.
Here is the problem :)
// Binding resources Array to ListAdapter
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, item ));
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String product = ((TextView) view).getText().toString();
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), Logged.class);
// sending data to new activity
i.putExtra("friend", product);
startActivity(i);
}
});
}

Change GetFriends constructor add reference to FriendList object:
try {
new GetFriends(FriendList.this).execute();
}catch (Exception e) {
e.printStackTrace() ;
Log.e("ERR ", "AsyncTASK" + e.toString());
}
class:
public class GetFriends extends [...]{
private ListActivity mList;
public GetFriends(ListActivity list){
mList = list;
}
[...]
#Override
protected void onPostExecute(JSONObject json) {
//set Adapter to list
mList.
}
}

Related

Adding parsed JSON to a ListView and displaying it

public class GithubTab extends Fragment implements AdapterView.OnItemClickListener {
ListView repoListView;
private ListAdapter adapter;
private List<RepositoryItem> repoListItems;
private List<String> repoNameList;
private List<String> userNameList;
private List<String> descriptionList;
private TextView tvData;
private static final String TAG = "Github Tab";
Button buttonHit;
TextView resultText;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.github_tab, container, false);
repoListView = (ListView) view.findViewById(R.id.repoList);
repoListItems = new ArrayList<>();
repoNameList = new ArrayList<>();
userNameList = new ArrayList<>();
descriptionList = new ArrayList<>();
adapter = new ListAdapter(getContext(), repoListItems);
repoListView.setAdapter(adapter);
tvData = (TextView) view.findViewById(R.id.tvJsonItem);
// Clickable: able to open the GitHub webpage of the re
repoListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getContext(), "Clicked id" + view.getTag(), Toast.LENGTH_SHORT).show();
}
});
new JSONTask().execute("https://api.github.com/users/whyjay17/repos");
for(int i = 0; i < repoNameList.size(); i++) {
repoListItems.add(new RepositoryItem(i, repoNameList.get(i), userNameList.get(i), "ddd"));
}
return view;
}
public class JSONTask extends AsyncTask<String, String, String> {
#Override
// Any non-UI thread process is running in this method. After completion, it sends the result to OnPostExecute
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
.... Code Hidden ....
return retreivedJson;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//cant close null
if (connection != null) {
// close both connection and the reader
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public void formatJSONArray(String results){
try {
JSONArray jsonArray = new JSONArray(results);
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jsonObject=jsonArray.getJSONObject(i);
if(jsonObject.optString("name") != null) {
//tvData.append(jsonObject.getString("name"));
repoNameList.add(jsonObject.getString("name"));
//Toast.makeText(getContext(), "1 " + repoNameList.get(1), Toast.LENGTH_SHORT).show();
}
if(jsonObject.optJSONObject("owner") != null){
JSONObject ownerObject=jsonObject.getJSONObject("owner");
if(ownerObject.optString("login")!=null) {
//tvData.append(ownerObject.getString("login"));
userNameList.add(ownerObject.getString("login"));
//ownerObject.append(ownerObject.getString("avatar_url"));
}
}
}
}catch (JSONException jsonException){
}
}
/*
* Called after the background computation finishes. Result of doInBackground is passed in as a parameter.
*
* */
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
/* for JSONArray data*/
if(result!=null && !result.isEmpty()) {
formatJSONArray(result);
}
}
}
}
The code above basically tries to parse a JSON data from https://api.github.com/users/famous/repos, adds some certain info (repo name, id, description) to the corresponding lists, and tries to display that on the listView that I created.
The listView works when I hard code the information (meaning that there is no problem with the listView itself), but when I try to put in the data inside the list (which has the parsed JSON info and I tested that it is actually inside the list), it gives me an empty list.
How can I make this work?
The data come asynchronous so inside onCreateView() the list data may not be ready yet for adding to adapter.
You need to move the code that add elements to ListView adapter into onPostExecute(), after formatJSONArray() method, then call notifyDatasetChange() to invalidate the ListView
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
/* for JSONArray data*/
if(result!=null && !result.isEmpty()) {
formatJSONArray(result);
for(int i = 0; i < repoNameList.size(); i++) {
repoListItems.add(new RepositoryItem(i,
repoNameList.get(i), userNameList.get(i), "ddd"));
}
adapter.notifyDatasetChanged();
}
}
You can call adapter.notifiDatasetchange() in your formatJSONArray method:
public void formatJSONArray(String results){
try {
JSONArray jsonArray = new JSONArray(results);
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jsonObject=jsonArray.getJSONObject(i);
if(jsonObject.optString("name") != null) {
//tvData.append(jsonObject.getString("name"));
repoNameList.add(jsonObject.getString("name"));
//Toast.makeText(getContext(), "1 " + repoNameList.get(1), Toast.LENGTH_SHORT).show();
}
if(jsonObject.optJSONObject("owner") != null){
JSONObject ownerObject=jsonObject.getJSONObject("owner");
if(ownerObject.optString("login")!=null) {
//tvData.append(ownerObject.getString("login"));
userNameList.add(ownerObject.getString("login"));
//ownerObject.append(ownerObject.getString("avatar_url"));
}
}
}
adapter.notifiDatasetchange();
}catch (JSONException jsonException){
}
}
If it don't work , you can set adapter again in your formatJSONArray method
adapter = new ListAdapter(getContext(), repoListItems);
repoListView.setAdapter(adapter);
It worked for me. I hope it can help your problem!
for(int i = 0; i < repoNameList.size(); i++) {
repoListItems.add(new RepositoryItem(i,repoNameList.get(i),userNameList.get(i), "ddd"));
}
adapter.notifyDataSetChanged();
`
add this line before
}catch (JSONException jsonException){

Passing Data from Fragment listview item to Activity string variable onitemclicklistener

I am trying to pass a ListView item from a fragment to a String variable "url" in activity, The intent successfully creates the activity however I run issues into it when I try passing data.
the fragment class has a listview with json data that brings up the list of picture,title and name. when a user selects an item it brings them to the activity. I want their selection transfer the name from the listview to the url variable in the other activity. so the url changed from "https://.....id=" to "https://.....id="+name from the fragment.
thats will make the recyclerview changed with the new url for any listview item clicked.
my fragment:
public class Accueil extends Fragment {
ArrayList<articles> arrayList;
ListView lv;
public static String URL1=null;
class ReadJSON extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
#Override
protected void onPostExecute(String content) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(content);
} catch (JSONException e1) {
e1.printStackTrace();
}
JSONArray jsonArray = null;
try {
jsonArray = jsonObject.getJSONArray("articles");
} catch (JSONException e1) {
e1.printStackTrace();
}
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject articlesobject = null;
try {
articlesobject = jsonArray.getJSONObject(i);
} catch (JSONException e1) {
e1.printStackTrace();
}
try {
arrayList.add(new articles(
articlesobject.getString("picture"),
articlesobject.getString("title"),
articlesobject.getString("name")
));
} catch (JSONException e1) {
e1.printStackTrace();
}
CustomListAdaper adaper = new CustomListAdaper(
getActivity().getApplicationContext(),
R.layout.custom_list_layout, arrayList
);
lv.setAdapter(adaper);
}
}
private String readURL(String theURL) {
StringBuilder content = new StringBuilder();
try {
URL url = new URL(theURL);
URLConnection urlConnection = url.openConnection();
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
content.append(line + "\n");
}
bufferedReader.close();
} catch (Exception e) {
e.printStackTrace();
}
return content.toString();
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
arrayList = new ArrayList<>();
View rootView = inflater.inflate(R.layout.accueil, container, false);
lv = (ListView) rootView.findViewById(R.id.ListView1);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
new Accueil.ReadJSON().execute("http://wach.ma/mobile/home.php");
}
});
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int
position, long id) {
String selectedFromList =
(lv.getItemAtPosition(position).toString());
Intent i = new Intent(getActivity(), Test.class);
i.putExtra("name", selectedFromList);
startActivity(i);
}
});
return rootView;
}
}
my activity:
public class Test extends AppCompatActivity {
public String URL_DATA="http://wach.ma/mobile/category.php?id=";
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<ListItem> listItems;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems = new ArrayList<>();
Intent i = getIntent();
String s1 = i.getStringExtra("name");
URL_DATA=URL_DATA+s1;
loadRecyclerViewData();
}
private void loadRecyclerViewData(){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Chargement...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET,
URL_DATA, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray("articles");
for(int i = 0; i<array.length();i++){
JSONObject o = array.getJSONObject(i);
ListItem item = new ListItem(
o.getString("picture"),
o.getString("name"),
o.getString("city"),
o.getString("add_time"),
o.getString("price")
);
listItems.add(item);
}
adapter = new Myadapter(listItems, getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(getApplicationContext(),
volleyError.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Thank you in advance, and i'm very sorry for my bad English
Your problem comes from this I think : String selectedFromList =
(lv.getItemAtPosition(position).toString());
lv.getItemAtPosition(position) returns an Object which is an item of the listView Adapter !
Calling toString() on this object will return nothing good :)
The OnClickListener has a View in parameter which is the parent View, in your case, the Item View you clicked.
You can retrieve the TextView holding the name field in the OnClickListener and get the string of this TextView like this :
#Override
public void onItemClick(AdapterView<?> parent, View view, int postion, long id) {
String name = ((TextView) view.findViewById(R.id.myNameField)).getText().toString();
}
Hope that will help you :)
PS : Post your XML code as well next time ;)
I fix it, just change this:
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int
position, long id) {
String selectedFromList =
(lv.getItemAtPosition(position).toString());
Intent i = new Intent(getActivity(), Test.class);
i.putExtra("name", selectedFromList);
startActivity(i);
}
});
return rootView;
to this:
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int
position, long id) {
String selectedFromList=
String.valueOf(arrayList.get(position).getIdd());
Intent i = new Intent(getActivity(), Test.class);
i.putExtra("name", selectedFromList);
startActivity(i);
}
});
return rootView;

Android - Display data from Adapter in Listview

I've currently got an application that pulls data from a mysql database and displays it in raw JSON format. I'm currently working on pushing this data into a String variable and displaying it on a Listview on a specific activity.
Problem is, when trying to display this data, my Listview is not populating; I'm sure the variable is not empty as the if statement would have captured this.
Here is snippet of MainActivity code:
//Methods to grab information from abhandym_DB database
public void getJSON(View view){
new BackgroundTask().execute();
}
public void parseJSON(View view){
if(JSON_String==null){
Toast.makeText(getApplicationContext(), "First Get Json", Toast.LENGTH_LONG).show();
}else{
Intent intent = new Intent(this,Test.class);
intent.putExtra("JSON_Data",JSON_String);
startActivity(intent);
}
}
class BackgroundTask extends AsyncTask<Void,Void,String>{
String json_url;
#Override
protected void onPreExecute() {
json_url = "http://abhandyman.x10host.com/json_get_data.php";
}
#Override
protected String doInBackground(Void... params) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
InputStream inputSteam = httpURLConnection.getInputStream();
BufferedReader buffereredReader = new BufferedReader(new InputStreamReader(inputSteam));
StringBuilder stringBuilder = new StringBuilder();
while((JSON_String = buffereredReader.readLine())!=null){
stringBuilder.append(JSON_String+"\n");
}
buffereredReader.close();
inputSteam.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
TextView textView = (TextView)findViewById(R.id.fragment1_textview_JSONAPPEAR);
textView.setText(result);
JSON_String = result;
}
}
Here is the code for my Test.java
public class Test extends AppCompatActivity {
String JSON_String;
JSONObject jsonObject;
JSONArray jsonArray;
DataAdapter dataAdapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_layout);
listView = (ListView)findViewById(R.id.test_listView);
dataAdapter = new DataAdapter(this, R.layout.row_layout);
listView.setAdapter(dataAdapter);
JSON_String = getIntent().getExtras().getString("JSON_Data");
try {
jsonObject = new JSONObject(JSON_String);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
String jobid,problem,resolution;
while(count<jsonObject.length()){
JSONObject JO = jsonArray.getJSONObject(count);
jobid = JO.getString("jobid");
problem = JO.getString("problem");
resolution = JO.getString("resolution");
Data data = new Data(jobid,problem,resolution);
dataAdapter.add(data);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Here is the code for my DataAdapter:
public class DataAdapter extends ArrayAdapter{
List list = new ArrayList();
public DataAdapter(Context context, int resource) {
super(context, resource);
}
public void add(Data object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
row = convertView;
DataHolder dataHolder;
if(row == null){
LayoutInflater layoutInflater = (LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout,parent,false);
dataHolder = new DataHolder();
dataHolder.tx_jobid = (TextView) row.findViewById(R.id.tx_jobid);
dataHolder.tx_problem = (TextView) row.findViewById(R.id.tx_problem);
dataHolder.tx_resolution = (TextView) row.findViewById(R.id.tx_resolution);
row.setTag(dataHolder);
}else{
dataHolder = (DataHolder)row.getTag();
}
Data data = (Data)this.getItem(position);
dataHolder.tx_jobid.setText(data.getJobid());
dataHolder.tx_problem.setText(data.getProblem());
dataHolder.tx_resolution.setText(data.getResolution());
return row;
}
static class DataHolder{
TextView tx_jobid,tx_problem,tx_resolution;
}
}
and here is what it displays when clicking on "Parse JSON" button.
listView empty after population
Any help or advise on why its not displaying would be much appreciated!
Thanks in advance!
your problem seems to be here :
while(count<jsonObject.length()){
you're not looping using the number of array elements but using the number of mapped key:value object which is one (the "server_response") , you have to change this line to :
while(count<jsonArray.length()){
,
you have just the first element showing because jsonObject.length() will return 1 since it have just one element.
from the doc, JSONObject, length() method:
Returns the number of name/value mappings in this object.
and in your case you have just one name/value mapped ("server_response":[array items...])
Check in Test.java. I think You are setting the adapter to the listview before adding data to it
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_layout);
listView = (ListView)findViewById(R.id.test_listView);
dataAdapter = new DataAdapter(this, R.layout.row_layout);
JSON_String = getIntent().getExtras().getString("JSON_Data");
try {
jsonObject = new JSONObject(JSON_String);
jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
String jobid,problem,resolution;
while(count<jsonObject.length()){
JSONObject JO = jsonArray.getJSONObject(count);
jobid = JO.getString("jobid");
problem = JO.getString("problem");
resolution = JO.getString("resolution");
Data data = new Data(jobid,problem,resolution);
dataAdapter.add(data);
count++;
}
} catch (JSONException e) {
e.printStackTrace();
}
listView.setAdapter(dataAdapter); //change effected
}

ArrayList is not Loading in Spinner

Can u please tell me why my arraylist is not Loading in spinner. It is showing empty Spinner.im to populate spinner using arraylist ,And doing a service call;
Where did i do the mistake.
Here is my Activity;
public class CircleListActivity extends MWTActivity {
private ArrayList<String> arrayList = new ArrayList<String>();
private Spinner state_spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState, MWT.Home_SCREEN);
setContentView(R.layout.circlelist);
showDialog(1);
MWTWebService.circlelistServices(new IMWTListener() {
#Override
public void recieveVersionResponse(String resp) {
}
#Override
public void receivedResponse(String resp, String id) {
}
#Override
public void receivedResponse(String resp) {
showDialog(1);
System.out.println("rsp: " + resp);
try {
JSONObject jsonObject = new JSONObject(resp);
JSONArray jsonArray = jsonObject
.getJSONArray("circleListForHording");
arrayList.add("Select State");
for (int i = 0; i < jsonArray.length(); i++) {
String state = (String) jsonArray.get(i);
arrayList.add(state);
}
state_spinner = (Spinner) findViewById(R.id.state);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
CircleListActivity.this,
android.R.layout.simple_spinner_item, arrayList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
System.out.println("PP " + adapter.getItem(1));
state_spinner.setAdapter(adapter);
dismissDialog(1);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(String resp, int erroCode) {
}
}, LoginScreen.userNameNew.toString().trim());
// if (Util.readNetworkConnection(CircleListActivity.this)) {} else {
// ArrayAdapter<String> adapter = new ArrayAdapter<String>(
// CircleListActivity.this,
// android.R.layout.simple_spinner_item, arrayList);
//
// adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// state_spinner.setAdapter(adapter);
//
// }
}
}

Android custom adapter passing ArrayList of Objects

hopefully someone can point me in the right direction, i am creating a custom adapter to display 3 items in a listview image,id,text.
so i get my data from a webservice returning JSON objects which works fine. my problem is im not sure where im going wrong after the Asynctask because the list does not have any data, i have implemented this already when passing single field to a spinner but just can't figure it out. i know the custom adapter works as when i manually assign new CallOut objects and add to the Arraylist they list displays fine thanks for any help.
public class ListCallOuts extends Activity {
ArrayList<CallOut> callOutResults=new ArrayList<CallOut>(); //=GetCallOuts();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
GetCallOuts();
//ArrayList<CallOut> searchResults = GetSearchResults();
final ListView lv1 = (ListView) findViewById(R.id.listView1);
lv1.setAdapter(new CallOutAdapter(this,callOutResults));
//lv1.setAdapter(new CallOutAdapter(this, searchResults));
lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = lv1.getItemAtPosition(position);
CallOut fullObject = (CallOut)o;
Toast.makeText(ListCallOuts.this, "You have chosen: " + " " +
fullObject.getName(), Toast.LENGTH_LONG).show();
}
});
}
private void GetCallOuts() {
new DownloadCallouts().execute(new String[]
{"http://192.168.0.16:8080/return_callouts.json"});
}
private class DownloadCallouts extends AsyncTask<String,Void,JSONArray> {
#Override
protected JSONArray doInBackground(String... urls) {
JSONArray array = null;
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
HttpEntity entity = execute.getEntity();
String data = EntityUtils.toString(entity);
array = new JSONArray(data);
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return array;
}
#Override
protected void onPostExecute(JSONArray jsonArray) {
for(int i=0;i<jsonArray.length();i++){
try {
JSONObject row = jsonArray.getJSONObject(i);
CallOut callOut = new
CallOut(row.getString("id"),row.getString("customer_name")) ;
callOutResults.add(callOut);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
Change this:
final ListView lv1 = (ListView) findViewById(R.id.listView1);
lv1.setAdapter(new CallOutAdapter(this,callOutResults));
With this:
final ListView lv1 = (ListView) findViewById(R.id.listView1);
callOutAdapter = new CallOutAdapter(this,callOutResults);
lv1.setAdapter(callOutAdapter);
Note: you should define this as a property of your class to reach it at onPostExecute method.
CallOutAdapter callOutAdapter;
And after updating your arraylist at onPostExecute add this line:
callOutAdapter.notifyDataSetChanged();

Categories

Resources