需要访问Main Class中的AsyncTask值

时间:2013-04-16 09:07:57

标签: android android-asynctask

我在异步任务中遇到问题,任何人都可以向我建议任何解决方案 我从这个链接下载了这个例子:
Source

我目前的结构是

  • Main Class扩展了MyTask并实现了AsyncTaskCompleteListener接口。
  • AsyncTaskCompleteListener是一个包含onTaskComplete方法的接口。
  • MyTask扩展Async Task,onPostExcute包含CallBackMethod,它将返回从doInBackground获得的结果集。
  • Http Class(Utils)包含Http连接,并将结果集从PostExecute返回到AsyncTaskComleteListner。

我试图从接口方法中获取主类中的结果集值以执行我的进一步操作 我试图从静态变量获取值,静态方法但它们没有工作,并尝试创建一个新的类对象来发送和接收结果,但每次它给我 NullPointerException 。因为AsyncTask之后写的语句在获得结果之前执行。

我还试图从其方法getStaus()获取asyncTask的状态,但它只返回Running并且当任务完成或完成时不会发出通知。

以下是代码示例:

主类代码:

package com.example.androidasynctask;


public class MainActivity extends Activity implements AsyncTaskCompleteListener {

public static String[] asyncResult;
String res[] = null;



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void btnclick(View view) {
    /*MyTask asyncTask = new MyTask(this);
    String [] asyncTaskResult = asyncTask.execute("fetchCategory.php","1%Id%1");*/

    //AsyncTask<String, Void, String[]> asyncTaskRes = new MyTask(this).execute("fetchCategory.php","1%Id%1");
    //new MyTask(this).execute("fetchCategory.php","1%Id%1");
    MyTask asyncTask = (MyTask) new MyTask(this).execute("fetchCategory.php","1%Id%1");

     if(asyncTask.getStatus().equals(AsyncTask.Status.FINISHED) || asyncTask.getStatus().equals(AsyncTask.Status.PENDING)) {
         asyncTask.execute();
     }
     else {

         Log.v("In Else","Get Value");
     }



}

@Override
public void onTaskComplete(String[] result) {
    Log.v("IN ON TASK COMPLETE","VALUE = "+result[1]);


}



/*@Override
public void onTaskComplete(String result) {
    System.out.println("calling onTaskComplete SIMPLE....");
    System.out.println("result :: "+ result);
}*/

public static class GetAsyncResult
{
    static String[] returnValues;


    public GetAsyncResult()
    {}
    public GetAsyncResult(String[] res)
    {

        returnValues = res;
        Log.v("getResultSetValues","returnValues"+returnValues[1]);
    }


    public void getResultSetValues()
    {
        Log.v("getResultSetValues","returnValues"+returnValues[1]);


    }

}

}

异步任务代码:

public class MyTask extends AsyncTask<String, Void, String[]> {

private Activity activity;
private ProgressDialog dialog;
private AsyncTaskCompleteListener callback;
public String[] asyncResultSetValue = null;
public MyTask(Activity act) {
    Log.v("MY TASK","ACTIVITY"+act);
    this.activity = act;
    this.callback = (AsyncTaskCompleteListener)act;
}

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

    Log.v("MY TASK","in ON PRE EXECUTE");
    dialog = new ProgressDialog(activity);
    dialog.setMessage("Loading...");
    dialog.show();
}

@Override
protected String[] doInBackground(String... params) {
    Log.v("MY TASK","DO IN BACKGROUND");
    Log.v("PARAMS"," params[0] = "+params[0]+ "| params[1]"+params[1]);
    asyncResultSetValue = Utils.process_query(params[0],params[1]);
    return asyncResultSetValue;
}

@Override
protected void onPostExecute(String[] result) {
    super.onPostExecute(result);
    Log.v("MY TASK","in ON POST EXECUTE");
    if (null != dialog && dialog.isShowing()) {
        dialog.dismiss();
    }
    callback.onTaskComplete(result);
}

}

HTTP CLASS CODE:

 public class Utils {

    static String result = null;
    String endResult;
    static java.io.InputStream  is = null;
    static StringBuilder sb=null;
    static String delimiter = "\\|";            
    static String delimiter1 = "\\%";
    static String[] temp = null;
    static String[] temp1 = null;
    static ArrayList<NameValuePair> nameValuePairs;
    static Context context;
    static ProgressDialog mDialog;
    static HttpResponse response;
    static String[] resultset_value = null;
    //static String url = "http://fortuneworkinprogress.in/News_App/";  //Global URL
    static String url = "http://10.0.2.2/News_App/";    //Global URL
    static String query_type,parameter;     

    /*************** PROCESS QUERY START  ***************/
      public static String[] process_query(String str_url, String parameter) {
            // String strval = select_parameter;
        String ret_val[] = null;
        String get_sel_val[] = null;    
        int loopcount =0;
        url = url+str_url;                                                                  //!!!! ######### CONCATINATING AND CREATING FULL URL ######## !!!!!!//
        Log.v("PROCESS QUERY PARAMETER","URL = "+url+" | PARAMTER = "+parameter);
        nameValuePairs = new ArrayList<NameValuePair>();

        //Log.i("STR VAL",""+strval);       //To Check which values are recieved
        try
        {
            String strval = parameter;
            get_sel_val=strval.split(delimiter1);

            for(int i =0; i < get_sel_val.length ; i++)     
            {

                loopcount = Integer.parseInt(get_sel_val[0]);           // First Delimeted Value which tells the number of count
                Log.i("Loopcount","cnt = "+loopcount);

            }

            for(int j=1;j<=(loopcount*2);j=j+2)                         //For Loop for making Name Values Pares Dynamic
            {
                nameValuePairs.add(new BasicNameValuePair(get_sel_val[j],get_sel_val[j+1]));
                //Log.i("J = ["+j+"]","pairvalue1 = "+get_sel_val[j]+"pairvalue2 ="+get_sel_val[j+1]);
            }
        }
        catch(Exception e)
        {
            Log.w("Exception in the getting value","Exp = "+e);
        }

        //nameValuePairs.add(new BasicNameValuePair("id","1"));

        try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(url);
                Log.v("CONNECT URL   ","Final url "+url);
                Log.w("CONNECTION STATUS ",httppost.toString());
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                Log.w("PAERSE VALUE ",nameValuePairs.toString());
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
                Log.w("1", "Connection establised succesfuly");
           }
         catch(Exception e)
         {
             Log.e("log_tag", "Error in http connection"+e.toString());
         }

         try{
                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                sb = new StringBuilder();
                sb.append(reader.readLine() + "\n");
                Log.v("SB VALUE = ","sb = "+sb.toString());
                String line="0";
                while ((line = reader.readLine()) != null) 
                {
                    sb.append(line + "\n");
                }
               is.close();
               result=sb.toString();

                //  Toast.makeText(getBaseContext(), result ,Toast.LENGTH_LONG).show();

                Log.w("result", result);
            }
          catch(Exception e)
          {
              Log.e("log_tag", "Error converting result "+e.toString());
              Toast.makeText(null, "error converting response to string" ,Toast.LENGTH_LONG).show();
          }

         String[] temp = null;
         String[] tempResult = null;

         if(result!=null)
         {
             tempResult = result.split(delimiter);                  //Split the entire return string into "rows"
             for(int i =0; i < tempResult.length-1 ; i++)       
              {
                 temp = null;   
                 temp = tempResult[i].split(delimiter1);        //Find columns for each row
                 ret_val = temp;
                 resultset_value=ret_val;
              }
        }
        else
        {
            Toast.makeText(null, "Cannot Find Routes" ,Toast.LENGTH_LONG).show();
        }

         Log.v("BEFORE RETUNR = ","ret_val = "+ret_val.toString());
         return ret_val;                                            //Returning the result value array
    }


                    /*************** PROCESS QUERY ENDS ***************/

      public static boolean isNetworkAvailable(Activity activity) 
      {
        ConnectivityManager connectivity = (ConnectivityManager) activity
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) 
        {
            return false;
        } 
        else
        {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) 
            {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) 
                    {
                        return true;
                    }
                }
            }
        }
        return false;
    }

}

提前致谢。

1 个答案:

答案 0 :(得分:0)

Because the statement written after the AsyncTask gets executes before getting the result.

原因是AsyncTask在单独的线程上运行,而不是在主(UI)线程上运行。

MyTask extends Async Task and onPostExcute contains CallBackMethod which will return the result-set got from the doInBackground.

您将获得此方法的结果值

   @Override
public void onTaskComplete(String[] result) {
    Log.v("IN ON TASK COMPLETE","VALUE = "+result[1]);


}

评论一段代码,

    if(asyncTask.getStatus().equals(AsyncTask.Status.FINISHED) || asyncTask.getStatus().equals(AsyncTask.Status.PENDING)) {
     asyncTask.execute();
 }
 else {

     Log.v("In Else","Get Value");
 }

进行更改,

public static String[] asyncResult;public String[] asyncResult = null;

更改以下内容,

asyncResultSetValue = Utils.process_query(params[0],params[1]);asyncResult = Utils.process_query(params[0],params[1]);return asyncResultSetValue;return asyncResult ;

通过添加一个日志来查看值,您将获得此方法的结果值

   @Override
public void onTaskComplete(String[] result) {
    Log.v("IN ON TASK COMPLETE","VALUE = "+result[1]);
    Log.v("IN ON TASK COMPLETE","VALUE = "+asyncResult[1]);

}