I have an listview that contacts a web service whenever it is called and this is what it looks like
public class ListView extends ListActivity {
ArrayList<HashMap<String, String>> questionList;
final String TAG_DATA_WEB = "data";
private String stringxxx;
ProgressDialog pDialog;
LoadAllData mTask;
JSONArray question = null;
android.widget.ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.listview);
stringxxx = getIntent().getStringExtra("TAG_SEARCH");
questionList = new ArrayList<HashMap<String, String>>();
mTask = new LoadAllData();
mTask.execute();
}
#Override
protected void onListItemClick(android.widget.ListView l, View v, int pos, long id) {
super.onListItemClick(l, v, pos, id);
HashMap<String, String> item = questionList.get(pos);
Intent i = new Intent(ListView.this, SingleListItem.class);
i.putExtra(TAG_DATA_WEB, item.get(TAG_DATA_WEB));
startActivity(i);
}
#Override
public void onBackPressed()
{
/** If user Pressed BackButton While Running Asynctask
this will close the ASynctask.
*/
if (mTask != null && mTask.getStatus() != AsyncTask.Status.FINISHED)
{
mTask.cancel(true);
}
super.onBackPressed();
Intent i = new Intent(ListView.this, PREV.class);
startActivity(i);
finish();
}
#Override
protected void onDestroy() {
if (mTask != null && mTask.getStatus() != AsyncTask.Status.FINISHED)
{
mTask.cancel(true);
}
super.onDestroy();
}
#Override
protected void onPause() {
if (pDialog != null)
{
if(pDialog.isShowing())
{
pDialog.dismiss();
}
super.onPause();
}
}
class LoadAllData extends AsyncTask<String, Void, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ListView.this);
pDialog.setMessage("Loading Data. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
pDialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
public void onCancel(DialogInterface dialog) {
mTask.cancel(true);
Intent i = new Intent(ListView.this, PREV.class);
startActivity(i);
finish();
}
});
JSONObject json = new JSONObject();
try {
String query = URLEncoder.encode(searchTerm, "utf-8");
String URL = "http://example.com";
JSONParsser jParser = new JSONParsser();
json = jParser.readJSONFeed(URL);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
JSONArray questions = json.getJSONObject("all").getJSONArray("questions");
for(int i = 0; i < DT.length(); i++) {
JSONObject question = DT.getJSONObject(i);
String data = question.getString(TAG_DATA_WEB);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_DATA_WEB, data);
questionList.add(map);
pDialog.dismiss();
ListAdapter adapter = new SimpleAdapter(getBaseContext(), questionList,
R.layout.listelements,
new String[] { TAG_DATA_WEB }, new int[] {
R.id.Subject,});
setListAdapter(adapter);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
The problem I have is that when I click on an item on the listview to go to the next activity, it does as its suppose too with no problem its just when I pressed the back button to go back the listview, the listview activity restarts and it also contacts the web service again to retrieve the information like as if I put finish(); after startArtivity(I); in the onItemClick part of the code. Now normally this wouldn't be a problem if you web service didn't have a search limit but the one i am using does. So basically what Im saying is that when the user clicks on an listview item to go to the next activity and when they press the onBack button, I want the information to still be there instead of the application contacting the web service again to retrieve information and the end result will be the search limit being reached. Can anybody help me with this?
I have used XML parsing so I can probably give you help logically.
You can use bean class with get and set methods and store the results
you get from web service.
Use Set methods to store the values where you have written the
parsing code.
Use get methods in your activity's adapter code to retrieve those
values.
This way web service won't be called again when you reach that
activity using back button.
But remember, if you launch that activity with service again from its parent, web service will be called again.
You would have several options:
Replace the AsyncTask data loading with an AsyncTaskLoader data loading. Check the Loader developer article first. I dropped using AsyncTasks for data loading long time ago...
The scond option is to store the data you receive and don't call the webservice next time. For this, store the data somehow in onSaveInstanceState and in onCreate check if Bundle parameter is not null and if you have data set there for th same key you used in onSaveInstanceState. If true, you already have the data. If false, query.
Depending on data importance and volatility you could save it once in some kind of app persistence (shared preference or sqlite) once you downloaded it and use it every time the activity recreates or creates itself.
Related
I am busy with an application where i am getting data from my azure database with sql and storing it in an array. I created a separate class where i get my data and my main activity connects to this class and then displays it.
Here is my getData class:
public class GetData {
Connection connect;
String ConnectionResult = "";
Boolean isSuccess = false;
public List<Map<String,String>> doInBackground() {
List<Map<String, String>> data = null;
data = new ArrayList<Map<String, String>>();
try {
ConnectionHelper conStr=new ConnectionHelper();
connect =conStr.connectionclass(); // Connect to database
if (connect == null) {
ConnectionResult = "Check Your Internet Access!";
} else {
// Change below query according to your own database.
String query = "select * from cc_rail";
Statement stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
Map<String,String> datanum=new HashMap<String,String>();
datanum.put("NAME",rs.getString("RAIL_NAME"));
datanum.put("PRICE",rs.getString("RAIL_UNIT_PRICE"));
datanum.put("RANGE",rs.getString("RAIL_RANGE"));
datanum.put("SUPPLIER",rs.getString("RAIL_SUPPLIER"));
datanum.put("SIZE",rs.getString("RAIL_SIZE"));
data.add(datanum);
}
ConnectionResult = " successful";
isSuccess=true;
connect.close();
}
} catch (Exception ex) {
isSuccess = false;
ConnectionResult = ex.getMessage();
}
return data;
}
}
And in my Fragmentactivity.java I simply just call the class as shown here:
List<Map<String,String>> MyData = null;
GetValence mydata =new GetValence();
MyData= mydata.doInBackground();
String[] fromwhere = { "NAME","PRICE","RANGE","SUPPLIER","SIZE" };
int[] viewswhere = {R.id.Name_txtView , R.id.price_txtView,R.id.Range_txtView,R.id.size_txtView,R.id.supplier_txtView};
ADAhere = new SimpleAdapter(getActivity(), MyData,R.layout.list_valence, fromwhere, viewswhere);
list.setAdapter(ADAhere);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HashMap<String,Object> obj=(HashMap<String,Object>)ADAhere.getItem(position);
String ID=(String)obj.get("A");
Toast.makeText(getActivity(), ID, Toast.LENGTH_SHORT).show();
}
});
My problem comes when I want to include the onPreExecute and onPostExecute because I am relatively new to android studio and I do not know where to put the following lines of code:
#Override
protected void onPreExecute() {
ProgressDialog progress;
progress = ProgressDialog.show(MainActivity.this, "Synchronising", "Listview Loading! Please Wait...", true);
}
#Override
protected void onPostExecute(String msg) {
progress.dismiss();
}
You need to get the data from your azure database using a background service or AsyncTask. However, you are defining a class GetData which does not extend AsyncTask and hence the whole operation is not asynchronous. And I saw you have implemented doInBackground method which is not applicable here as you are not extending AsyncTask. I would suggest an implementation like the following.
You want to get some data from your azure database and want to show them in your application. In these kind of situations, you need to do this using an AsyncTask to call the server api to get the data and pass the data to the calling activity using an interface. Let us have an interface like the following.
public interface HttpResponseListener {
void httpResponseReceiver(String result);
}
Now from your Activity while you want to get the data through an web service call, i.e. AsyncTask, just the pass the interface from the activity class to the AsyncTask. Remember that your AsyncTask should have an instance variable of that listener as well. So the overall implementation should look like the following.
public abstract class HttpRequestAsyncTask extends AsyncTask<Void, Void, String> {
public HttpResponseListener mHttpResponseListener;
private final Context mContext;
HttpRequestAsyncTask(Context mContext, HttpResponseListener listener) {
this.mContext = mContext;
this.mHttpResponseListener = listener;
}
#Override
protected String doInBackground(Void... params) {
String result = null;
try {
// Your implementation of getting data from your server
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(final String result) {
mHttpResponseListener.httpResponseReceiver(result);
}
#Override
protected void onCancelled() {
mHttpResponseListener.httpResponseReceiver(null);
}
}
Now you need to have the httpResponseReceiver function implemented in the calling Activity. So the sample activity should look like.
public class YourActivity extends AppCompatActivity implements HttpResponseListener {
// ... Other code and overriden functions
public void callAsyncTaskForGettingData() {
// Pass the listener here
HttpRequestAsyncTask getDataTask = new HttpRequestGetAsyncTask(
YourActivity.this, this);
getDataTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
#Override
public void httpResponseReceiver(String result) {
// Get the response callback here
// Do your changes in UI elements here.
}
}
To read more about how to use AsyncTask, you might consider having a look at here.
I am building an application that is pretty dependent on async requests to function.
I have the main Activity called MainActivity. This really doesn't do much apart from contain layouts, however it does have a recycleviewer.
I then have a couple of http requests that are done to populate the recycle viewer.
To do this I have wrote a java class as follows:
public class dataforUi extends AsyncTask<String, String, JsonObject> {
private ArrayList<UiElements> els;
protected void onPreExecute() {
progressDialog.setMessage("Downloading your data...");
progressDialog.show();
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface arg0) {
RedditRequests.this.cancel(true);
}
});
}
protected JsonObject doInBackground(String... params) {
Do the http request here, get the result and populate uiElements with it
}
#Override
protected void onPostExecute(JsonObject jsonObject) {
super.onPostExecute(jsonObject);
progressDialog.hide();
}
I have a few more classes like this but hopefully it serves as an example of what I'm trying to do.
Then back in Main Activity, I have this code:
public void getUiElements() {
dataforUi ui = new dataforUi(findViewById(android.R.id.content));
try {
ui.execute("https://t").get();
ArrayList<UiElements> r = ui.getEls();
Log.d("MainFeedScreen", "Size of r is:" + r.size());
UiAdapter = new UiAdapter(r);
mRecyclerView.setAdapter(UiAdapter);
} catch (Exception e) {
}
}
This works fine, but it is very jolty due to the use of .get() on execute to make it blocking. If i remove .get() the progress bar shows up and disappears when the task is done, but my ui thread has progressed past this and ha tried to populate my view with an Empty Array and therefore nothing shows.
I have done a bit of looking into it but cant find a conclusive way of managing the notification of the UI thread that an activity is done.
Would really appericiate any advice on this one.
You need to fix your design.
On post execute, use local broadcast to notify your MainActivity that the AsyncTask is done.
Try using a separate thread to process your data. I use a ListView in stead of a RecyclerView, but the principle is the same.
I have no problems with jolting views.
protected void onPostExecute(String result) {
final String value = result;
// dismiss the dialog after getting all data
progressDialog.dismiss();
if (!value.isEmpty()) {
// updating UI from a new thread
runOnUiThread(new Runnable() {
public void run() {
// ListData is my custom class that holds my data
ArrayList<ListData> arrayDriverListData = new ArrayList<ListData>();
ListDataAdapter adapter = new ListDataAdapter(ListActivity.this, arrayListData);
ListData data;
boolean b = true;
try {
// My data is from a Json source from node 'history'
JSONObject object = new JSONObject(value);
JSONArray array = object.getJSONArray("history");
int len = array.length();
if (len > 0) {
for (int i = 0; i < len; i++) {
final JSONObject o = array.getJSONObject(i);
// Parse my data and add it to my adapter
adapter.add(data);
}
}
} catch (JSONException jex) {
Log.e(TAG, "" + jex.getMessage());
}
// setListAdapter is my call to update my list view
setListAdapter(adapter);
}
});
}
}
Now just update the UI thread
private void setListAdapter(ListDataAdapter adapter){
// my ListView
lvHistory.setAdapter(adapter);
}
im using the azure mobile service. I have some users in the db i want to authenticate, and in order to do that, I execute a query to get a User after you enter a username and a password and press OK. When OK is pressed, if all it's well an intent should be started. How can I display a ProgressDialog until the callback method of the executed query is completed?
EDIT: the problem is that i have a button(logIn button) and when you click it, it will build a query and execute it in an async task, hence my problem. If i just add a progress dialog the call flow will move on since from the onClickListener point of view, the action has finished.
Just show() it before you call the query and dismiss() it in the callback method.
As your using the AsyncTask to query the data , use the onPreExecute and onPostExecute methods to show/dismiss the ProgressDialog.
Create a class which extends the AsyncTask , like this . In the onPreExecute show the ProgressDialog and when your done with fetching the data in doInBackground , in onPostExecute dismiss the dialog
public class QueryTask extends AsyncTask<Void,Void,Object> {
private ProgressDialog progressDialog = null;
private final Context mContext;
public QueryTask(Context context) {
mContext = context;
}
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(mContext);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// do your stuff to query the data
return null;
}
#Override
protected void onPostExecute(Object result) {
progressDialog.dismiss();
// do your other stuff with the queried result
}
#Override
protected void onCancelled(Object result) {
progressDialog.dismiss();
}
}
Finally, when button onClick execute the task
new QueryTask(YourActivity.this).execute();
This example code was used by me to load all the events from an SQL database. Until the app gets the data from the server, a progress dialog is displayed to the user.
class LoadAllEvents extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Just a moment...");
pDialog.setIndeterminate(true);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_events,
"GET", params);
try {
// Checking for SUCCESS TAG
int success = json.getInt(CONNECTION_STATUS);
if (success == 1) {
// products found
// Getting Array of Products
Events = json.getJSONArray(TABLE_EVENT);
// looping through All Contacts
for (int i = 0; i < Events.length(); i++) {
JSONObject evt = Events.getJSONObject(i);
// Storing each json item in variable
id = evt.getString(pid);
group = evt.getString(COL_GROUP);
name = evt.getString(COL_NAME);
desc = evt.getString(COL_DESC);
date = evt.getString(COL_DATE);
time = evt.getString(COL_TIME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(pid, id);
map.put(COL_GROUP, group);
map.put(COL_NAME, name);
map.put(COL_DESC, desc);
map.put(COL_DATE, date);
map.put(COL_TIME, time);
// adding HashList to ArrayList
eventsList.add(map);
}
} else {
// Options are not available or server is down.
// Dismiss the loading dialog and display an alert
// onPostExecute
pDialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
getActivity().runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(getActivity(),
eventsList, R.layout.list_item, new String[] {
pid, COL_GROUP, COL_NAME, COL_DATE, COL_TIME },
new int[] { R.id.pid, R.id.group, R.id.name, R.id.header,
R.id.title2 });
setListAdapter(adapter);
}
});
}
hope this helps.
I just have some really quick question about AsyncTask
See this my AsyncTask and the class that is it in
public class ListView extends ListActivity {
ArrayList<HashMap<String, String>> questionList;
final String TAG_RESULTS = "results";
final String TAG_QUESTION_SUBJECT = "Subject";
final String TAG_QUESTION_NUMANSWERS = "NumAnswers";
final String TAG_QUESTION = "question";
final String TAG_QUESTION_CONTENT = "Content";
final String TAG_QUESTION_CHOSENANSWER = "ChosenAnswer";
final String TAG_ANSWERS = "Answers";
final String TAG_ANSWER = "Answer";
final String TAG_ANSWERS_CONTENT = "content";
final String TAG_QUERY = "query";
final String TAG_COUNT = "count";
ProgressDialog pDialog;
LoadAllData mTask;
JSONArray question = null;
android.widget.ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.listview);
questionList = new ArrayList<HashMap<String, String>>();
mTask = new LoadAllData();
mTask.execute();
}
#Override
protected void onListItemClick(android.widget.ListView l, View v, int pos, long id) {
super.onListItemClick(l, v, pos, id);
HashMap<String, String> item = questionList.get(pos);
Intent i = new Intent(ListView.this, SingleListItem.class);
i.putExtra(TAG_QUESTION_SUBJECT, item.get(TAG_QUESTION_SUBJECT));
i.putExtra(TAG_QUESTION_CONTENT, item.get(TAG_QUESTION_CONTENT));
i.putExtra(TAG_QUESTION_CHOSENANSWER, item.get(TAG_QUESTION_CHOSENANSWER));
startActivity(i);
}
#Override
public void onBackPressed() {
if (mTask != null && mTask.getStatus() != AsyncTask.Status.FINISHED)
{
mTask.cancel(true);
}
super.onBackPressed();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
if (mTask != null && mTask.getStatus() != AsyncTask.Status.FINISHED)
{
mTask.cancel(true);
}
super.onDestroy();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
if (pDialog != null)
{
if(pDialog.isShowing())
{
pDialog.dismiss();
}
super.onPause();
}
}
class LoadAllData extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ListView.this);
pDialog.setMessage("Loading Data. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... args) {
pDialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
public void onCancel(DialogInterface dialog) {
mTask.cancel(true);
finish();
}
});
try {
Intent in = getIntent();
String searchTerm = in.getStringExtra("TAG_SEARCH");
String query = URLEncoder.encode(searchTerm, "utf-8");
String URL = "http://example.com";
JSONParsser jParser = new JSONParsser();
JSONObject json = jParser.readJSONFeed(URL);
try {
JSONArray questions = json.getJSONObject("all").getJSONArray("questions");
for(int i = 0; i < questions.length(); i++) {
JSONObject question = questions.getJSONObject(i);
String Subject = question.getString(TAG_QUESTION_SUBJECT);
String ChosenAnswer = question.getString(TAG_QUESTION_CHOSENANSWER);
String Content = question.getString(TAG_QUESTION_CONTENT);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_QUESTION_SUBJECT, Subject);
map.put(TAG_QUESTION_CONTENT, Content);
map.put(TAG_QUESTION_CHOSENANSWER, ChosenAnswer);
questionList.add(map);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String file_URL) {
if(file_URL!=null && file_URL.equals("0")) {
pDialog.dismiss();
Toast.makeText(ListView.this, "No data found", Toast.LENGTH_SHORT).show();
finish();
}else{
if (pDialog != null && pDialog.isShowing()) pDialog.dismiss();
ListAdapter adapter = new SimpleAdapter(getBaseContext(), questionList,
R.layout.listelements,
new String[] { TAG_QUESTION_SUBJECT }, new int[] {
R.id.Subject,});
setListAdapter(adapter);
}}}
Now the question I wanted to ask is if I take my AsyncTask out of this current activity and put it in a different file, will it make the execution of my doInBackGround method faster. I am asking this because when my AsyncTask is executing, it takes quite some time to finish and also in my logcat this message 09-24 20:12:55.928: I/Choreographer(824): Skipped 195 frames! The application may be doing too much work on its main thread. fills up my whole logcat when the AsyncTask is executing. I just want to know will It make a difference if I move it.
I just want to know will It make a difference if I move it.
No, it will not.
Moreover, the behavior of doInBackground() is not the source of your difficulty. It is something else, perhaps your onPostExecute(). The error is very explicit about your problem ("may be doing too much work on its main thread"), and doInBackground() does its work on another thread.
Are you sure that this code block belongs to doInbackground method ?
pDialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
public void onCancel(DialogInterface dialog) {
mTask.cancel(true);
finish();
});
The error clearly points that you are doing extra work not suitable for UI thread (which is not clear in your code above)
Regarding updated code - it still isn't clear where the problem is.
I suggest you go through the background code and look for anything touching the activity or UI - there might be some obscure problem caused by issuing UI thread requests on the background thread. setOnCancelListener() is one. getIntent() is another. Comment them out and see what happens.
Then start breaking it down. Comment out bits of code to remove them from the equation and see if it changes anything.
It's going to take a bit of hunting at this point, so the smaller you can make the errant code the better. Eventually you'll figure out what is causing the problem, and from that you can figure out why.
I currently have this class below which parses json urls and loads images and texts into a listview with the help of the Lazy Adapter Class and background thread.
Each list item consists of an image view and 2 text views.
I want to create pop up boxes (alert dialog) for each of the generated list items. The alert dialog will have options which will call other applications.
My question :
Would it be wise to code this alert dialog functionality in this class? I'm worried that there is a lot of stuff currently being done in the background and it might affect the app's functionality.
If not could anyone suggest another way to do it. thanks.
Json Activity Class :
public class JsonActivity extends SherlockActivity{
private ProgressDialog progressDialog;
// JSON Node names
static final String TAG_NAME = "name";
static final String TAG_IMAGEURL = "imageurl";
ListView list;
LazyAdapter adapter;
String chartUrl;
String[] urlNames = new String[] {
"urls..."
};
// chartItemList is the array list that holds the chart items
ArrayList<HashMap<String, String>> chartItemList = new ArrayList<HashMap<String,
String>>();
//Holds imageurls
ArrayList<String> imageurls = new ArrayList<String>();
JsonParser Parser = new JsonParser();
// JSONArray
JSONArray chartItems = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chart);
//Get the bundle
Bundle bundle = getIntent().getExtras();
//Extract the data from the bundle
int chartIndex = bundle.getInt("chartIndex");
String chartUrl = urlNames[chartIndex];
setTitle(bundle.getString("chartname"));
//url from where the JSON has to be retrieved
String url = chartUrl;
//Check if the user has a connection
ConnectivityManager cm = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null) {
if (!info.isConnected()) {
Toast.makeText(this, "Please check your connection and try again.",
Toast.LENGTH_SHORT).show();
}
//if positive, fetch the articles in background
else new getChartItems().execute(chartUrl);
}
//else show toast
else {
Toast.makeText(this, "Please check your connection and try again.",
Toast.LENGTH_SHORT).show();
}
}
class getChartItems extends AsyncTask<String, String, String> {
// Shows a progress dialog while setting up the background task
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(JsonActivity.this);
progressDialog.setMessage("Loading chart...");
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.show();
}
//Gets the json data for chart items data and presents it in a list view
#Override
protected String doInBackground(String... args) {
String json = Parser.getJSONFromUrl(args[0]);
String imageurl;
String rank;
String name;
String url;
try{
chartItems = new JSONArray(json);
JSONObject json_data=null;
for(int i=0;i<chartItems.length();i++){
json_data = chartItems.getJSONObject(i);
//Retrieves the value of the name from the json object
name=json_data.getString("name");
//Retrieves the image url for that object and adds it to an arraylist
imageurl=json_data.getString("imageurl");
//imageurls.add(imageurl);
HashMap<String, String> hashMap = new HashMap<String, String>();
// adding each child node to HashMap key => value
//hashMap.put(TAG_RANK, rank);
hashMap.put(TAG_NAME, name);
hashMap.put(TAG_IMAGEURL, imageurl);
// adding HashMap to ArrayList
chartItemList.add(hashMap);
}
;
}
catch (JSONException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
public void run() {
list=(ListView)findViewById(R.id.list);
// Getting adapter by passing xml data ArrayList
adapter = new LazyAdapter(JsonActivity.this, chartItemList);
list.setAdapter(adapter);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
});
return null;
}
//Removes the progress dialog when the data has been fetched
protected void onPostExecute(String args) {
progressDialog.dismiss();
}
}
}
My answer for this is Yes, it is wise enough to implement one more level network communication as far as your use case justifies it.
This depends on communication channel (EDGE/ 3G/ 4G/ WiFi) and use case of the application. Technically it is pretty much possible as far as you are doing this in background. It also depends on the size of the list which you are loading. Best way to check this is by implementing plug-able code and try it out.