在我的android应用程序中一个接一个地调用Asynctask

时间:2014-09-25 06:49:56

标签: android json android-layout android-asynctask

我有一个使用Asyncttask的应用程序,但我想在一个完成后执行两个任务。但是我无法做到这一点所以请你给我伪代码。 这是我的Asynctask类

@SuppressWarnings("unused")
private class getresponse extends AsyncTask<String, Void, Void>{
    ProgressDialog pd ;

    private Context _context;

    public getresponse(Context c)
    {
        _context = c;
    }

    @Override
    protected void onPreExecute() {

         progressDialog = new ProgressDialog(MainActivity.this);
         pd = new ProgressDialog(_context);
            pd.setTitle("Getting JSON details");
            pd.setMessage("Please wait...");
            pd.setCancelable(false);
            pd.setIndeterminate(true);
            pd.show();
        super.onPreExecute();
    }


    @SuppressWarnings("static-access")
    @Override
    protected Void doInBackground(String... params) {
        try {
            /*String t = finduserjson.substring(
                    finduserjson.indexOf("{"),
                    finduserjson.lastIndexOf(",{"));
            String j = "]}";
            finduserjson = t + j;
            Log.d("FINDUSERJSON", "FINDUSERJSON" + finduserjson);*/
            jsonobject1.put("username", params[0]);
            jsonobject1.put("udid",
                    "A892E0AB-6732-4F42-BEFA-3157315E9EE4");
            socket.emit("setPseudo", jsonobject1);
            socket.emit("findAllUsers", jsonobject1);

            Log.e("TAG",""+ socket.getId());
        } catch (JSONException | MalformedURLException e1) {
             if (pd.isShowing())
                    pd.dismiss();
            e1.printStackTrace();
        }



    return null;
    }
    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        try
        {
            if (pd.isShowing())
                pd.dismiss();
        }
        catch(Exception e)
        {

        }

         /*String t = finduserjson.substring(
                    finduserjson.indexOf("{"), 
                    finduserjson.lastIndexOf(",{")); 
            String j = "]}";
            finduserjson = t + j;
            Log.d("FINDUSERJSON", "FINDUSERJSON" + finduserjson);

              Intent intent = new Intent(MainActivity.this,
                        MenuScreen.class);  
                intent.putExtra("onlineuser", onlineuser);
                intent.putExtra("finduser", finduserjson);
                startActivity(intent);*/
        new getresponse111(MainActivity.this).execute();
    }



    @Override
    protected void onCancelled() {
        // TODO Auto-generated method stub
        super.onCancelled();
        pd.dismiss();
    }



}
private class getresponse111 extends AsyncTask<Void, Void, Void>{


    private Context _context;

    public getresponse111(Context c)
    {
        _context = c;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }


    @SuppressWarnings("static-access")
    @Override
    protected Void doInBackground(Void... params) {
        String t = finduserjson.substring(
                finduserjson.indexOf("{"),
                finduserjson.lastIndexOf(",{"));
        String j = "]}";
        finduserjson = t + j;
        Log.d("FINDUSERJSON", "FINDUSERJSON" + finduserjson);



    return null;
    }
    @Override
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);

              Intent intent = new Intent(MainActivity.this,
                        MenuScreen.class);  
                intent.putExtra("onlineuser", onlineuser);
                intent.putExtra("finduser", finduserjson);
                startActivity(intent);
    }



    @Override
    protected void onCancelled() {
        // TODO Auto-generated method stub
        super.onCancelled();

    }



}

错误如下

  09-25 13:00:30.997: E/AndroidRuntime(5906): FATAL EXCEPTION: AsyncTask #3
09-25 13:00:30.997: E/AndroidRuntime(5906): java.lang.RuntimeException: An error occured while executing doInBackground()
09-25 13:00:30.997: E/AndroidRuntime(5906):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
09-25 13:00:30.997: E/AndroidRuntime(5906):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
09-25 13:00:30.997: E/AndroidRuntime(5906):     at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
09-25 13:00:30.997: E/AndroidRuntime(5906):     at java.util.concurrent.FutureTask.run(FutureTask.java:239)
09-25 13:00:30.997: E/AndroidRuntime(5906):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
09-25 13:00:30.997: E/AndroidRuntime(5906):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
09-25 13:00:30.997: E/AndroidRuntime(5906):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
09-25 13:00:30.997: E/AndroidRuntime(5906):     at java.lang.Thread.run(Thread.java:841)
09-25 13:00:30.997: E/AndroidRuntime(5906): Caused by: java.lang.NullPointerException
09-25 13:00:30.997: E/AndroidRuntime(5906):     at com.example.socketserver.MainActivity$getresponse111.doInBackground(MainActivity.java:231)
09-25 13:00:30.997: E/AndroidRuntime(5906):     at com.example.socketserver.MainActivity$getresponse111.doInBackground(MainActivity.java:1)
09-25 13:00:30.997: E/AndroidRuntime(5906):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
09-25 13:00:30.997: E/AndroidRuntime(5906):     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
09-25 13:00:30.997: E/AndroidRuntime(5906):     ... 4 more

4 个答案:

答案 0 :(得分:2)

<强>步骤 ::

  • 只需使用两个AsyncTasks
  • onStart()
  • 启动第一个AsyncTask
  • 从第一个onPostExecute()启动第二个AsyncTask 的AsyncTask
  • 因此,当第一个AsyncTask完成时,第二个AsyncTask就是。{ 从头开始

Here is an Example::

    public class FrgLatein extends Fragment {
        //New-Instance
        public static FrgLatein newInstance(){
            Log.d("FrgLatein", "newInstance");
            FrgLatein fragment = new FrgLatein();
            return  fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            Log.d("FrgLatein", "onCreateView");
            View view=inflater.inflate(R.layout.frg_latein, container, false);
            setHasOptionsMenu(true);


            return view;
        }

        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            Log.d("FrgLatein", "onActivityCreated");
            super.onActivityCreated(savedInstanceState);

        }

        @Override
        public void onStart() {
            Log.d("FrgLatein", "onStart");
            super.onStart();
            new LongOperation1().execute("");

        }

    private class LongOperation1 extends AsyncTask<String, Void, String> {

            @Override
            protected String doInBackground(String... params) {
                 // Do the Web service long run here
                return "Executed";
            }

            @Override
            protected void onPostExecute(String result) {
              // Do the UI-task here
              new LongOperation2().execute("");
            }

            @Override
            protected void onPreExecute() {
              // Do the UI-task here
            }

            @Override
            protected void onProgressUpdate(Void... values) {
              // Do the UI-task here which has to be done during backgroung tasks are running like a downloading process
            }
        }



 private class LongOperation2 extends AsyncTask<String, Void, String> {

            @Override
            protected String doInBackground(String... params) {
                 // Do the Web service long run here
                return "Executed";
            }

            @Override
            protected void onPostExecute(String result) {
              // Do the UI-task here
            }

            @Override
            protected void onPreExecute() {
              // Do the UI-task here
            }

            @Override
            protected void onProgressUpdate(Void... values) {
              // Do the UI-task here which has to be done during backgroung tasks are running like a downloading process
            }
        }

    }

答案 1 :(得分:1)

你在另一个AsyncTask的onPostExecute中的Async任务,我发布了一些Pseudocode。

class AsyncTask1 extends AsynTask<Void, Void, String>{
       @Override
        protected String doInBackground(Void... params) {
            //TODO something
            return s;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void onPostExecute(String result) {
          // Handle JSON response of your result. 
          //TODO call another AsyncTask
          AsyncTask2.execute();
        }
   }

在另一个AsyncTask的postExecute中,您可以调用所需的任何Activity。

class AsyncTask2 extends AsynTask<Void, Void, String>{
           @Override
            protected String doInBackground(Void... params) {
                //TODO something
                return s;
            }

            @SuppressWarnings("unchecked")
            @Override
            protected void onPostExecute(String result) {
              // Handle JSON response of your result. 
              //TODO call Activity

            }
       }

答案 2 :(得分:0)

使用onPostExecute()方法。喜欢,

@Override 
    protected void onPostExecute(Void result) {
        // TODO Auto-generated method stub 
        super.onPostExecute(result);
        try 
        { 
            if (pd.isShowing())
                pd.dismiss();
        } 
        catch(Exception e)
        { 

        } 

     // If you want to call one more AsyncTask then call it here 
     // new AsyncClassName(_context).execute();   Your question is vague, please clarify it. 

       String t = finduserjson.substring(
            finduserjson.indexOf("{"), 
            finduserjson.lastIndexOf(",{")); 
    String j = "]}";
    finduserjson = t + j;
    Log.d("FINDUSERJSON", "FINDUSERJSON" + finduserjson);

      Intent intent = new Intent(MainActivity.this,
                MenuScreen.class);  
        intent.putExtra("onlineuser", onlineuser);
        intent.putExtra("finduser", finduserjson);
        startActivity(intent);

    } 

答案 3 :(得分:0)

只需将您的代码放入onPostExecute方法: 此方法在onBackground之后调用,您可以从中启动另一个asyncTask或启动活动或任何其他操作。

@Override
protected void onPostExecute(Void result) {
    // TODO Auto-generated method stub
    super.onPostExecute(result);
    String t = finduserjson.substring(
            finduserjson.indexOf("{"),
            finduserjson.lastIndexOf(",{"));
    String j = "]}";
    finduserjson = t + j;
    Log.d("FINDUSERJSON", "FINDUSERJSON" + finduserjson);
    try
    {
        if (pd.isShowing())
            pd.dismiss();
        Intent intent = new Intent(MainActivity.this,
                MenuScreen.class); 
        intent.putExtra("onlineuser", onlineuser);
        intent.putExtra("finduser", finduserjson);
        startActivity(intent);
    }
    catch(Exception e)
    {
    }
}

You can read about onPostExecute