I want to create an application using PHP webservices which can download file from server.
This is my Detail class:
public class ImportExportDataDetails extends Activity {
int id;
Button btnback;
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;
TextView txtname,tvfile1,tvfile2,tvdetail;
ImageView imgflag;
Button btnfile1,btnfile2;
String url1,url2,filenm1,filenm2;
private DefaultHttpClient httpclient;
private HttpPost httppost;
private ArrayList<NameValuePair> lst;
public static String[] image;
public static String[] name;
public static String[] file1;
public static String[] file2;
public static String[] fnm1;
public static String[] fnm2;
public static String[] detail;
private JSONArray users =null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_import_export_data_details);
Intent i=getIntent();
id=i.getIntExtra("id", 0);
txtname=(TextView)findViewById(R.id.txtname);
tvfile1=(TextView)findViewById(R.id.tvfile1);
tvfile2=(TextView)findViewById(R.id.tvfile2);
tvdetail=(TextView)findViewById(R.id.tvdetail);
imgflag=(ImageView)findViewById(R.id.imgflag);
btnfile1=(Button)findViewById(R.id.btnfile1);
btnfile2=(Button)findViewById(R.id.btnfile2);
btnback=(Button)findViewById(R.id.btnback);
btnback.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent i=new Intent(getApplicationContext(),ImportExportData.class);
startActivity(i);
}
});
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://kalalunsons.com/webservice/web-import-export-data-details.php?import_export=1");
lst=new ArrayList<NameValuePair>();
lst.add(new BasicNameValuePair("im_ex_data_id", Integer.toString(id)));
try {
httppost.setEntity(new UrlEncodedFormEntity(lst));
new details().execute();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
btnfile1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
startDownload();
}
});
}
private void startDownload() {
String url = url1;
new DownloadFileAsync().execute(url);
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Downloading file..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
class DownloadFileAsync extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
// Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/file.xlsx");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(""+(int)((total*100)/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onProgressUpdate(String... progress) {
Log.d("ANDRO_ASYNC",progress[0]);
mProgressDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
}
class details extends AsyncTask<String, integer, String>{
String jsonstring;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
HttpResponse httpresponse=httpclient.execute(httppost);
jsonstring=EntityUtils.toString(httpresponse.getEntity());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonstring;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
JSONObject JsonObject=null;
try {
JsonObject =new JSONObject(result);
JSONObject jobj=JsonObject.getJSONObject("0");
users=jobj.getJSONArray("import_export");
name=new String[users.length()];
image=new String[users.length()];
detail=new String[users.length()];
file1=new String[users.length()];
file2=new String[users.length()];
fnm1=new String[users.length()];
fnm2=new String[users.length()];
for(int i=0;i<users.length();i++){
JSONObject jo=users.getJSONObject(i);
name[i]=jo.getString("name");
image[i]=jo.getString("image");
detail[i]=jo.getString("details");
file1[i]=jo.getString("file");
file2[i]=jo.getString("file2");
fnm1[i]=jo.getString("file_name");
fnm2[i]=jo.getString("file_name");
txtname.setText(name[i]);
Picasso.with(getApplicationContext()).load(image[i]+"?import_export=1").into(imgflag);
tvdetail.setText(Html.fromHtml(detail[i]));
tvfile1.setText(fnm1[i]);
tvfile2.setText(fnm2[i]);
url1=file1[i];
url2=file2[i];
filenm1=tvfile1.getText().toString();
filenm1=filenm1.toLowerCase()+".xlsx";
}
//Toast.makeText(getApplicationContext(), url1, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
In that case the logcat doesn't display any error.when i run this code it start progress of downloading,when progress finished i check my sdcard folder but it not display any file.the file was downloaded successfully but it displays as binary format,what can i changes in my code.and how can i display it in the sdcard.
you can use some library for network calls:-
retrofit-
http://www.androidhive.info/2016/05/android-working-with-retrofit-http-library/
also background and UI threads are separate threads. In UI thread, you can update your views and UI like toast messages and load an image.
here is a great article to learn about asynctask, read this first --
https://androidresearch.wordpress.com/2012/03/17/understanding-asynctask-once-and-forever/
Issue: you are showing Toast in doInBackground() which run in separate thread. Remove Toast message from doInBackground() method
If you wanna show some info,use logs instead of Toast
Related
i have an web-based application that must retrive text in external database and image in server after one text retrived ,using following code for retrive text:
class BackgroundTaskOne extends AsyncTask<Void, Void, String>
{
String json_url;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
json_url="http://..some url../somefile.php";
}
#Override
protected String doInBackground(Void... voids) {
// TODO Auto-generated method stub
String error="";
try {
URL url=new URL(json_url);
HttpURLConnection httpUrlConnection=(HttpURLConnection) url.openConnection();
InputStream inputStream=httpUrlConnection.getInputStream();
BufferedReader bufferReader=new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder=new StringBuilder();
while((JSON_STRINO=bufferReader.readLine())!=null){
stringBuilder.append(JSON_STRINO+"\n");
//add new textView
}
bufferReader.close();
inputStream.close();
httpUrlConnection.disconnect();
json_string=stringBuilder.toString().trim();
return stringBuilder.toString().trim();
// return "one row of data inserted..";
} catch (MalformedURLException e) {
error=e.getMessage()+" first";
} catch (IOException e) {
// TODO Auto-generated catch block
error=e.getMessage()+" sec";
}
return error;
}
#Override
protected void onProgressUpdate(Void... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
json_string=result;
l=parse();
int i=0;
for(final String a[]:l){
TextView t=new TextView(MainActivity.this);
final String path=a[2]+".jpg";
t.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
t.setText(a[0]+" : "+a[1]+" i="+i);
t.setId(i);
Reklam.addView(t);
new LoadImage().execute(path);
i++;
}}}
i want to load image while loading first text and second image after second text in sequence but it loads all text then load all images , these folowing code for loading image:
private class LoadImage extends AsyncTask<String, String, Bitmap> {
Bitmap bitmap;
ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading Image ....");
pDialog.show();
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
ImageView img=new ImageView(MainActivity.this);
img.setImageBitmap(image);
img.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
Reklam.addView(img);
pDialog.dismiss();
}else{
pDialog.dismiss();
Toast.makeText(MainActivity.this, "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
}
}
}
if you want to run multiple thread parallely :
if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ) {
new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
new MyAsyncTask().execute();
}
I want to start timer after clicking on Button and poll for every 3 secs.
I am using following code.
private EditText url;
private Button submit;
private TextView error;
String some_URL;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_live);
loadviews();
handler=new Handler();
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
some_URL="http://"+url.getText().toString();
getStatus();
}
}
});
private void getStatus() {
// TODO Auto-generated method stub
handler.postDelayed(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
new Class_Poll().execute(some_URL);
error.setText("ID:"+ID+"\n"+
"Name:"+name+"\n" +
"Type:"+type+"\n"+
"Status:"+Status+"\n"+
"Content:"+Content);
}
}, 3000);
}
}
private void loadviews() {
// TODO Auto-generated method stub
url=(EditText)findViewById(R.id.url);
submit=(Button)findViewById(R.id.Submit);
error=(TextView)findViewById(R.id.log);
error.setMovementMethod(new ScrollingMovementMethod());
}
private class Class_Poll extends AsyncTask<String, Void, Void>{
private final HttpClient Client = new DefaultHttpClient();
#Override
protected Void doInBackground(String... arg0) {
// TODO Auto-generated method stub
Content=executeHttpRequest(some_URL);
return null;
}
#Override
protected void onPostExecute(Void unused) {
JSONObject jsonResponse;
try {
jsonResponse = new JSONObject(Content);
ID=jsonResponse.optString("ID").toString();
name=jsonResponse.optString("Name").toString();
type=jsonResponse.optString("Type").toString();
Status=jsonResponse.optString("Status").toString();
error.setText("ID:"+ID+"\n"+
"Name:"+name+"\n" +
"Type:"+type+"\n"+
"Status:"+Status+"\n"+
"Content:"+Content);
} catch (JSONException e) {
error.setText(e.toString());
}
//Toast.makeText(getApplicationContext(), "ID:"+ID+" Name:"+name+" Type:"+type+" Status:"+Status, Toast.LENGTH_LONG).show();
}
}
public static String executeHttpRequest(String url)
{
HttpURLConnection urlConnection = null;
try
{
URL httpUrl = new URL(url);
urlConnection = (HttpURLConnection) httpUrl.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.addRequestProperty("Accept", "text/html,text/xhtml,application/xhtml+xml,application/xml;");
urlConnection.setConnectTimeout(10000);
InputStream in = null;
try
{
in = urlConnection.getInputStream();
} catch (NullPointerException e)
{
Log.e("Check", "Request Failed, Check the url");
return null;
}
if (in != null)
{
in = new BufferedInputStream(in);
String response = readStream(in);
Log.e("Check", response + "");
if (response != null && !response.isEmpty())
{
// statusTrace.print(TAG, "Operation executed : " +
// isSuccess(response));
return response;
}
else
{
Log.e("Check", "Request Failed");
}
} else
;//statusTrace.print(TAG, "Request Failed");
} catch (IOException e)
{
Log.e("Check", "Error : " + e.toString());
//statusTrace.print("Error", "Network Error. Check connection and Tuxedo IP");
}
return null;
}
public static String readStream(InputStream in)throws IOException {
// TODO Auto-generated method stub
InputStreamReader is = new InputStreamReader(in);
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(is);
String read = br.readLine();
while (read != null)
{
sb.append(read);
read = br.readLine();
}
return sb.toString();
}
error is TextView in which I am displaying some Text.
And I am invoking web service in Asyntask. So it is not executing asynchtask for delay of 3 seconds after button click.
I don't know where know what is the problem exactly. It should execute actually, my textview is not getting updated for each 3 seconds.
Timer runs on a different thread you should not invoke AsyncTask from a background thread.
Please read Threading rules #
http://developer.android.com/reference/android/os/AsyncTask.html
public void scheduleAtFixedRate (TimerTask task, long delay, long period)
Added in API level 1
Schedule a task for repeated fixed-rate execution after a specific delay has passed.
Parameters
task the task to schedule.
delay amount of time in milliseconds before first execution.
period amount of time in milliseconds between subsequent executions.
Throws
IllegalArgumentException if delay < 0 or period <= 0.
IllegalStateException if the Timer has been canceled, or if the task has been scheduled or canceled.
Your delay is 0. See this }, 0, 3000);
can you suggest me an alternative to this so that I can execute
AsynchTask at after 3 secs of delay??
I assume you want to invoke asynctask after a 3 sec delay
You can use a Handler
Handler handler = new Handler():
handler.postDelayed(new Runnable(){
#Override
public void run() {
// run something after 3 sec delay
}
}, 3000);
Edit:
public class MainActivity extends Activity
{
private EditText url;
private Button submit;
private TextView error;
String Content;
String some_URL;
Handler handler;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_live);
loadviews();
handler=new Handler();
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
some_URL="http://"+url.getText().toString();
getStatus();
}
});
}
private void getStatus() {
// TODO Auto-generated method stub
handler.postDelayed(new Runnable(){
#Override
public void run() {
new Class_Poll().execute(some_URL);
}
}, 3000);
}
private void loadviews() {
// TODO Auto-generated method stub
url=(EditText)findViewById(R.id.url);
submit=(Button)findViewById(R.id.Submit);
error=(TextView)findViewById(R.id.log);
error.setMovementMethod(new ScrollingMovementMethod());
}
private class Class_Poll extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... arg0) {
String _response;
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpGet request = new HttpGet(arg0[0]);
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
}catch(Exception e)
{
e.printStackTrace();
}
return _response;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
JSONObject jsonResponse;
try {
jsonResponse = new JSONObject(result);
String ID=jsonResponse.optString("ID").toString();
String name=jsonResponse.optString("Name").toString();
String type=jsonResponse.optString("Type").toString();
String Status=jsonResponse.optString("Status").toString();
error.setText("ID:"+ID+"\n"+
"Name:"+name+"\n" +
"Type:"+type+"\n"+
"Status:"+Status+"\n"+
"Content:"+Content);
} catch (JSONException e) {
error.setText(e.toString());
}
}
}
}
I am getting a JSON response from a URL and convert it into a string. I want to parse this string to get some values from the response. But when the parsing takes place the application shows a blank screen(black screen) until the response is parsed. I wanted to show a ProgressDialog which shows how much data is to be downloaded so that the app does not show that blank screen. I tried showing a ProgressDialog but it is shown before the parsing and after it is done. The in between time still shows the blank screen.
Here is my code:-
String registerContet = "myUrl";
String items;
try
{
items = new FetchItems().execute(registerContet).get();
pDialog = new ProgressDialog(this).show(Home.this, "Fetching news items", "Please wait..");
JSONArray jObject = new JSONArray(items);
for (int i = 0; i < jObject.length(); i++)
{
JSONObject menuObject = jObject.getJSONObject(i);
String title= menuObject.getString("Title");
String description= menuObject.getString("BodyText");
String thumbnail= menuObject.getString("ThumbnailPath");
String newsUrl = menuObject.getString("Url");
String body = menuObject.getString("Body");
String newsBigImage = menuObject.getString("ImageBlobUrls");
map = new HashMap<String,String>();
map.put(SOURCETITLE, title);
map.put(TITLE, description);
map.put(THUMBNAILPATH, thumbnail);
map.put(BODY, body);
map.put(URL, newsUrl);
map.put(IMAGEBLOBURLS,newsBImage);
myNList.add(map);
}
itemsAdapter = new LazyAdapter(Home.this, myNList);
if(pDialog!=null && pDialog.isShowing())
{
pDialog.dismiss();
}
nList.setAdapter(itemsAdapter);
nList.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0,
View arg1, int position, long arg3)
{
// TODO Auto-generated method stub
myDialog = new ProgressDialog(Home.this).show(Home.this, "Fetching news..", "Just a moment");
HashMap<String, String> myMap = myNList.get(position);
Intent nIntent = new Intent(Home.this,NDetails.class);
newsIntent.putExtra("NItems", myMap);
startActivity(nIntent);
}
});
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
FetchItems.java is
private class FetchItems extends AsyncTask<String, String, String> {
// TODO Auto-generated method stub
ProgressDialog myDialog;
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
HttpResponse response = null;
String resultString = "";
String myResponseBody = "";
// Creating HTTP client
HttpClient httpClient = new DefaultHttpClient();
// Creating HTTP Post
HttpGet request = new HttpGet(params[0]);
try {
response = httpClient.execute(request);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = entity.getContent();
myResponseBody = convertToString(inputStream);
}
}
} catch (Exception e) {
}
return myResponseBody;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
/*
* if(myDialog.isShowing()) { myDialog.dismiss(); }
*/
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
/*
* myDialog = new ProgressDialog(Home.this);
* myDialog.setMessage("Loading"); myDialog.show();
*/
}
}
Can anyone tell me how can I resolve this.
Thanks
public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
Creating dialog in activity:
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DOWNLOAD_PROGRESS:
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Converting..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
return mProgressDialog;
default:
return null;
}
}
Show dialog in onPreExecute()
#Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
Dismiss dialog in onPostExecute()
#Override
protected void onPostExecute(String unused) {
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
Use this code with in onPreExecute method,
private ProgressDialog dialog;
dialog = new ProgressDialog(this);
dialog.setMessage("Please Wait...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
easy and simple code for percentage in dialog of progress dialog
> protected void onPreExecute() {
dialog = new ProgressDialog(UploadActivity.this);
dialog.setMessage("Loading, please wait.. ");
dialog.show();
dialog.setCancelable(false);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
dialog.setMessage("Loading, please wait.. "+String.valueOf(progress[0])+"%");
}
I am working on one android app in which i want to display progress Dialog till loading of gridview completed. But my problem is progress dialog is spin for some intial time. Then it stops spinning.
Here is my code.
public class allsites extends Activity {
private final String url_select = "http://api.stackexchange.com/2.1/sites?filter=!RGB_Y51.*-(YX";
private GridView gview;
private ListViewCustomAdapter adapter;
private ArrayList<Object> itemList = new ArrayList<Object>();
private ItemBean bean;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.allsites);
//GridView gridview = (GridView) findViewById(R.id.gvAllSites);
gview = (GridView) findViewById(R.id.gvallsites);
new task().execute();
}
private class task extends AsyncTask<Void, Void, GZIPInputStream> {
private ProgressDialog progress;
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(allsites.this, "Loading", "Please Wait...");
}
#Override
protected GZIPInputStream doInBackground(Void... params) {
ServerData httpclient = new ServerData();
GZIPInputStream zis = httpclient.GetServerData(url_select);
return zis;
}
#Override
protected void onPostExecute(GZIPInputStream zis) {
ParseJSON(zis);
if(progress!=null && progress.isShowing()==true)
progress.dismiss();
}
}
private void ParseJSON(GZIPInputStream zis)
{
Gson gson = new Gson();
Reader reader = new InputStreamReader(zis);
Sites response = gson.fromJson(reader, Sites.class);
List<Items> items = response.getItems();
for (Items site : items) {
//Toast.makeText(allsites.this, site.getApi_site_parameter().toString(), Toast.LENGTH_SHORT).show();
AddObjectToList(site.getIcon_url(),site.getName());
}
adapter = new ListViewCustomAdapter(this, itemList);
gview.setAdapter(adapter);
}
public void AddObjectToList(String imageURL, String title)
{
bean = new ItemBean();
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageURL).getContent());
bean.setImage(bitmap);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bean.setTitle(title);
itemList.add(bean);
}
}
Please give me suggestion how i can make progress dialog spinning till gridview get loaded.
move ParseJSON function to doInBackground event
#Override
protected Boolean doInBackground(Void... params) {
ServerData httpclient = new ServerData();
GZIPInputStream zis = httpclient.GetServerData(url_select);
ParseJSON(zis);
return true;
}
#Override
protected void onPostExecute(Boolean zis) {
progress.dismiss();
}
I'm trying to display process dialog, it is being showed as expected, but when it is being showed, doInBackground() is not being executed, when I press on screen of emulator, then doInBackground() starts executing again.
This is my AsyncTask class:
public class FetchEmployeeAsyncTask extends AsyncTask<String, Void, ArrayList<Employee> > {
private CaptureActivity activity;
//private ProgressDialog progressDialog;
public FetchEmployeeAsyncTask(CaptureActivity nextActivity) {
this.activity = nextActivity;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
/*progressDialog= new ProgressDialog(activity);
progressDialog.setCancelable(true);
progressDialog.setTitle("Fetching Employees!!");
progressDialog.setMessage("Please wait...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setProgress(0);
progressDialog.show();*/
}
#Override
protected ArrayList<Employee> doInBackground(String... url) {
// TODO Auto-generated methoVoidd stub
ArrayList<Employee> employees = null;
for(String employeeUrl : url){
employees = fetch(employeeUrl);
}
return employees;
}
private ArrayList<Employee> fetch(String url) {
// TODO Auto-generated method stub
ArrayList<Employee> employees = null;
String response = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
employees = EmployeeXMLParser.employeeParser(response);
System.out.println("Size in fetch "+employees.size());
//System.out.println("Employee Name :: " + employees.get(0).getFirstName() + " " + employees.get(0).getLastName());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} /*catch (XmlPullParserException e) {
// TODO Auto-generated catch block
System.out.println("Error parsing the response :: " + response);
e.printStackTrace();
}*/
return employees;
}
#Override
public void onPostExecute(ArrayList<Employee> employees){
super.onPostExecute(employees);
System.out.println("in post execxute "+employees.size());
//progressDialog.dismiss();
activity.showEmployees(employees);
}
}
I'm calling AsyncTask in this activity class:
public class CaptureActivity extends Activity {
private String url = "http://192.168.2.223:8680/capture/clientRequest.do?r=employeeList&cid=0";
FetchEmployeeAsyncTask employeeAsyncTask;
private ArrayList<Employee> employees = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("");
employeeAsyncTask = new FetchEmployeeAsyncTask(this);
employeeAsyncTask.execute(new String[] {url});
System.out.println("Status "+employeeAsyncTask.getStatus());
setContentView(R.layout.activity_capture);
}
What are you trying to do here? are you trying to get some values from the database if so check the assignment of the url if you are passing the value correctly.
Also please try explaining your problem in detail and paste some more code.
Try this:
protected void onPreExecute() {
progressDialog = ProgressDialog.show(currentActivity.this, "",
"Message Here", true);
}
protected void onPostExecute(String str) {
dialog.dismiss();
}