How to Asynctask within fragment? - android

I want to use a DefaultHttpClient/HttpGet asynctask to grab the JSON from the school's site. But I want to request it from within the Fragment.
How can I do that without failing?
This is what I already tried:
public class RequestData extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private Context context;
private String Error = null;
private ProgressDialog Dialog;
public RequestData(Context context) {
this.context = context;
}
protected void onPreExecute() {
Dialog = new ProgressDialog(context);
Dialog.setMessage("Downloading source..");
Dialog.show();
}
protected Void doInBackground(String... urls) {
try {
HttpGet httpget = new HttpGet(urls[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
Content = Client.execute(httpget, responseHandler);
} catch (ClientProtocolException e) {
Error = e.getMessage();
cancel(true);
} catch (IOException e) {
Error = e.getMessage();
cancel(true);
}
return null;
}
protected void onPostExecute(Void unused) {
Dialog.dismiss();
if (Error != null) {
Toast.makeText(context, Error, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "Source: " + Content, Toast.LENGTH_LONG).show();
}
}
}
Which is called by this:
RequestData request = new RequestData(getSherlockActivity());
request.execute(getBaseURL() + "phpinfo.php");

Related

Progress Dialog not showing in Android

Progress Dialog is not showing in AsyncTask Class In Android.
My AsyncTask Class Code:
class SyncData1 {
Context context;
DatabaseHelper myDbHelper;
ArrayList<String> ItemNo= new ArrayList<String>();
ArrayList<String> RepReceivedQty= new ArrayList<String>();
ArrayList<String> HotelReceivedQty= new ArrayList<String>();
ArrayList<String> IStatus= new ArrayList<String>();
String jsodata;
String ChallanNo="",HotelRepReceivedOn="",HotelReceivedOn="",Status="";
String url=null;
Commans com;
public SyncData1(Context context)
{
this.context=context;
}
public void fetchData()
{
ItemNo.clear();
IStatus.clear();
RepReceivedQty.clear();
HotelReceivedQty.clear();
com= new Commans(context);
myDbHelper =new DatabaseHelper(context);
com.connectdb(myDbHelper);
Cursor curval= myDbHelper.dbQery("Select * from Challan_R where Flag=1 limit 1");
if(curval != null && curval.moveToFirst()) {
ChallanNo= curval.getString(0);
Status=curval.getString(5);
HotelRepReceivedOn=curval.getString(6);
HotelReceivedOn= curval.getString(7);
}
curval.close();
Cursor curItem= myDbHelper.dbQery("Select * from ChallanItems where ChallanNo= "+"'"+ChallanNo+"'");
if(curItem != null && curItem.moveToFirst()) {
while( !curItem.isAfterLast())
{
ItemNo.add(curItem.getString(0));
IStatus.add(curItem.getString(2));
RepReceivedQty.add(curItem.getString(9));
HotelReceivedQty.add(curItem.getString(1));
curItem.moveToNext();
}
}
curItem.close();
if(ChallanNo.length()>1)
{
jsodata=com.reciveJson(ChallanNo, HotelRepReceivedOn, HotelReceivedOn, Status, ItemNo, RepReceivedQty, HotelReceivedQty, IStatus);
Log.d("Json", jsodata);
ReciveChallanAsyn task = new ReciveChallanAsyn();
task.execute("");
}
}
private class ReciveChallanAsyn extends AsyncTask<String, Void, String> {
public static final int HTTP_TIMEOUT = 30 * 1000;
#Override
protected String doInBackground(String... urls) {
String response = "";
HttpEntity resEntity;
try {
//url=urls[0].getUrl();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Constants.SERVICE_SYNC_DATA);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("data",jsodata));
nameValuePairs.add(new BasicNameValuePair("token",CreateChallan.token));
nameValuePairs.add(new BasicNameValuePair("customer_code",CreateChallan.strcustomer_code));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse responsePOST = httpclient.execute(httppost);
resEntity = responsePOST.getEntity();
response=EntityUtils.toString(resEntity);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
#SuppressLint("DefaultLocale")
#Override
protected void onPostExecute(String result) {
Log.d("Result", result);
pd.dismiss();
if(result!=null)
{
if(result.contentEquals("1") && result!=null)
{ com.connectdb(myDbHelper);
Toast.makeText(context, " Challan Sent ", Toast.LENGTH_LONG).show();
myDbHelper.ChallN_Updateb("", "2", ChallanNo,"");
Cursor curval1= myDbHelper.dbQery("Select * from Challan_R where Flag=1 limit 1");
if(curval1 != null && curval1.moveToFirst()) {
fetchData();
}
curval1.close();
com.disconnectdb();
}
else
Toast.makeText(context, "Error In Sending Challan", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(context, "Data Not Fount", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onPreExecute()
{
// pd = ProgressDialog.show(HomeChallan.this, ""," Please wait...");
pd = new ProgressDialog(HomeChallan.this);
pd.setMessage(" Please wait... ");
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.show();
}
}
It's a subclass of my main class where I am using the Async Task class
I am using the class SyncData1 class on onclickListerner Method
Cursor curval1= myDbHelper.dbQery("Select * from Challan_R where Flag=1 limit 1");
if(curval1 != null && curval1.moveToFirst()) {
SyncData1 data= new SyncData1(context);
data.fetchData();
Hope this can solve your issue, do some editing as per your requirment..
private final Handler handler = new Handler();
private Thread thread;
private QueueRunner runner = new QueueRunner();
private CustomProgressDialog mProgressBar;
private class QueueRunner implements Runnable
{
public void run()
{
try
{
synchronized(this)
{
handler.post(new Runnable()
{
public void run()
{
if (((Activity) AsyncWebPostClient.this.context).isFinishing() == false)
mProgressBar = CustomProgressDialog.show(AsyncWebPostClient.this.context,
null,null,true,true );
}
});
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
in your preExecute call this..
thread = new Thread(runner);
thread.start();
in your onpost call this..
mProgressBar.dismiss();
Edit: I have use customeProgress Dialog you can use Progress Dialog
this is your asynctask method,copy and paste it hope it's worked:
private class ReciveChallanAsyn extends AsyncTask<String, Void, String> {
public static final int HTTP_TIMEOUT = 30 * 1000;
#Override
protected void onPreExecute()
{
// pd = ProgressDialog.show(HomeChallan.this, ""," Please wait...");
pd = new ProgressDialog(HomeChallan.this);
pd.setMessage(" Please wait... ");
pd.setIndeterminate(false);
pd.setCancelable(false);
pd.show();
}
#Override
protected String doInBackground(String... urls) {
String response = "";
HttpEntity resEntity;
try {
//url=urls[0].getUrl();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Constants.SERVICE_SYNC_DATA);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("data",jsodata));
nameValuePairs.add(new BasicNameValuePair("token",CreateChallan.token));
nameValuePairs.add(new BasicNameValuePair("customer_code",CreateChallan.strcustomer_code));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse responsePOST = httpclient.execute(httppost);
resEntity = responsePOST.getEntity();
response=EntityUtils.toString(resEntity);
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
#SuppressLint("DefaultLocale")
#Override
protected void onPostExecute(String result) {
Log.d("Result", result);
pd.dismiss();
if(result!=null)
{
if(result.contentEquals("1") && result!=null)
{ com.connectdb(myDbHelper);
Toast.makeText(context, " Challan Sent ", Toast.LENGTH_LONG).show();
myDbHelper.ChallN_Updateb("", "2", ChallanNo,"");
Cursor curval1= myDbHelper.dbQery("Select * from Challan_R where Flag=1 limit 1");
if(curval1 != null && curval1.moveToFirst()) {
fetchData();
}
curval1.close();
com.disconnectdb();
}
else
Toast.makeText(context, "Error In Sending Challan", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(context, "Data Not Fount", Toast.LENGTH_LONG).show();
}
}
}

Passing object model to another AsyncTask from other AsyncTask and adding data to model doesn't render

This is my first async task, which gets called first, it gets data from server and then onPostExecute it executes other async task, which downloads and sets image.
private class GetData extends AsyncTask<String, Void, Void> {
private final HttpClient client = new DefaultHttpClient();
private String content;
private String error = null;
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... progress) {
}
#Override
protected Void doInBackground(String... params) {
try {
HttpGet httpget = new HttpGet(params[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
content = client.execute(httpget, responseHandler);
} catch (ClientProtocolException e) {
error = e.getMessage();
cancel(true);
} catch (IOException e) {
error = e.getMessage();
cancel(true);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (error == null) {
try {
JSONObject dataDishes = new JSONObject(content);
Log.d("DISHES", dataDishes.toString());
ArrayList<DishModel> dishData = new ArrayList<DishModel>();
for (int i = 0; i < 8; i++) {
DishModel model = new DishModel();
model.setName("Company " + i);
model.setDesc("desc" + i);
//TODO: set data img
new GetImage(model).execute("http://example.com/" + (i + 1) + ".png");
dishData.add(model);
}
ListView listAllDishes = (ListView) getView().findViewById(R.id.listView);
DishRowAdapter adapterAllDishes = new DishRowAdapter(getActivity(),
R.layout.dish_row, dishData);
listAllDishes.setAdapter(adapterAllDishes);
} catch (JSONException e) {
Log.d("DISHES", e.toString());
}
} else {
Log.e("DISHES", error);
}
}
}
This is another async task, it downloads image and onPostExecute it sets image to passed model.
private class GetImage extends AsyncTask<String, Void, Void> {
private DishModel model;
private Bitmap bmp;
public getImage(DishModel model) {
this.model = model;
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... progress) {
}
#Override
protected Void doInBackground(String... params) {
try {
URL url = new URL(params[0]);
Log.d("DISHES", params[0]);
try {
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
Log.d("DISHES", e.toString());
}
} catch (MalformedURLException e) {
Log.d("DISHES", e.toString());
}
return null;
}
#Override
protected void onPostExecute(Void result) {
model.setPhoto(bmp);
}
}
It works if I do both data/image download proccess in one AsyncTask doInBackground(String... params), but it doesnt when I split data and image downloading into seperate async tasks. Furthermore I dont get any exceptions or errors.
UPDATE: Images shows up when i switch views..
At first, getImage and getData are classes, and classes names in Java are capitalized.
Technically, you can run another AsyncTask from onProgressUpdate() or onPostExecute() - https://stackoverflow.com/a/5780190/1159507
So, try to put the breakpoint in second AsyncTask call and debug is it called.

show an error message when can not requested URL in android

I have this code to request an URL and show the result on the screen by a TextView. this is my code:
public class AsyncronoustaskAndroidExample extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.asyncronoustask_android_example);
final Button GetServerData = (Button) findViewById(R.id.GetServerData);
GetServerData.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String serverURL = "http://androidexample.com/media/webservice/getPage.php";
new LongOperation().execute(serverURL);
}
});
}
private class LongOperation extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(AsyncronoustaskAndroidExample.this);
TextView uiUpdate = (TextView) findViewById(R.id.output);
protected void onPreExecute() {
uiUpdate.setText("Output : ");
}
protected Void doInBackground(String... urls) {
try {
// Server url call by GET method
HttpGet httpget = new HttpGet(urls[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
Content = Client.execute(httpget, responseHandler);
} catch (ClientProtocolException e) {
Error = e.getMessage();
cancel(true);
} catch (IOException e) {
Error = e.getMessage();
cancel(true);
}
return null;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
if (Error != null) {
uiUpdate.setText("Output : "+Error);
} else {
uiUpdate.setText("Output : "+Content);
}
}
}
}
But when the URL is invalid, my program stop, I tried to show an error message but I can't. please help me!
thank so much.
Please check your log cat. Mostly you must be getting an IllegalStateException. If it is the case you have got to catch that too.
If you want to check your url is valid or invalid you need to use URL. Here's the example.
URL url;
try {
url = new URL(urls[0]);
HttpGet httpGet = new HttpGet(url.toString());
} catch (MalformedURLException e1) {
e1.printStackTrace();
}

ProcessDialog is not appearing properly?

This is my function that is in LoginActivity.java.So onclick of button i am calling this function.
public void postHttpRequest(String userId,String pass,TextView error){
RequestClient reqClient = new RequestClient(LoginActivity.this);
String AppResponse = null;
try {
url = "myurl";
Log.d("URL", url);
AppResponse = reqClient.execute().get();
String status = ValidateLoginStatus.checkLoginStatus(AppResponse);
Log.d("Status recived", status);
if(status.equals("200")){
saveInformation(userId,pass);
startingActivity(HOST_URL);
}else{
error.setText("Incorrect UserName or Password");
}
} catch (Exception e) {
Log.e("Exception Occured", "Exception is "+e.getMessage());
}
}
From this function i am calling a AsynkTask for Http Communication.So onclick of button when i am geeting the response then my processDialog in opening just for one sec.I want as i click the buttoon my processDialog should get open utill i got the response
public class RequestClient extends AsyncTask<String, Void, String>{
ProgressDialog pDialog;
Context context;
public RequestClient(Context c) {
context = c;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Authenticating user...");
pDialog.show();
}
#Override
protected String doInBackground(String... aurl){
String responseString="";
DefaultHttpClient httpClient=new DefaultHttpClient();
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(LoginActivity.url);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
responseString = EntityUtils.toString(resEntityGet);
Log.i("GET RESPONSE", responseString);
}
} catch (Exception e) {
Log.d("ANDRO_ASYNC_ERROR", "Error is "+e.toString());
}
Log.d("ANDRO_ASYNC_ERROR", responseString);
httpClient.getConnectionManager().shutdown();
return responseString;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
if(pDialog!=null)
pDialog.dismiss();
}
}
So please suggest me what changes i have to make so that processDialog should display properly in the center of the device
//add style in your progressbialog
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setMessage("Authenticating user...");
if (pDialog != null && !pDialog.isShowing()) {
pDialog.show();
}
}
AsyncTask return value only after using get() method
Drawing from the above link
Calling the get() method of AsyncTask will block the main thread and wait for the result to be returned. This effectively makes using an AsyncTask become a synchronous operation in which case there's no point in using an AsyncTask.
The only reason I can think of to use the get() method would be from a thread other than the main (UI) thread although I can't think of many reasons to do that.
On Button click
RequestClient reqClient = new RequestClient(LoginActivity.this,new TheInterface() {
#Override
public void theMethod(String result) {
Log.i("Result =",result);
}
});
reqClient.execute(url); // no get(). pass url to doInBackground()
In your activity class
public interface TheInterface {
public void theMethod(String result);
}
}
AsyncTask
public class RequestClient extends AsyncTask<String, Void, String>{
ProgressDialog pDialog;
Context context;
TheInterface listener;
public RequestClient(Context c,TheInterface listen) {
context = c;
listener = listen;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Authenticating user...");
pDialog.show();
}
#Override
protected String doInBackground(String... aurl){
String responseString="";
HttpClient client;
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(aurl[0]); // url
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
responseString = EntityUtils.toString(resEntityGet);
Log.i("GET RESPONSE", responseString);
}
} catch (Exception e) {
Log.d("ANDRO_ASYNC_ERROR", "Error is "+e.toString());
}
Log.d("ANDRO_ASYNC_ERROR", responseString);
client.getConnectionManager().shutdown();
return responseString;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
pDialog.dismiss();
if (listener != null)
{
listener.theMethod(result);
}
}
}
It seems that your button code is not correct, because it's async, but you are trying to use it as standart sync code.
Try to move this code into onPostExecute:
String status = ValidateLoginStatus.checkLoginStatus(response);
Log.d("Status recived", status);
if(status.equals("200")){
saveInformation(userId,pass);
startingActivity(HOST_URL);
}else{
error.setText("Incorrect UserName or Password");
}
and make this button click code:
public void postHttpRequest(String userId,String pass,TextView error){
RequestClient reqClient = new RequestClient(LoginActivity.this);
String AppResponse = null;
try {
url = "myurl";
Log.d("URL", url);
reqClient.execute();
} catch (Exception e) {
Log.e("Exception Occured", "Exception is "+e.getMessage());
}
}

AsyncTask - onPostExecute is not called

I'm working on one project and I need to call one AsyncTask, but the onPostExecute method is not called.
This is my class:
public class WebService extends AsyncTask<String, String, String> {
private ArrayList<SimpleObserver> listeners;
private int responseCode;
private String message;
private String response;
private String URL;
public WebService() {
listeners = new ArrayList<SimpleObserver>();
}
public void addListener(SimpleObserver obs) {
listeners.add(obs);
}
public void removeListener(SimpleObserver obs) {
listeners.remove(obs);
}
public void notifyListener(String s) {
for (SimpleObserver listener : listeners)
listener.onChange(s);
}
public String getResponse() {
return response;
}
public String getErrorMessage() {
return message;
}
public int getResponseCode() {
return responseCode;
}
#Override
protected void onPreExecute() {
//notifyListener("A calcular");
}
#Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
HttpParams my_httpParams = new BasicHttpParams();
final String proxyHost = android.net.Proxy.getDefaultHost();
final int proxyPort = android.net.Proxy.getDefaultPort();
if(proxyPort != -1)
{
my_httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxyHost, proxyPort));
}
DefaultHttpClient client = new DefaultHttpClient(my_httpParams);
HttpGet httpGet = new HttpGet(url);
Log.d("URL serviço HttpGet", url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
Log.d("RESPOSTA do web service", response);
} catch (Exception e) {
e.printStackTrace();
response = e.getMessage();
Log.e("ERRO de respota", e.getMessage());
}
}
return response;
}
#Override
protected void onPostExecute(String result) {
Log.d("onPostExecute Serviço", result);
notifyListener(result);
}
}
I have created this method:
public void executeService(String param) {
try {
Log.d("Entrar", "no serviço");
s.execute(new String [] {URL+param});
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Erro ao aceder ao web service", e.getMessage());
}
}
to call the task.
these are the results of Log
08-28 17:47:21.936: D/URL serviço HttpGet(2055): http://192.168.56.1:8080/pt.Agile21.Acerola.WebService/rest/acerola?id=g;ana#eu.com
08-28 17:47:22.456: D/RESPOSTA do web service(2055): ana;ana#eu.com;pass;0
08-28 17:47:22.456: D/RESPOSTA do web service(2055): ana;ana#eu.com;pass;0
As you can see I have all the results of doInBackground(). :S
Someone can help me to understand which is the problem?
Something that I saw now looking for the Log files.. my onPostExeute method returns when I finish my app on purpose.. it is not normal.. :S can someone help me?

Categories

Resources