如何从Thread获得返回值?

时间:2014-07-15 09:10:26

标签: android multithreading web-services webserver getter-setter

我正在Thread使用Webservice,但我无法从Thread获取数据,因为我无法从Thread返回数据。

这是我的WebService.java

public class Webservice {
    static String result;
    public static String readUrl(final String url) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    HttpClient client = new DefaultHttpClient();
                    HttpPost method = new HttpPost(url);
                    HttpResponse response = client.execute(method);
                    InputStream stream = response.getEntity().getContent();
                    result = ConvertInputStreamToString(stream);
                    Log.i("xxx","OK" + result);

                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
            thread.start();
            return result;
    }

    private static String ConvertInputStreamToString(InputStream inputstteam) {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    inputstteam));
            StringBuilder builder = new StringBuilder();
            String line = "";

            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            return builder.toString();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

这是NotesActivity.java

public class NotesActivity extends Activity {

    private ArrayList<StructTask> nettasks = new ArrayList<StructTask>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Thread thread = new Thread(new Runnable() {

            @Override
            public void run() {
                String result = Webservice.readUrl("http://192.168.200.101:8081/note-server/");
                if (result != null) {
                    try {
                        JSONArray tasks = new JSONArray(result);
                        for (int i = 0; i < tasks.length(); i++) {
                            JSONObject object = tasks.getJSONObject(i);
                            //Log.i("LOG", "Task: " + object.getString("task_title"));
                            StructTask task = new StructTask();
                            task.id = object.getLong("task_id");
                            task.title = object.getString("task_title");
                            task.desc = object.getString("task_desc");
                            task.done = object.getBoolean("task_done");
                            nettasks.add(task);

                            for (StructTask taskes : nettasks) {
                                Log.i("LOG", "Taskes: " + taskes.id + "|" + taskes.title + "|" + taskes.desc + "|" + taskes.done);
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                } 
                else
                {
                    Log.i("OK", "TaskesOK: " + result);
                    Log.i("LOG", "Task: " + "NULL");
                }

            }
        });
        thread.start();

    }
}

这是我的StructTask.java

public class StructTask {
    public long id;
    public String title;
    public String desc;
    public boolean done;
}

此代码返回NULL。

3 个答案:

答案 0 :(得分:1)

试试这种方式

1)Webservice.java

public class Webservice {
        public interface WebCallListener{
            void onCallComplete(String result);
        }
        public static void readUrl(final String url,final WebCallListener callListener) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        HttpClient client = new DefaultHttpClient();
                        HttpPost method = new HttpPost(url);
                        HttpResponse response = client.execute(method);
                        InputStream stream = response.getEntity().getContent();
                        callListener.onCallComplete(ConvertInputStreamToString(stream));
                    } catch (ClientProtocolException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
            thread.start();
        }

        private static String ConvertInputStreamToString(InputStream inputstteam) {
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        inputstteam));
                StringBuilder builder = new StringBuilder();
                String line = "";

                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }
                return builder.toString();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }

2)NotesActivity.java

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

        Webservice.readUrl("http://192.168.200.101:8081/note-server/",new WebCallListener() {
            @Override
            public void onCallComplete(String result) {
                if (result != null) {
                    try {
                        JSONArray tasks = new JSONArray(result);
                        for (int i = 0; i < tasks.length(); i++) {
                            JSONObject object = tasks.getJSONObject(i);
                            //Log.i("LOG", "Task: " + object.getString("task_title"));
                            StructTask task = new StructTask();
                            task.id = object.getLong("task_id");
                            task.title = object.getString("task_title");
                            task.desc = object.getString("task_desc");
                            task.done = object.getBoolean("task_done");
                            nettasks.add(task);

                        }
                        for (StructTask taskes : nettasks) {
                                Log.i("LOG", "Taskes: " + taskes.id + "|" + taskes.title + "|" + taskes.desc + "|" + taskes.done);
                            }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
                else
                {
                    Log.i("OK", "TaskesOK: " + result);
                    Log.i("LOG", "Task: " + "NULL");
                }
            }
        });

    }

答案 1 :(得分:0)

您可以使用以下代码:

private class ImageDownloader extends AsyncTask {

    @Override
    protected Bitmap doInBackground(String... param) {
        // TODO Auto-generated method stub
        return myBackgroundImageDownloadFun(param[0]);
    }

    @Override
    protected void onPreExecute() {
        Log.i("Async-Example", "onPreExecute Called");
        simpleWaitDialog = ProgressDialog.show(ImageDownladerActivity.this,
                "Wait", "Downloading Image");

    }

    @Override
    protected void onPostExecute(Bitmap result) {
        Log.i("Async-Example", "onPostExecute Called");
        MyImageView.setImageBitmap(result);
        simpleWaitDialog.dismiss();

    }

答案 2 :(得分:0)

为此你可以使用AsyncTask,即

private class Webservice extends AsyncTask<Void, Void, ArrayList<StructTask>> {
    private ArrayList<StructTask> nettasks = new ArrayList<StructTask>();
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected ArrayList<StructTask> doInBackground(Void... params) {
        try {
            String result = readUrl("http://192.168.200.101:8081/note-server/");
             JSONArray tasks = new JSONArray(result);
             for (int i = 0; i < tasks.length(); i++) {
                 JSONObject object = tasks.getJSONObject(i);
                 //Log.i("LOG", "Task: " + object.getString("task_title"));
                 StructTask task = new StructTask();
                 task.id = object.getLong("task_id");
                 task.title = object.getString("task_title");
                 task.desc = object.getString("task_desc");
                 task.done = object.getBoolean("task_done");
                 nettasks.add(task);
             }
             for (StructTask taskes : nettasks) {
                 Log.i("LOG", "Taskes: " + taskes.id + "|" + taskes.title + "|" + taskes.desc + "|" + taskes.done);
             }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return nettasks;
    }
 /* after parsing response this method will be called*/


    @Override
    protected void onPostExecute(ArrayList<StructTask> result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
    }

    private String readUrl(String url) throws Exception{
        HttpClient client = new DefaultHttpClient();
        HttpPost method = new HttpPost(url);
        HttpResponse response = client.execute(method);
        InputStream stream = response.getEntity().getContent();
        String result = ConvertInputStreamToString(stream);
        Log.i("xxx", "OK" + result);
        return result;
    }

    private String ConvertInputStreamToString(InputStream inputstteam) {
        try {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(inputstteam));
            StringBuilder builder = new StringBuilder();
            String line = "";

            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            return builder.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

在onCreate方法的活动类中尝试像这样调用

Webservice service = new Webservice(); service.excute();

所以它将开始执行上述线程。

我认为这会对你有所帮助