Android Async任务获取结果

时间:2013-02-23 09:52:17

标签: android

我在主要活动中调用Async Task类:这里是代码

 public class MainActivity extends Activity implements AsyncResponse {

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



                        Connection connection=new Connection();
                        connection.execute();



                    }
        Here is my Connection class:
        class  Connection extends AsyncTask<String,String, Void>
        {
            public AsyncResponse delegate=null;
            String result = "";
             InputStream is=null;
            @Override
            protected Void doInBackground(String... params) {


                // TODO Auto-generated method stub
                /*ArrayList<NameValuePair> nameValuePairs = null;
                  int i=0;

                     String username=params[i].toString();
                     String password=params[i+1].toString();
                     String validation=params[i+2].toString();
                  nameValuePairs = new ArrayList<NameValuePair>();
                 nameValuePairs.add(new BasicNameValuePair("username",username));
                 nameValuePairs.add(new BasicNameValuePair("password",password));

               //  nameValuePairs.add(new BasicNameValuePair("username",));*/
                try{
                        HttpClient httpclient = new DefaultHttpClient();
                        HttpPost httppost = new HttpPost("http://10.0.2.2/connection.php");
                      //  httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                        HttpResponse response = httpclient.execute(httppost);
                        HttpEntity entity = response.getEntity();
                         is = entity.getContent();
                }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);
                        StringBuilder sb = new StringBuilder();
                        String line = null;
                        while ((line = reader.readLine()) != null) {
                                sb.append(line + "\n");
                        }
                        is.close();

                        result=sb.toString();
                }catch(Exception e){
                        Log.e("log_tag", "Error converting result "+e.toString());
                }
                return null;
                // TODO Auto-generated method stub
                }
            protected void onPostExecute(Void v) {

             try{


                 JSONArray jArray = new JSONArray(result);

                 delegate.processFinish(jArray);

               //  labels2.add(password);


               //Returndata(labels2); 

             }

             catch(JSONException e){
                 Log.e("log_tag", "Error parsing data "+e.toString());
         }
        }




        }

在post post上我将Jarray发送到一个接口:并在我的主Activity中使用该接口:             这是我的界面:

public interface AsyncResponse {

            void processFinish(JSONArray jArray);

        }

并使用它这样的主要活动:

 @Override
        public void processFinish(JSONArray jarray) {
            // TODO Auto-generated method stub
            try {
                for(int i=0;i<=jarray.length();i++)
                   {
                             JSONObject json_data;
                json_data = jarray.getJSONObject(i);
                String  username=json_data.getString("username");
                 String password=json_data.getString("password");
                 Toast.makeText(getBaseContext(),username+password,Toast.LENGTH_LONG).show();
            }

                 }
                catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

2 个答案:

答案 0 :(得分:3)

只是一个建议当你的doInBackground方法返回String时,onPostExecute中的params将具有doInBackground的返回值。你不必声明一个单独的字符串。看看下面,

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected String doInBackground(URL... urls) {
         String someresult = "got from some operations";
         return someresult;
     }

     protected void onPostExecute(String result) {
         System.out.println("The resulting string from doInBackground is " + result);
     }
 }

其次使用Connection类,

public AsyncResponse delegate=null;

你还没有初始化委托变量,它是null!所以你有一个Null指针异常。你永远不能在java中实例化一个接口。但是,您可以通过接口类型引用实现接口的对象。希望这会有所帮助。

编辑:

如果您有一个B类实现的界面,那么您可以拥有AsyncResponse test = new B();,如下所示

public interface AsyncResponse 
{
}
public class B implements AsyncResponse 
{
}

public static void main(String[] args)
{
    AsyncResponse  test = new B();
}

现在在Android中,您无法实例化一个Activity。而是引用该活动实例。我打赌你有一个方法。

答案 1 :(得分:0)

我认为代码没有声明正在使用的接口。

在MainActivity类中应该声明以下内容。

您创建的连接线程未声明任何接口。

因此它将被声明为null值。

        public class MainActivity extends Activity implements AsyncResponse {

            Connection connection=new Connection(); // You shud declare on top

                @Override

                protected void onCreate(Bundle savedInstanceState) {

                    connection.delegate=this;

                    super.onCreate(savedInstanceState);

                    setContentView(R.layout.activity_main);


                    connection.execute();



                }