Check if JSON response contains certain value - java

So I'm building an Android app in Android Studio for an excisting webpage with a login feature. I connected the app succesfully to the websites database already and I can login and get a response from the server. The app is looking for an error value in the response, but the response contains no error value.
This is the code in my app:
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Launch main activity
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
This is the response the server gives when the login was succesfull:
Login Response: {"howislife":1,"rekeningnummer":"212220","soortuser":"student","datum":"05 Sep 2017"}
So when the login was succesfull it says "howislife:1", when the password or username is incorrect it says "howislife:2" or "howislife:3". So the code in my Android app needs to check what value "howislife" is. How can I do that? Thanks in advance!

Try this code,
int howislife = (!jsonObjects.isNull("howislife")) ?
jsonObjects.optInt("howislife") : 0;
if (howislife == 1) {
//login sucess
} else {
//login failed
}

I assume your api gives response always with those parameters and if the response comes empty or null then check for it before converting to JSONObject, then you could try below code, it will work.
JSONObject jObj = new JSONObject(response);
if(jObj.getInt("howislife")==1){
System.out.println("Login success");
}else{
System.out.println("Login fail");
}

There is a function "has()" to check keys for JSONObject in Android.
boolean has (String name)
Returns true if this object has a mapping for name. The mapping may be NULL.
More details:
https://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)

I solved it using this code already, thanks!
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
int login1 = jObj.getInt("howislife");
System.out.println(login1);
//Check for error node in json
if (login1 == 1) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Launch main activity
Intent intent = new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
} else if(login1 == 2) {
Toast.makeText(getApplicationContext(), "Wachtwoord verkeerd", Toast.LENGTH_LONG).show();
} else if(login1 == 3) {
Toast.makeText(getApplicationContext(), "Gebruikersnaam of/en wachtwoord verkeerd", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Er is iets fout gegaan, probeer opnieuw.", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}

Related

Android how to get user Facebook information when user is already logged in

How can I get users facebook information when he is already logged in? I think I am doing everything fine but its not working..
1st. I am getting the accessToken and checking if it exists. If it does exist I try to get user data.
AccessToken accessToken = AccessToken.getCurrentAccessToken();
if (accessToken != null) {
String userData = getUserDataFromFacebook(accessToken, headerTitle);
headerTitle.setText(userData);
}
2nd. I try to get the user data the same way as i would get it at the first facebook login.
getUserDataFromFacebook:
private String getUserDataFromFacebook(AccessToken accessToken, final TextView headerTitle) {
Log.v("LoginActivity", "I am here"); // this log works
GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.v("LoginActivity", "RESPONSE: " + response); //this log doesn`t work.
// Application code
try {
Log.v("LoginActivity", "I am here"); //this log doesn`t work
name = object.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return name;
}
The biggest problem is that the the onCompleted method is not called and I cant access any of the information. I have no idea why..
P.S. I am terrible at Java and this is my first android application.
You're not actually executing the request.
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// your logic
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link");
request.setParameters(parameters);
request.executeAsync();
Keep in mind this is an Async call so you can't return the name from the function like you've tried to do. Instead you'll have to implement a callback mechanism.
Try this code as it is it will help you to get data from facebook.
make sure you already set permission for data on FacebookLoginButton.
private void getUserDataFromFacebook() {
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.e(" Response", response.toString());
String res = (String) object.toString();
Log.e("Response", res);
Gson gson = new Gson();
if (res.length() > 0) {
//do your work here with your res
} else {
Utils.showDialog(SelectFacebookAlbumActivity.this, "",
"Error in getting data");
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name");
request.setParameters(parameters);
request.executeAsync();
}
Let us know it it works for you.

ArrayList, print only the value

I have a contactList = new ArrayList<>(); where I store information in this format: "name", value_for_name.
I populate my contactList inside this function:
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("results");
// looping through All Results
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String icon = c.getString("icon");
String id = c.getString("id");
String name = c.getString("name");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
// contact.put("id", id);
contact.put("name", name);
// contact.put("email", icon);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
The problem is that when I try to print a value:
System.out.println(contactList.get(position));
The output is in this format:
{name="Foo"}
I only want to print Foo
I tried also with: System.out.println(String.valueOf(contactList.get(position)));
but I always get the whole string: {name="Foo"}
Can you help me, please?
Do I really need to parse the string?
Try:
System.out.println(contactList.get(position).get("name"));
I see you have a hashmap into an array list so you want to get the object from "X" position from array and after that get the value from the hashmap by property name.

Post method not working in AsyncHttpClient in Android

Hi I am developing android app using java restfull webservices Here I am getting one issue in calling web service through post method when I use client.post("") my all values get null while calling webservice. I dont know why it is happening. And when I use client.get("") its working properly.And I am able to do register properly through client.get. But I want to use client.post Please help me let me know what I am mistaking.
public void registerUser(View view){
String name = nameET.getText().toString();
String email = emailET.getText().toString();
String password = pwdET.getText().toString();
RequestParams params = new RequestParams();
if(Utility.isNotNull(name) && Utility.isNotNull(email) && Utility.isNotNull(password)){
if(Utility.validate(email)){
control
params.put("name", name);
params.put("username", email);
params.put("password", password);
// Invoke RESTful Web Service with Http parameters
invokeWS(params);
}
}
public void invokeWS(RequestParams params){
System.out.println("params===== "+params);
prgDialog.show();
**AsyncHttpClient client = new AsyncHttpClient();
client.post("http://localhost:8080/DemoForAndroid/register/doregister",params ,new AsyncHttpResponseHandler()** {
// When the response returned by REST has Http response code '200'
public void onSuccess(String response) {
// Hide Progress Dialog
System.out.println("response======= "+response);
prgDialog.hide();
try {
// JSON Object
JSONObject obj = new JSONObject(response);
// When the JSON response has status boolean value assigned with true
if(obj.getBoolean("status")){
// Set Default Values for Edit View controls
setDefaultValues();
// Display successfully registered message using Toast
Toast.makeText(getApplicationContext(), "You are successfully registered!", Toast.LENGTH_LONG).show();
}
// Else display error message
else{
errorMsg.setText(obj.getString("error_msg"));
Toast.makeText(getApplicationContext(), obj.getString("error_msg"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
// When the response returned by REST has Http response code other than '200'
public void onFailure(int statusCode, Throwable error,
String content) {
// Hide Progress Dialog
prgDialog.hide();
// When Http response code is '404'
if(statusCode == 404){
Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
}
// When Http response code is '500'
else if(statusCode == 500){
Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
}
// When Http response code other than 404, 500
else{
Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]", Toast.LENGTH_LONG).show();
}
}
});
System.out.println("Client======= "+client);
}
log file
01-28 12:10:26.307: W/KeyCharacterMap(106): No keyboard for id 0
01-28 12:10:26.307: W/KeyCharacterMap(106): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
01-28 12:11:33.238: I/System.out(274): params===== username=raju#mail.com&name=Raju &password=123456
01-28 12:11:33.328: D/dalvikvm(274): GC_FOR_MALLOC freed 5941 objects / 275504 bytes in 57ms
01-28 12:11:33.378: I/System.out(274): Client======= com.loopj.android.http.AsyncHttpClient#44ef5638
01-28 12:11:33.578: I/System.out(274): response======= {"tag":"register","status":false,"error_msg":"Error occured"}
01-28 12:11:33.678: I/ARMAssembler(58): generated scanline__00000077:03515104_00000000_00000000 [ 33 ipp] (47 ins) at [0x360af8:0x360bb4] in 405396 ns
01-28 12:11:33.745: W/InputManagerService(58): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy#450aa070
Restful Webservice code
#Path("/register")
public class Register {
// HTTP Get Method
User usr = new User();
#POST
// Path: http://localhost/<appln-folder-name>/register/doregister
#Path("/doregister")
// Produces JSON as response
#Produces(MediaType.APPLICATION_JSON)
// Query parameters are parameters: http://localhost/<appln-folder-name>/register/doregister?name=pqrs&username=abc&password=xyz
public String doLogin(#QueryParam("name") String name, #QueryParam("username") String uname, #QueryParam("password") String pwd){
String response = "";
System.out.println("Inside doLogin "+uname+" "+pwd);
int retCode = registerUser(name, uname, pwd);
System.out.println("ret code= "+retCode);
if(retCode == 0){
response = Utitlity.constructJSON("register",true);
}else if(retCode == 1){
response = Utitlity.constructJSON("register",false, "You are already registered");
}else if(retCode == 2){
response = Utitlity.constructJSON("register",false, "Special Characters are not allowed in Username and Password");
}else if(retCode == 3){
response = Utitlity.constructJSON("register",false, "Error occured");
}
return response;
}
private int registerUser(String name, String uname, String pwd){
System.out.println("Inside checkCredentials");
System.out.println("name= "+name);
System.out.println("uname= "+uname);
System.out.println("pwd= "+pwd);
int result = 3;
if(Utitlity.isNotNull(uname) && Utitlity.isNotNull(pwd)){
try {
System.out.println("add user---------------");
/* if(DBConnection.insertUser(name, uname, pwd)){*/
usr.setName(name);
usr.setUsername(uname);
usr.setPassword(pwd);
new UserDao().addUser(usr);
System.out.println("RegisterUSer if");
result = 0;
/* }*/
} /*catch(SQLException sqle){
System.out.println("RegisterUSer catch sqle");
//When Primary key violation occurs that means user is already registered
if(sqle.getErrorCode() == 1062){
result = 1;
}
//When special characters are used in name,username or password
else if(sqle.getErrorCode() == 1064){
System.out.println(sqle.getErrorCode());
result = 2;
}
}*/
catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Inside checkCredentials catch e ");
result = 3;
}
}else{
System.out.println("Inside checkCredentials else");
result = 3;
}
return result;
}
}
webservice log
Inside doLogin null null
Inside checkCredentials
name= null
uname= null
pwd= null
Inside isNotNull
Inside checkCredentials else
ret code= 3
replace #QueryParam with #FormParam in doLogin()
i think #QueryParam will be more like a GET param expected.

facebook like returns Error finding the requested story

I want to use FB SDK to do a like on a postId.
The post is in a 3rd part fb page.
Usually it works. But when I try to do like few days after the post was created I get this response:
Error finding the requested story
here is my code:
Request request = new Request(session,
takeFromPublicMacrosOrServer(currentOffer.fbPostId)
+ "/likes", null, HttpMethod.POST,
new Request.Callback() {
#Override
public void onCompleted(Response response) {
// Request complete
if (response.getError() == null) {
UnlockRequestToServer unlockRequestToServer = new UnlockRequestToServer(
mOffersListActivity,
PublicMacros.TYPE_UNLOCK_FB_LIKE,
currentOffer.fbPostId);
} else {
final String errorMsg = "error: "
+ response.getError().toString();
Log.e(MyLogger.TAG, errorMsg);
mToaster.showToastInUiThread(errorMsg);
}
String re = response.toString();
}
});
request.executeAsync();

Permissions Error - Trying to get friends using android facebook sdk

I am trying to add a feature to my android app that allows users to "checkin" with other people tagged to the checkin.
I have the checkins method working no problem and can tag some one by adding the user ID as a parameter (see code below)
public void postLocationTagged(String msg, String tags, String placeID, Double lat, Double lon) {
Log.d("Tests", "Testing graph API location post");
String access_token = sharedPrefs.getString("access_token", "x");
try {
if (isSession()) {
String response = mFacebook.request("me");
Bundle parameters = new Bundle();
parameters.putString("access_token", access_token);
parameters.putString("place", placeID);
parameters.putString("Message",msg);
JSONObject coordinates = new JSONObject();
coordinates.put("latitude", lat);
coordinates.put("longitude", lon);
parameters.putString("coordinates",coordinates.toString());
parameters.putString("tags", tags);
response = mFacebook.request("me/checkins", parameters, "POST");
Toast display = Toast.makeText(this, "Checkin has been posted to Facebook.", Toast.LENGTH_SHORT);
display.show();
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") ||
response.equals("false")) {
Log.v("Error", "Blank response");
}
} else {
// no logged in, so relogin
Log.d(TAG, "sessionNOTValid, relogin");
mFacebook.authorize(this, PERMS, new LoginDialogListener());
}
} catch(Exception e) {
e.printStackTrace();
}
}
This works fine (I've posted it in case it is of help to anyone else!), the problem i am having is i am trying to create a list of the users friends so they can select the friends they want to tag. I have the method getFriends (see below) which i am then going to use to generate an AlertDialog that the user can select from which in turn will give me the id to use in the above "postLocationTagged" method.
public void getFriends(CharSequence[] charFriendsNames,CharSequence[] charFriendsID, ProgressBar progbar) {
pb = progbar;
try {
if (isSession()) {
String access_token = sharedPrefs.getString("access_token", "x");
friends = charFriendsNames;
friendsID = charFriendsID;
Log.d(TAG, "Getting Friends!");
String response = mFacebook.request("me");
Bundle parameters = new Bundle();
parameters.putString("access_token", access_token);
response = mFacebook.request("me/friends", parameters, "POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") ||
response.equals("false")) {
Log.v("Error", "Blank response");
}
} else {
// no logged in, so relogin
Log.d(TAG, "sessionNOTValid, relogin");
mFacebook.authorize(this, PERMS, new LoginDialogListener());
}
} catch(Exception e) {
e.printStackTrace();
}
}
When i look at the response in the log it reads:
"got responce: {"error":{"type":"OAuthException", "message":"(#200) Permissions error"}}"
I have looked through the graphAPI documentation and searched for similar questions but to no avail! I'm not sure if i need to request extra permissions for the app or if this is something your just not allowed to do! Any help/suggestions would be greatly appreciated.
You might need the following permissions:
user_checkins
friends_checkins
read_friendlists
manage_friendlists
publish_checkins
Check the related ones from the API docs. Before that, make sure that which line causes this permission error and try to fix it.
The solution is to implement a RequestListener when making the request to the Facebook graph API. I have the new getFriends() method (see below) which uses the AsyncGacebookRunner to request the data.
public void getFriends(CharSequence[] charFriendsNames,String[] sFriendsID, ProgressBar progbar) {
try{
//Pass arrays to store data
friends = charFriendsNames;
friendsID = sFriendsID;
pb = progbar;
Log.d(TAG, "Getting Friends!");
//Create Request with Friends Request Listener
mAsyncRunner.request("me/friends", new FriendsRequestListener());
} catch (Exception e) {
Log.d(TAG, "Exception: " + e.getMessage());
}
}
The AsyncFacebookRunner makes the the request using the custom FriendsRequestListener (see below) which implements the RequestListener class;
private class FriendsRequestListener implements RequestListener {
String friendData;
//Method runs when request is complete
public void onComplete(String response, Object state) {
Log.d(TAG, "FriendListRequestONComplete");
//Create a copy of the response so i can be read in the run() method.
friendData = response;
//Create method to run on UI thread
FBConnectActivity.this.runOnUiThread(new Runnable() {
public void run() {
try {
//Parse JSON Data
JSONObject json;
json = Util.parseJson(friendData);
//Get the JSONArry from our response JSONObject
JSONArray friendArray = json.getJSONArray("data");
//Loop through our JSONArray
int friendCount = 0;
String fId, fNm;
JSONObject friend;
for (int i = 0;i<friendArray.length();i++){
//Get a JSONObject from the JSONArray
friend = friendArray.getJSONObject(i);
//Extract the strings from the JSONObject
fId = friend.getString("id");
fNm = friend.getString("name");
//Set the values to our arrays
friendsID[friendCount] = fId;
friends[friendCount] = fNm;
friendCount ++;
Log.d("TEST", "Friend Added: " + fNm);
}
//Remove Progress Bar
pb.setVisibility(ProgressBar.GONE);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FacebookError e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
Feel free to use any of this code in your own projects, or ask any questions about it.
You can private static final String[] PERMISSIONS = new String[] {"publish_stream","status_update",xxxx};xxx is premissions

Categories

Resources