Android Calling Async Task in Action

I have an activity that selects an image from a gridview and allows me to save the image. I use Async Task for all my codes. I have separated my AsyncTask from several classes. What do I call them from my work? How to pass a string back to my AsyncTask.

SingleImageView.class

@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.save_image: new SaveImageTask().execute(image_url,context); //<-- The method execute(String...) in the type AsyncTask<String,String,String> is not applicable for the arguments (String, Context) return true; default: return false; } 

SaveImageTask.class

  public class SaveImageTask extends AsyncTask<String, String, String> { private Context context; private ProgressDialog pDialog; String image_url; URL myFileUrl = null; Bitmap bmImg = null; @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); pDialog = new ProgressDialog(context); //<<-- Couldnt Recognise pDialog.setMessage("Downloading Image ..."); pDialog.setIndeterminate(false); pDialog.setCancelable(false); pDialog.show(); } @Override protected String doInBackground(String... args) { // TODO Auto-generated method stub try { myFileUrl = new URL(image_url); HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection(); conn.setDoInput(true); conn.connect(); InputStream is = conn.getInputStream(); bmImg = BitmapFactory.decodeStream(is); } catch (IOException e) { e.printStackTrace(); } try { String path = myFileUrl.getPath(); String idStr = path.substring(path.lastIndexOf('/') + 1); File filepath = Environment.getExternalStorageDirectory(); File dir = new File (filepath.getAbsolutePath() + "/Wallpaper/"); dir.mkdirs(); String fileName = idStr; File file = new File(dir, fileName); FileOutputStream fos = new FileOutputStream(file); bmImg.compress(CompressFormat.JPEG, 75, fos); fos.flush(); fos.close(); } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(String args) { // TODO Auto-generated method stub pDialog.dismiss(); } } 
+7
source share
2 answers

You create a new instance of SaveImageTask , and then call its execute method, passing it String arguments ( execute takes varargs).

 new SaveImageTask().execute("foo", "bar"); 

Edit

Since your AsyncTask uses Context , you need to pass it through the constructor.

 public class SaveImageTask extends AsyncTask<String, String, String> { private Context context; private ProgressDialog pDialog; String image_url; URL myFileUrl = null; Bitmap bmImg = null; public SaveImageTask(Context context) { this.context = context; } ... } 

Then call AsyncTask from your Activity as follows:

 new SaveImageTask(this).execute("foo", "bar"); 
+13
source
 private PopupWindow popupWindow; // this function will be on MainActivity class findViewById(R.id.main_page_layout).post(new Runnable() { public void run() { new SendJsonValue ().execute(); } }); public class SendJsonValue extends AsyncTask<String, Void, String>{ @Override protected void onPreExecute(){ /*code for pop window initialization begins here*/ LayoutInflater layoutInflater =(LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE); final View popupView = layoutInflater.inflate(R.layout.popup_window, null); popupWindow = new PopupWindow( popupView, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); //creating popup popupWindow.showAtLocation(popupView, Gravity.CENTER, 0, 0); } protected String doInBackground(String... params) { // TODO Auto-generated method stub //loadingMore = true;//parameter to take control on load more HttpClient httpclient = new DefaultHttpClient(); final HttpParams httpParams = httpclient.getParams(); HttpConnectionParams.setConnectionTimeout(httpParams, 30000);//set time out for receiving response HttpConnectionParams.setSoTimeout(httpParams, 30000); HttpPost httppost = new HttpPost("http://10.0.2.2/upload_test/InsertData.php"); try{ BasicNameValuePair idValuePair = new BasicNameValuePair("dev_id", device_id); BasicNameValuePair emailValuePair = new BasicNameValuePair("dev_email", device_email); BasicNameValuePair jsonStringValuePair = new BasicNameValuePair("json", jObjectMain.toString()); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(idValuePair); nameValuePairs.add(emailValuePair); nameValuePairs.add(jsonStringValuePair); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); //response class to handle responses jsonResult = inputStreamToString(response.getEntity().getContent()).toString(); JSONObject object = new JSONObject(jsonResult); }catch(ConnectTimeoutException e){ }catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); }catch(Exception e){ } return jsonResult; } protected void onPostExecute(String Result){ System.out.println(Result); } private StringBuilder inputStreamToString(InputStream is) { String rLine = ""; StringBuilder answer = new StringBuilder(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); try { while ((rLine = rd.readLine()) != null) { answer.append(rLine); } } catch (IOException e) { e.printStackTrace(); } return answer; } } 
0
source

All Articles