0

I am developing an android app, I have run into a situation where the app will use an API to send some data to the php webservice and the webservice will greate some json encoded message which will be echoed back.

My question is

  1. How Do I store this json message that was sent by php echo into a variable in the android app?
  2. How Do I then go about parsing the json and use the data to construct a switch case?

I had raised a similar question sometime back and was told to use AsyncTask but what I don't understand is why would I need to use it.

The sample json response that will be sent by the phpwebservice is

{"error":false,"message":"New user created"}

I want to be able to get the error variable and decide if there is any error and also get the message in a variable and display it to the user in the app.

I currently have the android signup.java code like this

public void post() throws UnsupportedEncodingException
    {
        // Get user defined values
        uname = username.getText().toString();
        email   = mail.getText().toString();
        password   = pass.getText().toString();
        confirmpass   = cpass.getText().toString();
        phone = phn.getText().toString();

        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse httpResponse = null;
        HttpPost httppost = new HttpPost("http://www.rgbpallete.in/led/api/signup");
        if (password.equals(confirmpass)) {
            try {
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
                nameValuePairs.add(new BasicNameValuePair("uname", uname));
                nameValuePairs.add(new BasicNameValuePair("pass", password));
                nameValuePairs.add(new BasicNameValuePair("email", email));
                nameValuePairs.add(new BasicNameValuePair("phone", phone));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                httpResponse = httpclient.execute(httppost);
                //Code to check if user was successfully created
                final int statusCode = httpResponse.getStatusLine().getStatusCode();
                switch (statusCode)
                {
                    case 201:
                        Toast.makeText(getBaseContext(), "Successfully Registered", Toast.LENGTH_SHORT).show();
                        break;
                    case 400:
                        Toast.makeText(getBaseContext(), "Username already taken", Toast.LENGTH_SHORT).show();
                        username.setText("");
                        break;
                    default:
                        Toast.makeText(getBaseContext(), "Unknown error occurred", Toast.LENGTH_SHORT).show();
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else
        {
            Toast.makeText(getBaseContext(), "Password mismatch", Toast.LENGTH_SHORT).show();
            //Reset password fields
            pass.setText("");
            cpass.setText("");
        }

    }

While this checks the http header code and might work( I havent tested it out) I want to use the jsnon response and do the handling using it.

Rick Roy
  • 1,656
  • 2
  • 21
  • 47
  • this may help you: http://stackoverflow.com/questions/22816335/java-httprequest-json-response-handling – mboeckle Dec 19 '14 at 16:50
  • Thank you although it is a similar case to mine but in that example the guy is posting a json message I just want to post simple data over http post – Rick Roy Dec 19 '14 at 16:59
  • alright: maybe this one? http://stackoverflow.com/questions/20058240/extracting-data-from-json-array – mboeckle Dec 19 '14 at 17:02

1 Answers1

1

Use java-json:

HttpURLConnection urlConnection = (HttpURLConnection) (uri.toURL().openConnection());
urlConnection.setConnectTimeout(1500);
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("uname", uname));
params.add(new BasicNameValuePair("pass", password));
params.add(new BasicNameValuePair("email", email));

OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(
    new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();

urlConnection.connect();
if(urlConnection.getResponseCode() == 200){
    InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
    BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
    StringBuilder responseStrBuilder = new StringBuilder();

    String inputStr;
    while ((inputStr = streamReader.readLine()) != null)
        responseStrBuilder.append(inputStr);
    JSONObject json = new JSONObject(responseStrBuilder.toString());
    String message = json.getString("message");
}
tachyonflux
  • 20,103
  • 7
  • 48
  • 67
  • But from what I understand this only opens the url and gets the response. But in my case the app has to first post data to the php file and then on the basis of this data the php will generate a json. Will that same thing work in here? – Rick Roy Dec 19 '14 at 16:53
  • You can write the POST header into the URLConnection's output stream – tachyonflux Dec 19 '14 at 17:02
  • the toURL() function has to be defined by me or is predefined, if it is predefined which class do I need to import coz my studio says that it Cannot resolve the method. Also in the `uri.toURL()` I assumed `uri` is a string variable which will store the url, is my assumption correct? – Rick Roy Dec 19 '14 at 17:24
  • I guess you could just use `HttpURLConnection urlConnection = (HttpURLConnection) (new URL("http://www.rgbpallete.in/led/api/signup").openConnection());` – tachyonflux Dec 19 '14 at 17:36
  • Thanks just one last query, in the code `writer.write(getQuery(params));` the `getQuery()` cannot be resolved any idea into why? I am sorry this is my first app and my android app developer is sick, I don't really know much about android programming @tachyonflux – Rick Roy Dec 19 '14 at 17:40
  • 1
    Oh sorry, I just added the post stuff from here: http://stackoverflow.com/questions/9767952/how-to-add-parameters-to-httpurlconnection-using-post/13486223#13486223 – tachyonflux Dec 19 '14 at 17:43
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/67345/discussion-between-rick-roy-and-tachyonflux). – Rick Roy Dec 19 '14 at 17:46