Chris Mikkelsen Chris Mikkelsen - 6 months ago 29
Android Question

How do I get the value of a string variable from a JSONParser class?

I have a log-in web API which returns true if you have successfully logged-in and false otherwise.

Now I want to get that returned value which is why I have made used of this

PostAsync
Class calling on an
HttpRequest
Method from the
JSONParser
Class.

These are the codes:

public class Sign_inFragment extends Fragment {

String email, password, logInResult;
EditText ev, pv;
Button bv;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.sign_in_fragment, container, false);

bv = (Button) v.findViewById(R.id.signinButton);
ev = (EditText) v.findViewById(R.id.emailTextView);
pv = (EditText) v.findViewById(R.id.passwordTextView);

bv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ev.getText() != null && pv.getText() != null) {
email = ev.getText().toString();
password = pv.getText().toString();

new PostAsync().execute(email, password);

//logInResult = //Get the value from the API which should return true or false
}
}
});

return v;
}
}





public class PostAsync extends AsyncTask<String, String, JSONObject> {

JSONParser jsonParser = new JSONParser();

private ProgressDialog pDialog;

private static final String LOGIN_URL = "http://my-api.mydoctorfinder.com/logger";

private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";


/*@Override
protected void onPreExecute() {
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Attempting login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}*/

@Override
protected JSONObject doInBackground(String... args) {

try {

HashMap<String, String> params = new HashMap<>();
params.put("email", args[0]);
params.put("password", args[1]);

Log.d("request", "starting");

JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);

if (json != null) {
Log.d("JSON result", json.toString());

return json;
}

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


return null;
}

protected void onPostExecute(JSONObject json) {

int success = 0;
String message = "";

if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}

if (json != null) {
//Toast.makeText(MainActivity.this, json.toString(),
//Toast.LENGTH_LONG).show();

try {
success = json.getInt(TAG_SUCCESS);
message = json.getString(TAG_MESSAGE);
} catch (JSONException e) {
e.printStackTrace();
}
}

if (success == 1) {
Log.d("Success!", message);
}else{
Log.d("Failure", message);
}
}

}





public class JSONParser {
String charset = "UTF-8";
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result;
URL urlObj;
JSONObject jObj = null;
StringBuilder sbParams;
String paramsString;
String logInResult;

public JSONObject makeHttpRequest(String url, String method, HashMap<String, String> params) {

sbParams = new StringBuilder();
int i = 0;
for (String key : params.keySet()) {
try {
if (i != 0){
sbParams.append("&");
}
sbParams.append(key).append("=")
.append(URLEncoder.encode(params.get(key), charset));

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}

if (method.equals("POST")) {
// request method is POST
try {
urlObj = new URL(url);

conn = (HttpURLConnection) urlObj.openConnection();

conn.setDoOutput(true);

conn.setRequestMethod("POST");

conn.setRequestProperty("Accept-Charset", charset);

conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);

conn.connect();

paramsString = sbParams.toString();

wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(paramsString);
wr.flush();
wr.close();

} catch (IOException e) {
e.printStackTrace();
}
}
else if(method.equals("GET")){
// request method is GET

if (sbParams.length() != 0) {
url += "?" + sbParams.toString();
}

try {
urlObj = new URL(url);

conn = (HttpURLConnection) urlObj.openConnection();

conn.setDoOutput(false);

conn.setRequestMethod("GET");

conn.setRequestProperty("Accept-Charset", charset);

conn.setConnectTimeout(15000);

conn.connect();

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

}

try {
//Receive the response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}

Log.d("JSON Parser", "result: " + result.toString());

logInResult = result.toString();//I want to get the value of this String variable.

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

conn.disconnect();

// try parse the string to a JSON object
try {
jObj = new JSONObject(result.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON Object
return jObj;
}

}

Answer

You have the following solutions:
Make the async task doInBackground method return an object of your desire and inside the doInBackground parse your json and save some values inside this object.
Then in onPostExecute you get the object and return it to the caller(activity, fragment, etc) via a callback.
Solution two, just return the desired string in doInBackground and get it in onPostExecute and do the same as I said in the first solution. Example for the object(same goes for string):

 @Override
protected CustomObject doInBackground(String... args) {
    CustomObject customObject = null;
    try {

        HashMap<String, String> params = new HashMap<>();
        params.put("email", args[0]);
        params.put("password", args[1]);

        Log.d("request", "starting");

        JSONObject json = jsonParser.makeHttpRequest(
                LOGIN_URL, "POST", params);

        if (json != null) {
            Log.d("JSON result", json.toString());

           //parse your json;
           //for example:
           customObject = parseCustomObject(json);
        }

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


    return customObject;
}