2

i new to android and i have developed an application to post and get the response from a php server.

AsyncTask

    class MyTask extends AsyncTask<String, Void, String> {


    @Override
    protected String doInBackground(String... arg0) {


        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://172.16.110.3/agent_tracking/index.php/api/rest/auth");

        try {
            // Add your data
            List<BasicNameValuePair> nameValuePairs = new ArrayList<>(1);
            nameValuePairs.add(new BasicNameValuePair("key", arg0[0]));
           // nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            String responseString = EntityUtils.toString(entity, "UTF-8");

            return responseString;

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }
        return null;
    }
}

Main Class

  Button login = (Button) findViewById(R.id.btn_login);
    login.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            EditText username = (EditText) findViewById(R.id.et_user_name);
            EditText password = (EditText) findViewById(R.id.et_password);

            String user_name = username.getText().toString();
            String paswrd = password.getText().toString();
            String timeStamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());

            String data2 = user_name + "|" + paswrd + "|" + timeStamp;

            byte[] data = new byte[0];
            try {
                data = data2.getBytes("UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            String base64 = Base64.encodeToString(data, Base64.DEFAULT);

            show_message(base64);
            new MyTask().execute(base64);
            //postData();
            //startActivity(new Intent(MainActivity.this, mainmenu.class));
        }
    });

My problem is am returning a value called responseString from the AsyncTask. I want to catch that value from the main class and display it in the message box.

i tried like this

     String result = new MyTask().execute(base64);

i am getting the error incomparable type error.

Can some one help me to get the returned vale to the main class

Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
Sathya Baman
  • 3,424
  • 7
  • 44
  • 77

5 Answers5

2

There are multiple way to achieve this. I am describing the one way in steps:

1) Create a method in your activity which will perform the desired action on activity like.

public void showData(String responseString)
{
    tvText.setText(responseString)
}

2) When you are calling your asyncTask pass activity object in asyncTask like

new MyTask(MainClass.this).execute(base64);

3) Call showData method from onPostExecute like:

mainclassObj.showData(response);
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
Sulabh Jain
  • 342
  • 1
  • 9
1

Based on answer @BlackBelt linked... This will do the trick for you:

String result = new MyTask().execute(base64).get();
Community
  • 1
  • 1
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
  • IMO , this not ideal **1.)** Don't assume you will get the response as quickly as possible and beware of network problem **2.)** Since result is a product of async you might get null pointer if you use this value before async returns any results. – neferpitou Jun 30 '15 at 13:59
0

You can override the onPostExecute method of the AsyncTask. The return value(responseString ) is the parameter of the onPostExecute. Then you can show your message use the parameter.

CodeS
  • 1
0

You can't return any data from asynchronous methods directly, like you posted String result = new MyTask().execute(base64);

But to achieve your goal you can use onPostExecute() method of asynctask

onPostExecute(String result) {
    yourTextView.setText(result);
}
Vladyslav Matviienko
  • 10,610
  • 4
  • 33
  • 52
0

It has to be handled via Response callbacks. Which gets triggered on either success or failure cases. I suggest you to use Network Managing libraries like loopj or volley, which takes care of request threads and also callbacks.

Charan
  • 942
  • 1
  • 6
  • 18