Llamada a Android Async Tarea en una actividad

Tengo una actividad que selecciona una imagen de un gridview y permite que usted ahorre la imagen. Estoy utilizando Async Task para todos mis códigos. Separé mi AsyncTask de algunas clases. ¿Cómo los llamo de mi actividad? ¿Cómo puedo pasar la cadena de nuevo a mi 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(); } } 

Crea una nueva instancia de SaveImageTask y luego llama a su método execute , pasando los argumentos String a ella ( execute takes a varargs).

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

Editar

Dado que su AsyncTask utiliza un Context , necesitará pasarlo a través de un 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; } ... } 

A continuación, llame al AsyncTask de su Activity manera:

 new SaveImageTask(this).execute("foo", "bar"); 
 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; } } 
  • Android No se encontraron las siguientes clases: EditText (Cambiar a android.widget.EditText, Corregir ruta de compilación, Editar XML)
  • Android, cómo obtener el nombre del paquete?
  • Listado del paquete de reloj / alarma del fabricante y nombre de la clase, por favor agregue
  • Ampliación de la clase Aplicación de Android
  • Android-calling Intent de una clase interna
  • Android Llamar a un método de otra clase
  • Cómo crear una variable global en android?
  • Clase de robot como clases para android
  • ¿Cómo puedo acceder a los valores almacenados de un Bean desde dentro de otra Clase
  • Cómo recuperar la actividad solicitada por un Intent
  • obtener el valor entero de EditText Android
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.