Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/210.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android在活动中调用异步任务_Android_Class_Android Activity_Android Asynctask - Fatal编程技术网

Android在活动中调用异步任务

Android在活动中调用异步任务,android,class,android-activity,android-asynctask,Android,Class,Android Activity,Android Asynctask,我有一个从gridview中选择图像的活动,它允许您保存图像。我的所有代码都使用异步任务。我把我的任务从几个类中分离出来。我如何从我的活动中称呼他们?如何将字符串传递回AsyncTask SingleImageView.class @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.save_ima

我有一个从gridview中选择图像的活动,它允许您保存图像。我的所有代码都使用异步任务。我把我的任务从几个类中分离出来。我如何从我的活动中称呼他们?如何将字符串传递回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;
        }
@覆盖
公共布尔值onOptionsItemSelected(菜单项项){
开关(item.getItemId()){
案例R.id.save_图像:

新建SaveImageTask().execute(image_url,context);//创建
SaveImageTask
的新实例,然后调用其
execute
方法,将字符串参数传递给它(
execute
使用varargs)

编辑

由于您的
AsyncTask
使用
上下文
,因此需要通过构造函数将其传入

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;
    }

    ...

}
private-poppwindow-poppwindow;
//此函数将位于MainActivity类上
findviewbyd(R.id.main\u page\u布局).post(新的Runnable(){
公开募捐{
新的SendJsonValue().execute();
}
});
公共类SendJsonValue扩展了AsyncTask{
@凌驾
受保护的void onPreExecute(){
/*弹出窗口初始化代码从此处开始*/
LayoutFlater LayoutFlater=(LayoutFlater)getBaseContext().getSystemService(布局\充气器\服务);
最终视图popupView=LayoutFlater.充气(R.layout.popup_窗口,空);
popupWindow=新的popupWindow(
弹出视图,
LayoutParams.FILL\u父级,
LayoutParams.FILL_PARENT);//创建弹出窗口
popupWindow.showAtLocation(popupView,重心,0,0);
}
受保护的字符串doInBackground(字符串…参数){
//TODO自动生成的方法存根
//loadingMore=true;//用于控制LoadMore的参数
HttpClient HttpClient=新的DefaultHttpClient();
最终HttpParams HttpParams=httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams,30000);//设置接收响应的超时
HttpConnectionParams.setSoTimeout(httpParams,30000);
HttpPost HttpPost=新的HttpPost(“http://10.0.2.2/upload_test/InsertData.php");  
试一试{
BasicNameValuePair idValuePair=新的BasicNameValuePair(“开发id”,设备id);
BasicNameValuePair emailValuePair=新的BasicNameValuePair(“开发电子邮件”,设备电子邮件);
BasicNameValuePair jsonStringValuePair=新的BasicNameValuePair(“json”,jObjectMain.toString());
List nameValuePairs=新的ArrayList();
nameValuePairs.add(idValuePairs);
nameValuePairs.add(EmailValuePairs);
添加(jsonStringValuePair);
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
HttpResponse response=httpclient.execute(httppost);//处理响应的响应类
jsonResult=inputStreamToString(response.getEntity().getContent()).toString();
JSONObject对象=新的JSONObject(jsonResult);
}捕获(ConnectTimeoutException e){
}catch(ClientProtocolException e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(JSONException e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(例外e){
}
返回jsonResult;
}
受保护的void onPostExecute(字符串结果){
系统输出打印项次(结果);
}
私有StringBuilder inputStreamToString(InputStream为){
字符串rLine=“”;
StringBuilder answer=新建StringBuilder();
BufferedReader rd=新的BufferedReader(新的InputStreamReader(is));
试一试{
而((rLine=rd.readLine())!=null){
答:追加(rLine);
}
}
捕获(IOE异常){
e、 printStackTrace();
}
返回答案;
}  
}

pDialog=newprogressdialog(上下文);捕获到错误无法找到AlertDialog。我看不到在
SaveImageTask
中设置的
Context
的位置。请检查我编辑的代码。我不明白contextThe
Context
是如何传递到
execute
的。它应该传递到构造函数中。
execute
方法只会我想我会问另一个问题,这个问题已经回答了。
new SaveImageTask().execute("foo", "bar");
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;
    }

    ...

}
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;
           }  
    }