Showing Progress Dialog while loading data from the internet - java

I want to show a Progress Dialog on button click in my app while data is loaded from the internet. I can't get it to work, could someone give me some tips on where to put the Dialog function?
This is my AsyncTask method:
private class GetTweets extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... twitterURL) {
//start building result which will be json string
StringBuilder tweetFeedBuilder = new StringBuilder();
//should only be one URL, receives array
for (String searchURL : twitterURL) {
HttpClient tweetClient = new DefaultHttpClient();
try {
//pass search URL string to fetch
HttpGet tweetGet = new HttpGet(searchURL);
//execute request
HttpResponse tweetResponse = tweetClient.execute(tweetGet);
StatusLine searchStatus = tweetResponse.getStatusLine();
if (searchStatus.getStatusCode() == 200) {
//get the response
HttpEntity tweetEntity = tweetResponse.getEntity();
InputStream tweetContent = tweetEntity.getContent();
InputStreamReader tweetInput = new InputStreamReader(tweetContent);
BufferedReader tweetReader = new BufferedReader(tweetInput);
String lineIn;
while ((lineIn = tweetReader.readLine()) != null) {
tweetFeedBuilder.append(lineIn);
}
}
else
tweetDisplay.setText("Error!");
}
catch(Exception e){
tweetDisplay.setText("Error!");
e.printStackTrace();
}
}
//return result string
return tweetFeedBuilder.toString();
}
protected void onPostExecute(String result) {
//start preparing result string for display
StringBuilder tweetResultBuilder = new StringBuilder();
try {
//get JSONObject from result
JSONObject resultObject = new JSONObject(result);
//get JSONArray contained within the JSONObject retrieved - "results"
JSONArray tweetArray = resultObject.getJSONArray("results");
//loop through each item in the tweet array
for (int t=0; t<tweetArray.length(); t++) {
//each item is a JSONObject
JSONObject tweetObject = tweetArray.getJSONObject(t);
tweetResultBuilder.append(tweetObject.getString("from_user")+": ");
tweetResultBuilder.append(tweetObject.get("text")+"\n\n");
}
}
catch (Exception e) {
tweetDisplay.setText("Error!");
e.printStackTrace();
}
//check result exists
if(tweetResultBuilder.length()>0)
tweetDisplay.setText(tweetResultBuilder.toString());
else
tweetDisplay.setText("no results!");
}
}

In the AsyncTask class use onPrexecute method to display progress dialog and use onPostExecute to dismiss it:
#Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(YOUR_ACTIVITY_CLASS_NAME.this);
pDialog.setMessage("Please Wait");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected void onPostExecute(String str)
{
// Dismiss the dialog once finished
pDialog.dismiss();
}
Don't forget to define pDialog before you call it:
ProgresDialog pDialog;

Related

Set Progressbar with percentage when data download from json get method in android

I want to show progress bar with percentage of the download the data from json. Right now I am getting the data from the url and store in the local database in other class and this class called in MainActivity. Now I want to show the progressbar with percentage of the download file from json url.
This is my code
public class Web_Product {
Context context;
List<Variable> list = new ArrayList<Variable>();
//List<Variable> list1;
String url = "https://api.androidhive.info/progressdialog/hive.jpg";
URL url1 = null;
InputStream is1 = null;
String product_id, product_name, product_image;
private byte[] logoImage;
private JSONArray jsonArray;
public Web_Product(Context context) {
this.context = context;
Log.e("hello", "Message");
}
public void product_insert() {
// new AsyncLogin().execute();
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.e("TEST", "jsonStr:-" + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonRootObject = new JSONObject(jsonStr);
//Get the instance of JSONArray that contains JSONObjects
JSONArray jsonArray = jsonRootObject.optJSONArray("product");
//Iterate the jsonArray and print the info of JSONObjects
for (int i = 0; i < jsonArray.length(); i++) {
Log.e("TEST_P", "in");
JSONObject details = jsonArray.getJSONObject(i);
product_id = details.getString("product_id");
product_name = details.getString("product_name");
product_image = details.getString("product_image");
logoImage = getLogoImage(product_image);
Variable variable_object = new Variable();
variable_object.setProduct_id(product_id);
variable_object.setProduct_name(product_name);
variable_object.setProduct_url_image(logoImage);
list.add(variable_object);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
Log.e("TEST1", " Ritunjay" + list.size());
Product_data product = new Product_data(context);
product.Insert_Product(list);
Log.e("listpo", "" + list);
}
public JSONArray json_web_prod() {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.e("TEST", "jsonStr:-" + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonRootObject = new JSONObject(jsonStr);
//Get the instance of JSONArray that contains JSONObjects
jsonArray = jsonRootObject.optJSONArray("product");
} catch (JSONException e) {
e.printStackTrace();
}
}
return jsonArray;
}`
Main Activity
class add extends AsyncTask<String, Integer, String> {
ProgressDialog mProgressDialog;
#Override
protected void onProgressUpdate(Integer... values) {
mProgressDialog.setProgress(values[0]);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setTitle("Downloading Data...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
#Override
protected void onPostExecute(String aVoid) {
super.onPostExecute(aVoid);
mProgressDialog.dismiss();
flag = true;
Intent intent = getIntent();
startActivity(intent);
finish();
Log.e("flag , post", "" + flag);
}
#Override
protected String doInBackground(String... params) {
web_product = new Web_Product(getApplicationContext());
web_product.product_insert();
return null;
}
}`
In doInBackground , you need to publishProgress also . So that your progress bar can updated , like this
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
Here totalSize will help you to calculate your total remaining data and publishProgress will public it .

How i can println the statuscode in display with a toast when the request is fail?

Need to println HttpResponse response if the conexion is fail
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
private ProgressDialog pDialog;
#Override
protected String doInBackground(String... params) {
return GET();
}
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Iniciando sesiĆ³n...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
}
public String GET() {
String url = "http://"+ippref+":8080/Activo/webresources/activo.entities.coreusuario/usuarios/" + usuario_ws + "/" +contrasenia_ws+ "";
String result = "";
BufferedReader inStream = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet(url);
HttpResponse response = httpClient.execute(httpRequest);
response.getStatusLine().getStatusCode();
inStream = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent()));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = inStream.readLine()) != null) {
buffer.append(line);
}
inStream.close();
result = buffer.toString();
respuesta_ws = Integer.valueOf(result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
Need printl the statuscode
Check for return status. If its value is not 200 then its a failure and toast it.
if(response.getStatusLine().getStatusCode()!=200){
Toast.makeText(getApplicationContext(),
"Request failure!",
Toast.LENGTH_LONG).show();
}
Use this :
Toast.makeText(getApplicationContext(),
response.getStatusLine().getStatusCode(),
Toast.LENGTH_LONG).show();
import android.widget.Toast
And you can change time of toast by changing Toast.LENGTH_LONG
Of course if you want to only show toast when http response is bad,then add the logic for checking the error cases and make toast there.
Hope this helps. :)

App crashes when getting data from JSON

I'm trying to retrieve data from JSON but it crashes whenever I try to retrieve data from my Android app.
// Intent i = new Intent(this,MainMenu.class);
// startActivity(i);
new AsyncTask<Void, Void, Void>()
{
ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = new ProgressDialog(JobScreen.this);
progressDialog.setMessage("Getting Items..");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... voids)
{
try
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet post = new HttpGet("http://users.abdullahadhaim.com/users/WebServiceResturant.asmx/login?userName=abood&Password=123");
HttpResponse response = httpClient.execute(post);
String responseString = EntityUtils.toString(response.getEntity());
JSONArray jsonArray = new JSONArray(responseString);
JSONObject jsonObject = jsonArray.getJSONObject(0);
ed1.setText(jsonObject.getString("UserName"));
Log.e("Done", "Done");
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(JobScreen.this, "Faild", Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid)
{
super.onPostExecute(aVoid);
progressDialog.dismiss();
}
}.execute();
It looks like the problem is that you're calling ed1.setText() in the background thread.
Just move that call to onPostExecute(), and return the String value that you need from doInBackground().
Also remove the Toast from doInBackground(), and move it to onPostExecute() to be displayed if the return value of doInBackground() is null;
I just ran this, and it worked fine, and set the text to abood:
//use String for last parameter here:
new AsyncTask<Void, Void, String>() {
ProgressDialog progressDialog;
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(JobScreen.this);
progressDialog.setMessage("Getting Items..");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
}
//String return value:
protected String doInBackground(Void... unused) {
try
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet post = new HttpGet("http://users.abdullahadhaim.com/users/WebServiceResturant.asmx/login?userName=abood&Password=123");
HttpResponse response = httpClient.execute(post);
String responseString = EntityUtils.toString(response.getEntity());
JSONArray jsonArray = new JSONArray(responseString);
JSONObject jsonObject = jsonArray.getJSONObject(0);
Log.e("Done", "Done");
//return the String you need:
return jsonObject.getString("UserName");
}
catch (Exception e)
{
e.printStackTrace();
//remove this Toast:
//Toast.makeText(MainActivity.this, "Faild", Toast.LENGTH_SHORT).show();
}
return null;
}
//String parameter
protected void onPostExecute(String username) {
super.onPostExecute(username);
if (username == null){
//Toast if username is null
Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
else{
//Set the text here with the String received:
ed1.setText(username);
}
progressDialog.dismiss();
}
}.execute();

How to use common request and response in soap asynctask throughout multiple activities android?

I am using Soap request and response using asynctask. I am sending json request and fetching the response. But How to use this asynctask to perform request and response in common class. So that I can use in multiple activites by passing request and fetch response. Please provide me solution. How to solve this?
So far I am doing like this. I wrote for single asynctask. But for another service call, I need to perform another asynctask. How to use this in common and perform.
I have commented in code for better understanding. Here is my code.
class A extend Activity{
private String sessionId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.sortfilterclick);
new CommonElement().execute();
}
class CommonElement extends AsyncTask<String, String, String> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(CommonElement.this);
dialog.show();
dialog.setCancelable(false);
}
#Override
protected String doInBackground(String... args) {
try {
// these are all common
SoapSerializationEnvelope env = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER11);
env.dotNet = false;
env.xsd = SoapSerializationEnvelope.XSD;
env.enc = SoapSerializationEnvelope.ENC;
HttpTransportSE androidHttpTransport = new HttpTransportSE(Constants.API_URL);
sessionId = Utils.readPreferences(CommonElement.this,Constants.SESSION_ID, null);
if (sessionId == null) {
SoapObject request = new SoapObject(Constants.NAMESPACE, "login");
request.addProperty("username", "Clothing");
request.addProperty("apiKey", "Clothing");
env.setOutputSoapObject(request);
androidHttpTransport.call("", env);
Object result = env.getResponse();
sessionId = result.toString();
Utils.savePreferences(SortFilterPopupActivity.this,
Constants.SESSION_ID, sessionId);
}// till this it's common
//here json reuest datas varies in json.put()...
SoapObject requests = new SoapObject(Constants.NAMESPACE, "call");//these are common
requests.addProperty("sessionId", sessionId);//these are common
requests.addProperty("resourcePath","sortap.Action"); //this will change for every property
JSONObject json = new JSONObject();// these will change
json.put("page", "1");
json.put("limit", "10");
json.put("name", sortName);
json.put("order", sortOrder);
json.put("id", "3");
json.put("cate_id", "4");
String params = json.toString();
requests.addProperty("args", params);
env.setOutputSoapObject(requests);
androidHttpTransport.call("", env);
Object results = env.getResponse();
//based on various request and response this varies.
if (results.toString() != null) {
JSONObject jsono = new JSONObject(results.toString());
JSONArray jarray = jsono.getJSONArray("results");
for (int i = 0; i < jarray.length(); i++) {
JSONObject object = jarray.getJSONObject(i);
String id = object.getString("id");
String productName = object.getString("product_name");
String imageUrl = object.getString("image_url");
int productPrice = object.getInt("price");
}
}
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.cancel();
}

Json response is very slow android

I'm writing an Android application which will occasionally need to download a json string of around 1MB and containing around 1000 elements, and parse each of these into an SQLite database, which I use to populate a ListActivity.
Even though the downloading and parsing isn't something that needs to be done on every interaction with the app (only on first run or when the user chooses to refresh the data), I'm still concerned that the parsing part is taking too long, at around two to three minutes - it seems like an eternity in phone app terms!
I am using this code... :-
public class CustomerAsyncTask extends AsyncTask<String, Integer, String> {
private Context context;
private String url_string;
private String usedMethod;
private String identifier;
List<NameValuePair> parameter;
private boolean runInBackground;
AsynTaskListener listener;
private Bitmap bm = null;
public ProgressDialog pDialog;
public String entityUtil;
int index = 0;
public static int retry = 0;
private String jsonString = "";
private String DialogString = "";
// use for AsyncTask web services-----------------
public CustomerAsyncTask(Context ctx, String url, String usedMethod,
String identifier, boolean runInBackground, String DialogString,
List<NameValuePair> parameter, AsynTaskListener callack) {
this.context = ctx;
this.url_string = url;
this.usedMethod = usedMethod;
this.identifier = identifier;
this.parameter = parameter;
this.runInBackground = runInBackground;
this.listener = callack;
this.DialogString = DialogString;
}
public CustomerAsyncTask(Context ctx, String url, String usedMethod,
String identifier, boolean runInBackground,
List<NameValuePair> parameter, AsynTaskListener callack, Bitmap bm) {
this.context = ctx;
this.url_string = url;
this.usedMethod = usedMethod;
this.identifier = identifier;
this.parameter = parameter;
this.runInBackground = runInBackground;
this.listener = callack;
this.bm = bm;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
if (runInBackground)
initProgressDialog(DialogString);
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#SuppressWarnings("deprecation")
#Override
protected String doInBackground(String... params) {
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 10000; // mili second
HttpConnectionParams.setConnectionTimeout(httpParameters,
timeoutConnection);
int timeoutSocket = 10000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
try {
HttpResponse response = null;
if (usedMethod.equals(GlobalConst.POST)) {
HttpPost httppost = new HttpPost(this.url_string);
httppost.setHeader("Content-Type",
"application/x-www-form-urlencoded");
// Customer Login MObile
if (identifier.equals("Customer_Login")) {
if (params.length > 0) {
parameter = new ArrayList<NameValuePair>();
parameter.add(new BasicNameValuePair("cus_mob",
params[0]));
}
httppost.setEntity(new UrlEncodedFormEntity(parameter));
// Customer Verify Code
} else if (identifier.equals("Customer_mob_verify")) {
if (params.length > 0) {
parameter = new ArrayList<NameValuePair>();
parameter.add(new BasicNameValuePair("cus_verify",
params[0]));
parameter.add(new BasicNameValuePair("cus_mobile",
params[1]));
}
httppost.setEntity(new UrlEncodedFormEntity(parameter));
} else if (identifier.equals("Dashboard")) {
if (params.length > 0) {
parameter = new ArrayList<NameValuePair>();
parameter.add(new BasicNameValuePair("cus_id",
params[0]));
}
httppost.setEntity(new UrlEncodedFormEntity(parameter));
}
response = (HttpResponse) httpClient.execute(httppost);
} else if (usedMethod.equals(GlobalConst.GET)) {
HttpGet httpput = new HttpGet(this.url_string);
httpput.setHeader("Content-Type",
"application/x-www-form-urlencoded");
response = (HttpResponse) httpClient.execute(httpput);
}
// Buffer Reader------------------------
InputStream inputStream = null;
String result = null;
try {
HttpEntity entity1 = response.getEntity();
inputStream = entity1.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
} finally {
try {
if (inputStream != null)
inputStream.close();
} catch (Exception squish) {
}
}
jsonString = result;
} catch (ClientProtocolException e) {
e.printStackTrace();
return AsyncResultConst.CONNEERROR;
} catch (IOException e) {
e.printStackTrace();
return AsyncResultConst.CONNEERROR;
} catch (Exception e1) {
e1.printStackTrace();
return AsyncResultConst.EXCEPTION;
} finally {
httpClient.getConnectionManager().shutdown();
}
return AsyncResultConst.SUCCESS;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
if (runInBackground)
pDialog.dismiss();
if (result.equals(AsyncResultConst.SUCCESS)) {
listener.onRecieveResult(identifier, jsonString);
} else if (result.equals(AsyncResultConst.PARSINGERROR)) {
// showAlertMessage(context, "Error", "Parsing Error", null);
listener.onRecieveException(identifier, result);
} else {
if (retry < 0) {
retry++;
new CustomerAsyncTask(context, url_string, usedMethod,
identifier, runInBackground, DialogString, parameter,
listener).execute("");
} else {
// showAlertMessage(context, "Error", "Connection Error", null);
listener.onRecieveException(identifier, result);
}
}
super.onPostExecute(result);
}
private void initProgressDialog(String loadingText) {
pDialog = new ProgressDialog(this.context);
pDialog.setMessage(loadingText);
pDialog.setCancelable(false);
pDialog.show();
}
}
Don't use Async-task in such case, use native java thread here.
new Thread(new Runnable() {
public void run() {
// Do your work .....
}
}).start();
When need to update UI. Yes! Android won't allow you to do that. so... solution is: USE Handler for that :)
Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
// Do Update your UI
}
});
Use AsyncTask for:
Simple network operations which do not require downloading a lot of
data Disk-bound tasks that might take more than a few milliseconds
Use Java threads for:
Network operations which involve moderate to large amounts of data (either uploading or downloading)
High-CPU tasks which need to be run in the background
Any task where you want to control the CPU usage relative to the GUI thread
You could use Google's GSON as well.
Try to use Jackson Library to manage your JSON. It is really efficient. You can find it here : http://mvnrepository.com/artifact/org.codehaus.jackson/jackson-jaxrs
I am using it for a 400KB file is less than 1 second.
If you want a tuto this one looks good http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/
This is how is read JSON into my listview in my app. The result is processed to my app in an average of 3 seconds on Wi-Fi and 5 seconds on 3G:
public class CoreTeamFragment extends ListFragment {
ArrayList> membersList;
private String url_all_leaders = //URL goes here
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
// JSON Node names
private static final String CONNECTION_STATUS = "success";
private static final String TABLE_TEAM = "CoreTeam";
private static final String pid = "pid";
private static final String COL_NAME = "CoreTeam_Name";
private static final String COL_DESC = "CoreTeam_Desc";
private static final String COL_PIC = "CoreTeam_Picture";
JSONArray CoreTeam = null;
public static final String ARG_SECTION_NUMBER = "section_number";
public CoreTeamFragment() {
}
public void onStart() {
super.onStart();
membersList = new ArrayList<HashMap<String, String>>();
new LoadAllMembers().execute();
// selecting single ListView item
ListView lv = getListView();
// Lauching the Event details screen on selecting a single event
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String ID = ((TextView) view.findViewById(R.id.leader_id))
.getText().toString();
Intent intent = new Intent(view.getContext(),
CoreTeamDetails.class);
intent.putExtra(pid, ID);
view.getContext().startActivity(intent);
}
});
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_coreteam,
container, false);
return rootView;
}
class LoadAllMembers 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_leaders,
"GET", params);
try {
// Checking for SUCCESS TAG
int success = json.getInt(CONNECTION_STATUS);
if (success == 1) {
// products found
// Getting Array of Products
CoreTeam = json.getJSONArray(TABLE_TEAM);
// looping through All Contacts
for (int i = 0; i < CoreTeam.length(); i++) {
JSONObject ct = CoreTeam.getJSONObject(i);
// Storing each json item in variable
String id = ct.getString(pid);
String name = ct.getString(COL_NAME);
String desc = ct.getString(COL_DESC);
String pic = ct.getString(COL_PIC);
// 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_NAME, name);
map.put(COL_DESC, desc);
map.put(COL_PIC, pic);
// adding HashList to ArrayList
membersList.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(),
membersList,
R.layout.coreteam_item,
new String[] { pid, COL_NAME, COL_DESC, COL_PIC },
new int[] { R.id.leader_id, R.id.leaderName,
R.id.photo });
setListAdapter(adapter);
}
});
}
}
}
Use Volley or Retrofit lib.
Those lib are increasing the speed.
Volley:
JsonObjectRequest channels = new JsonObjectRequest(Method.POST,
Constants.getaccountstatement + Constants.key, statement_object,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject arg0) {
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError e) {
Toast.makeText(context, "Error", Toast.LENGTH_SHORT).show();
}

Categories