Threads and Asynctask task use for httppost

不羁的心 提交于 2020-01-23 11:02:20

问题


Friends ,i need help to android httppost data to server using Asynctask or Threads I need to send data to my server when i click post button.But when i click it app need to go to next page and data need to send through as background process.I'm new to Android.I don't know what is exactly use for this kind of task (Threads or Asyanctask). I tried this code but it will give me exception error

public void startProgress(final String name) {
        // Do something long
        Runnable runnable = new Runnable() {
            @Override
            public void run() {               
               try {
                   Thread.sleep(500);
                   send(name);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

             }
        };
        new Thread(runnable).start();
    }


    public void send(String name)
    {
        // get the message from the message text box
           HttpClient httpclient = new DefaultHttpClient();
           HttpPost httppost = new HttpPost("http://10.0.2.2:8080/Test");
           try {
                 List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                 String co2 =input_field.getText().toString(); 
                 nameValuePairs.add(new BasicNameValuePair("Name", name));
                 httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                 Toast toast = Toast.makeText(getApplicationContext(), "Got it ", Toast.LENGTH_SHORT);
                 toast.show();
                 httpclient.execute(httppost);
                 input_field.setText("");
            } catch(Exception e){
                 Toast toast2 = Toast.makeText(getApplicationContext(),  "error", Toast.LENGTH_SHORT);
                 toast2.show();
            }
    }

but if i use it this way it works.(text is TextView item in that page)

public void startProgress(final String name) {
        // Do something long
        Runnable runnable = new Runnable() {
          @Override
          public void run() {



               try {
                Thread.sleep(500);

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


             text.post(new Runnable() {
                @Override
                public void run() {

                    send(name);
                }
              });
            }


        };
        new Thread(runnable).start();
      }

What happen in bellow piece of code can you please explain about this also

text.post(new Runnable() {
                    @Override
                    public void run() {

                        send(name);
                    }
                  });

please help me to solve this problem.If there is better way to do my need please mentioned it .Because it have very less experience about Android development


回答1:


You can do this by using AsyncTask like this:

public class HttpPostExanple extends AsyncTask<String, Void, String> 
{       

    @Override
    protected String doInBackground(String... params)   
    {           
        BufferedReader inBuffer = null;
        String url = "http://10.0.2.2:8080/Test";
        String result = "fail";
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost request = new HttpPost(url);
            List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
            postParameters.add(new BasicNameValuePair("name", params[0]));

            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
                    postParameters);

            request.setEntity(formEntity);
             httpClient.execute(request);
                    result="got it";

        } catch(Exception e) {
            // Do something about exceptions
            result = e.getMessage();
        } finally {
            if (inBuffer != null) {
                try {
                    inBuffer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return  result;
    }

    protected void onPostExecute(String page)
    {       
        //textView.setText(page); 
        Toast toast = Toast.makeText(getApplicationContext(), page, Toast.LENGTH_SHORT);
      toast.show();
    }   
}  

And you need to have this in your main method

new HttpPostExample().execute(new String[] {name}); 

Check this out. Hope this will help you.




回答2:


You should implement something like this:

new Thread(new Runnable() {
    public void run() {
      send(name); // if this method need to access the UI interface you have to use .post method 
    }
  }).start();

About your question: the .post method causes the Runnable to be added to the message queue. The runnable will be run on the user interface thread. [reference]

And this is required because without this method you violate the single thread model: the Android UI toolkit is not thread-safe and must always be manipulated on the UI thread. In your piece of code, the TextView is manipulated on a worker thread, which can cause really weird problems.

As you can see, If the method inside your thread need to access the UI you should use .post method, and this make more laborious the code. So the right solution may be use the AsyncTask that will manage for you the complexity of the threads. You have to put the piace of code that need to access on the UI, in the onPostExecute() method




回答3:


I suggest you to use robospice or other frameworks as alternative:

  • Volley
  • DataDroid
  • REST Provider
  • REST Droid
  • PostMan (rings twice) Lib
  • Ion
  • droidQuery
  • Android Job Queue
  • Goro

    because activity can be recreated before onPostExecute reached. AsyncTask is not good example for networking in Activity.



来源:https://stackoverflow.com/questions/19124150/threads-and-asynctask-task-use-for-httppost

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