Android Horizontal Progress bar not working for getting JSON - android

I am trying to setup Progress Bar to getting large amount of JSON from Server by showing percentage but it not working.I have don't idea regarding this.So Please help me from scratch.
Test.java
public class Test extends AppCompatActivity {
// Progress Dialog
private ProgressDialog pDialog;
private Toolbar mToolbar;
public static final int progress_bar_type = 0;
List<NameValuePair> params;
// File url to download
private static String file_url = "http://dcntv.in:3035/area_list";
Connect cn = new Connect();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("opid", "19"));
new DownloadFileFromURL().execute(file_url);
}
/**
* Background Async Task to download file
* */
class DownloadFileFromURL extends AsyncTask<String, String, String> {
/**
* Before starting background thread
* Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String...urls) {
return cn.readJSONFeed(urls[0],params);
}
/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}
/**
* After completing background task
* Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String result) {
Dialog d = new Dialog(Test.this);
TextView tv = new TextView(Test.this);
tv.setText(result.toString());
ScrollView sv = new ScrollView(Test.this);
sv.addView(tv);
d.setContentView(sv);
d.show();
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);
}
}
/**
* Showing Dialog
* */
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type: // we set this to 0
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}
}
Connect.java (for cn Object)
public class Connect {
public String readJSONFeed(String URL,List<NameValuePair> params) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
try {
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpClient.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
}
return stringBuilder.toString();
}
}

Progress Bar popup but progress count not working
Because not calling publishProgress method from doInBackground to publish progress update on UI Thread.
Publish update using current code make following changes:
1. Add one more parameter in readJSONFeed to get object of DownloadFileFromURL :
public String readJSONFeed(String URL,List<NameValuePair> params,
DownloadFileFromURL objDownloadFileFromURL) {
... ...
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
// add this line
objDownloadFileFromURL.publishProgress(stringBuilder.length());
}
....
}
2. Pass DownloadFileFromURL.this when calling readJSONFeed from doInBackground :
return cn.readJSONFeed(urls[0],params,DownloadFileFromURL.this);

Related

How to get correct entity content length to show progress in progress dialog?

I want to upload multiple image files using Android MultiPart Entity via AsyncTask in an activity. When I attempt to upload single image file then the progress dialog shows correct progress and as soon as 100% progress is reached the dialog dismisses and does the further tasks. But, when I am attempting to upload multiple image files it shows the 100% progress and the progress dialog is stuck till other image files are being uploaded to server. I add the multiple image files to entity using a for loop. But when I try to get the content length it seems that I am getting wrong value.
#SuppressWarnings("deprecation")
private class UploadAttachments extends AsyncTask<Void, Integer, String> {
ProgressDialog pDialog;
long totalSize = 0;
int statusCode;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(RegistrationActivity.this);
pDialog.setMessage(getString(R.string.label_upload_attachments));
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setMax(mFilePaths.size());
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected void onProgressUpdate(Integer... progress) {
pDialog.setProgress(progress[0]);
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Network.URL_UPLOAD);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
for (int i = 0; i < mFilePaths.size(); i++) {
entity.addPart("image" + i, new FileBody(new File(mFilePaths.get(i))));
mPrefix += 1;
entity.addPart("prefix" + i, new StringBody(String.valueOf(mPrefix)));
}
totalSize = entity.getContentLength();
entity.addPart("count", new StringBody(String.valueOf(mFilePaths.size())));
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
responseString = getString(R.string.label_upload_successful);
} else {
responseString = getString(R.string.error_network_error);
}
} catch (IOException e) {
responseString = getString(R.string.error_network_error);
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
if (mToast != null) mToast.cancel();
mToast = makeText(getApplicationContext(), result, Toast.LENGTH_SHORT);
mToast.show();
mPreferences.clearRegDetails();
Intent intent = new Intent(RegistrationActivity.this, MainActivity.class);
startActivity(intent);
}
}
Please have a look. Please help me on this! Thanks.

Multiple progress bar on image

I have multiple images and i am uploading on php server using asynctask my problem is i want to show circular progress bar on every image individually like whatsapp but don't know how to do. here is my code
/**
* Uploading the file to server
* */
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
}
#Override
protected String doInBackground(Void... params)
{
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(serviceurl+"conversations.php");
try {
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
/* example for setting a HttpMultipartMode */
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
File sourceFile = new File(imgDecodableString);
// Progress listener - updates task's progress
MyHttpEntity.ProgressListener progressListener =
new MyHttpEntity.ProgressListener() {
#Override
public void transferred(float progress) {
publishProgress((int) progress);
}
};
// Adding file data to http body
entity.addPart("file", new FileBody(sourceFile));
// Extra parameters if you want to pass to server
entity.addTextBody("from_user",(prefid.getString("userid", null)),ContentType.TEXT_PLAIN);
entity.addTextBody("to_user",touser_id,ContentType.TEXT_PLAIN);
entity.addTextBody("message_type", msg_type,ContentType.TEXT_PLAIN);
httppost.setEntity(new MyHttpEntity(entity.build(),
progressListener));
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
I am calling above code in my main activity and i am using this to upload images and video.
please help me how i can set progress bar on multiple images same as in whatsapp
Thanks
You could pass the View to the AsyncTask, by create new constructor then show/hide it, notice that you have to runOnUIThread for the view.
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
ImageView iv_loading;
public UploadFileToServer(ImageView iv_loading){
this.iv_loading = iv_loading;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
runOnUiThread(new Runnable() {
#Override
public void run() {
iv_loading.setVisibility(View.VISIBLE);
}
}
);
}
...
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
runOnUiThread(new Runnable() {
#Override
public void run() {
iv_loading.setVisibility(View.GONE);
}
}
);
}
}

How can I get filleUploaded URL as string from async task in android

I am uploading an image on server by using async task and in the end I want to return value of uploaded file url. How can I do that
I am calling asynctask as
new Config.UploadFileToServer(loginUserInfoId, uploadedFileURL).execute();
and my asynctask function is as:
public static final class UploadFileToServer extends AsyncTask<Void, Integer, String> {
String loginUserInfoId = "";
String filePath = "";
long totalSize = 0;
public UploadFileToServer(String userInfoId, String url){
loginUserInfoId = userInfoId;
filePath = url;
}
#Override
protected void onPreExecute() {
// setting progress bar to zero
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
// updating progress bar value
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.HOST_NAME + "/AndroidApp/AddMessageFile/"+loginUserInfoId);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(filePath);
// Adding file data to http body
entity.addPart("file", new FileBody(sourceFile));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
responseString = responseString.replace("\"","");
return responseString;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
Try my code as given below.
public Result CallServer(String params)
{
try
{
MainAynscTask task = new MainAynscTask();
task.execute(params);
Result aResultM = task.get(); //Add this
}
catch(Exception ex)
{
ex.printStackTrace();
}
return aResultM;//Need to get back the result
}
You've almost got it, you should do only one step. As I can see, you are returning the result at the doInBackground method (as a result of calling uploadFile). Now, this value is passed to the onPostExecute method, which is executed on the main thread. In its body you should notify components, which are waiting for result, that result is arrived. There are a lot of methods to do it, but if you don't want to used 3rd party libs, the simplest one should be to inject listener at the AsyncTask constructor and call it at the onPostExecute. For example, you can declare the following interface:
public interface MyListener {
void onDataArrived(String data);
}
And inject an instance implementing it at the AsyncTask constructor:
public UploadFileToServer(String userInfoId, String url, MyListener listener){
loginUserInfoId = userInfoId;
filePath = url;
mListener = listener;
}
Now, you can simply use it at the onPostExecute:
#Override
protected void onPostExecute(String result) {
listener.onDataArrived(result);
super.onPostExecute(result); //actually `onPostExecute` in base class does nothing, so this line can be removed safely
}
If you are looking for a more complex solutions, you can start from reading this article.

ProgressBar in asynctask is not showing on upload

Can someone tell me, why progressbar isnt showing when picture is being uploaded. I copied asynctask structure from my old project where it works. In my old project i use asynctask to download pictures from web server, and to show progressbar while downloading.
Here is my code:
public class PreviewPostActivity extends Activity {
ImageView imageView;
TextView tvComment;
Button submit;
MyLocationListener locationListener;
List<NameValuePair> list = new ArrayList<NameValuePair>();
private final String url = "***"; //Url of php script
ProgressDialog pDialog;
String responseMessage="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.preview_post);
Intent intent = this.getIntent();
imageView = (ImageView)findViewById(R.id.imgPerview);
tvComment = (TextView)findViewById(R.id.txtPreviewComment);
submit = (Button)findViewById(R.id.btnPreviewSubmit);
Bitmap image = (Bitmap)intent.getParcelableExtra("picture");
String comment = intent.getStringExtra("comment");
locationListener = (MyLocationListener)intent.getSerializableExtra("location");
String imagePath = intent.getStringExtra("imagePath");
String date = intent.getStringExtra("date");
imageView.setImageBitmap(image);
tvComment.setText(comment);
//tvComment.append("\n"+locationListener.latitude + "\n"+locationListener.longitude);
list.add(new BasicNameValuePair("image", imagePath));
list.add(new BasicNameValuePair("comment", comment));
list.add(new BasicNameValuePair("longitude", Double.toString(locationListener.longitude)));
list.add(new BasicNameValuePair("latitude", Double.toString(locationListener.latitude)));
list.add(new BasicNameValuePair("date", date));
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new uploadPost().execute();
}
});
}
public void post(List<NameValuePair> nameValuePairs) {
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 100000);
HttpConnectionParams.setSoTimeout(httpParameters, 200000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
try {
MultipartEntity entity = new MultipartEntity();
for(int index=0; index < nameValuePairs.size(); index++) {
if(nameValuePairs.get(index).getName().equalsIgnoreCase("image")) {
// If the key equals to "image", we use FileBody to transfer the data
entity.addPart(nameValuePairs.get(index).getName(), new FileBody(new File(nameValuePairs.get(index).getValue()),"image/jpeg"));
} else {
// Normal string data
entity.addPart(nameValuePairs.get(index).getName(), new StringBody(nameValuePairs.get(index).getValue()));
}
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity httpEntity = response.getEntity();
String responseMessage = EntityUtils.toString(httpEntity);
tvComment.setText(responseMessage);
} catch (IOException e) {
e.printStackTrace();
}
}
class uploadPost extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(PreviewPostActivity.this);
pDialog.setMessage("Uploading post. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
//post(list);
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 100000);
HttpConnectionParams.setSoTimeout(httpParameters, 200000);
HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
try {
MultipartEntity entity = new MultipartEntity();
for(int index=0; index < list.size(); index++) {
if(list.get(index).getName().equalsIgnoreCase("image")) {
// If the key equals to "image", we use FileBody to transfer the data
entity.addPart(list.get(index).getName(), new FileBody(new File(list.get(index).getValue()),"image/jpeg"));
} else {
// Normal string data
entity.addPart(list.get(index).getName(), new StringBody(list.get(index).getValue()));
}
}
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost, localContext);
HttpEntity httpEntity = response.getEntity();
responseMessage = EntityUtils.toString(httpEntity);
//tvComment.setText(responseMessage);
} catch (IOException e) {
e.printStackTrace();
}
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
tvComment.setText(responseMessage);
pDialog.dismiss();
}
}
So when i hit button for upload, screen freezes and stay frozen until upload is complete, and progress bar isnt showing at all. Sometimes it shows, but its rly rear and i dont know why. I have tried calling Post() method from class in doInBackground body insted of whole code (code in body is the same as in post() method) but effect is the same, so i guess i didnt do something right in creating progressbar. But again i say i copied whole asynctask code from old project in witch it worked fine.
EDIT:
I just tryed creating progress bar in constructor of PreviewPostActivity.class and after that i made constructor for asynctask class but it still dosent work. I am rly confused becouse it worked in my old program.
Here is code from him:
class GetSlike extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(KlubSlikeActivity.this);
pDialog.setMessage("Ucitavanje u toku. Molimo vas sacekajte...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Getting product details in background thread
* */
protected String doInBackground(String... params) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
String id = Integer.toString(k.getId());
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("klub",id));
slikeUrl = JSONAdapter.getSlike(params);
gv.setAdapter(new SlikeAdapter(slikeUrl,KlubSlikeActivity.this));
}
});
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
Only thing changed is doInBackground body...
Edited:
Dialog is display after runOnUiThread() is executed.
I found this library which is perfect to accomplish the upload task and also provide a progress handler which could be used to set the value of a ProgressBar:
https://github.com/nadam/android-async-http
It could be used like the following... Set onClickHandler for the upload Button:
#Override
public void onClick(View arg0) {
try {
String url = Uri.parse("YOUR UPLOAD URL GOES HERE")
.buildUpon()
.appendQueryParameter("SOME PARAMETER IF NEEDED 01", "VALUE 01")
.appendQueryParameter("SOME PARAMETER IF NEEDED 02", "VALUE 02")
.build().toString();
AsyncHttpResponseHandler httpResponseHandler = createHTTPResponseHandler();
RequestParams params = new RequestParams();
// this path could be retrieved from library or camera
String imageFilePath = "/storage/sdcard/DCIM/Camera/IMG.jpg";
params.put("data", new File(imageFilePath));
AsyncHttpClient client = new AsyncHttpClient();
client.post(url, params, httpResponseHandler);
} catch (IOException e) {
e.printStackTrace();
}
}
then add this method to your activity code:
public AsyncHttpResponseHandler createHTTPResponseHandler() {
AsyncHttpResponseHandler handler = new AsyncHttpResponseHandler() {
#Override
public void onStart() {
super.onStart();
}
#Override
public void onProgress(int position, int length) {
super.onProgress(position, length);
progressBar.setProgress(position);
progressBar.setMax(length);
}
#Override
public void onSuccess(String content) {
super.onSuccess(content);
}
#Override
public void onFailure(Throwable error, String content) {
super.onFailure(error, content);
}
#Override
public void onFinish() {
super.onFinish();
}
};
return handler;
}
Run on ui thread in asynctask doinbackground() is not correct. Also you are returning null in doInBackground() and you have parameter file_url in onPostExecute(). Return value in doInbackground() recieve value in onPostExecute().
doInBackGround() runs in background so you cannot access or update ui here.
To update ui you can use onPostExecute().
Your AsyncTask should be something like below. You are doing it the wrong way.
http://developer.android.com/reference/android/os/AsyncTask.html. See the topic under The 4 steps
pd= new ProgressDialog(this);
pd.setTitle("Posting data");
new PostTask().execute();
private class PostTask extends AsyncTask<VOid, Void, Void> {
protected void onPreExecute()
{//display dialog.
pd.show();
}
protected SoapObject doInBackground(Void... params) {
// TODO Auto-generated method stub
//post request. do not update ui here. runs in background
return null;
}
protected void onPostExecute(Void param)
{
pd.dismiss();
//update ui here
}

android Async and http client

I have a custom http class in my android app to handle http post data that is sent to the server. However, I need to convert it to extend asyncTask because I need to 1, show a progress animation while the data is being fetched and 2, refresh/update the ui at the same time.
So what would be the easiest way to do this. Please note that I am already using the class throughout my app to handle httpPOST requests.
Here is the class:
public class Adapter_Custom_Http_Client
{
//<editor-fold defaultstate="collapsed" desc="Class Members">
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
private static HttpClient mHttpClient;
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="getHttpClient">
private static HttpClient getHttpClient()
{
if(mHttpClient == null)
{
mHttpClient = new DefaultHttpClient();
final HttpParams params = mHttpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
}
return mHttpClient;
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="executeHttpPost">
public static String executeHttpPost(String url, ArrayList postParameters) throws Exception
{
BufferedReader in = null;
try
{
HttpClient client = getHttpClient();
HttpPost request = new HttpPost(url);
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null)
{
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally
{
if (in != null)
{
try
{
in.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
//</editor-fold>
//<editor-fold defaultstate="collapsed" desc="executeHttpGet">
public static String executeHttpGet(String url) throws Exception
{
BufferedReader in = null;
try
{
HttpClient client = getHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null)
{
sb.append(line + NL);
}
in.close();
String result = sb.toString();
return result;
}
finally
{
if (in != null)
{
try
{
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
//</editor-fold>
}
Use this Async Class:
public class Albums extends AsyncTask<Void, Void, Void> {
//declarations what u required
#Override
protected void onPreExecute() {
super.onPreExecute();
///declare ur progress view and show it
}
#Override
protected Void doInBackground(Void... params) {
//do ur http work here which is to be done in background
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//Update ur UI here...
}
}
Any problem please ask..
EDIT:
Albums alb=new Albums();
alb.execute(null);///u can use different arguments that u need
follow like this:
public class postmethod extends AsyncTask<Void, Void, Void> {
//declarations what u required
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
//do ur work here completly that will runs as background
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
}
}
Create new asynch inner class in your activity :
public class InnerClass extends AsyncTask<Void, Void, String>{
ProgressDialog dialog;
#Override
protected String doInBackground(Void... params) {
String result = Adapter_Custom_Http_Client.executeHttpPost(url , param);
return result;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(context, "", "Please wait....");
super.onPreExecute();
}
}
and execute background task using
new InnerClass().execute();

Categories

Resources