How get return value from Thread?

让人想犯罪 __ 提交于 2020-01-11 14:45:50

问题


I am using Thread for Webservice but i cant get the data from Thread because i cant return data from Thread.

This is my 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;
    }
}

This is 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();

    }
}

This is my StructTask.java :

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

This code return for me NULL .


回答1:


Just try this way

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

    }



回答2:


You may use your code some thing like this:

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();

    }



回答3:


For this you can use AsyncTask i.e,

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

In your activity class in onCreate method try to call like this

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

so it will starts the excution of the above thread.

i think this will helps you



来源:https://stackoverflow.com/questions/24754164/how-get-return-value-from-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!