0

i want to create a login and register system with json . i want first get content of url , next parse the json string . Json String sample :

{ "employee":{"mesg":"username is exsist!","id":0,"name":0,"username":0,"email":0,"status":500} }

i just need mesg Or status . i cant parse it . every time i want parse this string , my application give force stop

this is my code :

    package com.sourcey.materiallogindemo;

import android.app.ProgressDialog;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;



import butterknife.Bind;
import butterknife.ButterKnife;

public class SignupActivity extends AppCompatActivity {

    //URL to get JSON Array

    //JSON Node Names



    public String nurl;


    private static final String TAG = "SignupActivity";

    @Bind(R.id.input_name) EditText _nameText;
    @Bind(R.id.input_email) EditText _emailText;
    @Bind(R.id.input_tell) EditText _tellText;
    @Bind(R.id.input_password) EditText _passwordText;
    @Bind(R.id.btn_signup) Button _signupButton;
    @Bind(R.id.link_login) TextView _loginLink;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signup);
        ButterKnife.bind(this);

        _signupButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                signup();
            }
        });

        _loginLink.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Finish the registration screen and return to the Login activity
                finish();
            }
        });
    }



    public void signup() {
        Log.d(TAG, "Signup");

        if (!validate()) {
            onSignupFailed();
            return;
        }

        _signupButton.setEnabled(false);

        final ProgressDialog progressDialog = new ProgressDialog(SignupActivity.this,
                R.style.AppTheme_Dark_Dialog);
        progressDialog.setIndeterminate(true);
        progressDialog.setMessage("در حال انجام عملیات...");
        progressDialog.show();

        String name = _nameText.getText().toString();
        String email = _emailText.getText().toString();
        String tell = _tellText.getText().toString();
        String password = _passwordText.getText().toString();

        // TODO: Implement your own signup logic here.

        nurl = "http://someurl/json/user.php?type=register&mobile="+tell+"&p="+password+"&email="+email+"&name="+name;

       //new JSONParse().execute();

        new android.os.Handler().postDelayed(
                new Runnable() {
                    public void run() {

                        onSignupSuccess();
                        progressDialog.dismiss();


                    }
                }, 3000);
    }


    public void onSignupSuccess() {
        _signupButton.setEnabled(true);
        setResult(RESULT_OK, null);
        finish();
    }

    public void onSignupFailed() {
        Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show();

        _signupButton.setEnabled(true);
    }

    public boolean validate() {
        boolean valid = true;

        String name = _nameText.getText().toString();
        String email = _emailText.getText().toString();
        String tell = _tellText.getText().toString();
        String password = _passwordText.getText().toString();

        if (name.isEmpty() || name.length() < 3) {
            _nameText.setError("at least 3 characters");
            valid = false;
        } else {
            _nameText.setError(null);
        }

        if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            _emailText.setError("enter a valid email address");
            valid = false;
        } else {
            _emailText.setError(null);
        }

        if (tell.isEmpty() || !android.util.Patterns.PHONE.matcher(tell).matches()) {
            _tellText.setError("enter a valid phone number");
            valid = false;
        } else {
            _tellText.setError(null);
        }

        if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
            _passwordText.setError("between 4 and 10 alphanumeric characters");
            valid = false;
        } else {
            _passwordText.setError(null);
        }



        return valid;
    }













}

now i dont know what can i do exactly to parse string and get just status or mesg, thanks for helm . i need this very much and sorry for amature question . regards

2
  • Show code which u have tried to parse posted JSON String Commented Jan 22, 2016 at 6:32
  • You have some good answers. I would suggest you use one of the answers here, instead of creating a new question. Commented Jan 22, 2016 at 13:36

4 Answers 4

1

You can use a JSONObject for this task.

For example (omitting try/catch):

JSONObject root = new JSONObject(jsonString);
JSONObject employee = root.getJSONObject("employee");
String message = employee.getString("name");
String username = employee.getString("username");
String email = employee.getString("email");
int id = employee.getInt("id");
int status = employee.getInt("status");

If you aren't sure of the consistency of your JSON, you should check whether the key exists first.

You should also check your JSON datatypes, you appear to have integers for name, username and email. However, those are seldom integers.

JSONObject Documentation.

Sign up to request clarification or add additional context in comments.

Comments

1

There are libraries that can help you parse the Json, you can use gson or Jackson. I actually used retrofit to make the calls to my API as it then allows for you to plug in a json deserializer and then it just does all the work for you. It also handles all the HTTP calls and is rather simple to use.

Comments

1

Suggest you to go with Volley. Below is the sample code for the same

JsonObjectRequest jsonObjReqfirst = new JsonObjectRequest(Request.Method.GET,urlBuffer.toString(),null,
                    new Response.Listener<JSONObject>(){

                        @Override
                        public void onResponse(JSONObject response) {
                            Log.i(Constants.NETLOG, "Volley response= " + response.toString());
                            getResponseprocessed(response));

                        }
                    }, new Response.ErrorListener(){
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e(Constants.NETLOG, "VolleyError response= " + error.toString());

                }
            });
            Volley.newRequestQueue(mContext).add(jsonObjReqfirst);

void getResponseprocessed(JSONObject response){
            try {
                JSONObject statusObj = response.getJSONObject("employee");
                String mseg=statusObj.getString("mesg");
                int status = statusObj.getInt("status");

            } catch (JSONException e) {
                e.printStackTrace();
            }
    }

Comments

1

Use Volley library for getting JSON response from url as below -

First add library in your project Module:app dependency as below -

dependencies {
compile 'com.mcxiaoke.volley:library-aar:1.0.1'
...
}

Use below code to get response from Volley Library -

// Instantiate the RequestQueue.
    RequestQueue queue = Volley.newRequestQueue(this);
    String url = "WEBSERVICE_URL"; // eg:- "http://www.google.com";

    // Request a string response from the provided URL.
    StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {

                @Override
                public void onResponse(String response) {
                    System.out.println("Response is: " + response);
                    try {
                         JSONObject jobj = new JSONObject(response);
                         JSONObject jEmp = jobj.getJSONObject("employee");
                         String message = jEmp.getString("mesg");
                         int Status = jEmp.getInt("status");

                   } catch (JSONException e) {
                         e.printStackTrace();
                   }

                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {

                    if(error.networkResponse != null && error.networkResponse.data != null){
                        VolleyError verror = new VolleyError(new String(error.networkResponse.data));
                        System.out.println("That didn't work!\n" + error.toString());
                    }

                }

    });

    // Add the request to the RequestQueue.
    queue.add(stringRequest);

You can parse the JSON as below -

 try {
        JSONObject jobj = new JSONObject(responseJSONString);
        JSONObject jEmp = jobj.getJSONObject("employee");
        String message = jEmp.getString("mesg");
        int Status = jEmp.getInt("status");

    } catch (JSONException e) {
        e.printStackTrace();
    }

`responseJSONString` is the JSON response you got.

3 Comments

it works great , thank you ... second problem that i have is this , how can i take the content from the url and put in variable.. i work php , in php we have file_put_contents and equal content with variable, in android i down know how can i do this , thanks
thank you very much . but it give me force stop , i write like this : justpaste.it/qs5t
@persian: You need to add the volley code on some Button click. I believe its a sign-up request so put it after -> nurl = "htt....."; string definition.

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.