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.

3
  • this may help you: stackoverflow.com/questions/22816335/… Commented Dec 19, 2014 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 Commented Dec 19, 2014 at 16:59
  • alright: maybe this one? stackoverflow.com/questions/20058240/… Commented Dec 19, 2014 at 17:02

1 Answer 1

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");
}
Sign up to request clarification or add additional context in comments.

7 Comments

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?
You can write the POST header into the URLConnection's output stream
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?
I guess you could just use HttpURLConnection urlConnection = (HttpURLConnection) (new URL("http://www.rgbpallete.in/led/api/signup").openConnection());
Oh sorry, I just added the post stuff from here: stackoverflow.com/questions/9767952/…
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.