0

Hello i am currently having an issue sending a JSON object from my PHP to an Android device. I have done this before with another person and it worked fine but now it does not seem to work.

It is a simple login script. It should return the user's data or "false" based on whether the login email and password entered are correct.

The response is visible when tried in a browser but according to my colleague, he gets an empty array when viewing on his android development machine.

This is the php code:

<?php
 include('config.php');
 include('functions.php');
 include('password_hash_lib/password.php');
 if (!isset($_REQUEST["device"]))
 {
 $Email = $_POST['Email'];
 $Password = $_POST['Password'];
 try
 {
 if (authenticate($Email, $Password))
 {
 echo "true";
 }
 else {
 echo "false";
 }
 }
 catch (Exception $e)
 {
 echo $e->getMessage();
 }
 }
 else if (isset($_REQUEST["device"]))
 {
 $device = $_REQUEST['device'];
 $Email = $_REQUEST['email'];
 $Password = $_REQUEST['password'];
 if ($device == 'mobi')
 { 
 try
 {
 if (authenticate($Email, $Password))
 {
 $curruser = explode("+", $_SESSION['sess_user_auth']);
 $arr = new ArrayObject(Array(), ArrayObject::STD_PROP_LIST); 
 $arr->userid = $curruser[0];
 $arr->email = $curruser[1];
 $arr->fullname = $curruser[2];
 $arr->displaypic = $curruser[3];
 $arr->displayname = $curruser[4];
 echo str_replace("\\", "", json_encode((object) $arr)); 
 }
 else {
 echo "false";
 }
 }
 catch (Exception $e)
 {
 echo $e->getMessage();
 }
 }
 }
?>

This is the android code my colleague wrote:

@Override
protected Boolean doInBackground(Void... params) {
// TODO Auto-generated method stub
boolean status=false;
LoginMgr lmgr=new LoginMgr(getSherlockActivity().getBaseContext());
try {
HttpClient httpclient= new DefaultHttpClient();
HttpGet httpget=new HttpGet("http://www.xxxxx.com/login.php?device=mobi&[email protected]&password=xxxxxxx
");
HttpResponse response= httpclient.execute(httpget);
int statuscode=response.getStatusLine().getStatusCode();
if(statuscode==200){
InputStream is=response.getEntity().getContent();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
final StringBuilder stringbuild= new StringBuilder();
String curr_line;
if((curr_line=br.readLine())!=null){
stringbuild.append(curr_line);
String jsonstr=stringbuild.toString();
getSherlockActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(getSherlockActivity(), stringbuild.toString(), Toast.LENGTH_LONG).show(); 
}
});
if(!jsonstr.equalsIgnoreCase("false")){
JSONObject job=new JSONObject(jsonstr);
String str=job.getString("3").replace("\\/","/");
String image="http://www.xxxxx.com/img/timthumb.php?&h=50&w=50&src=
"+str;
lmgr.loginUser(new Login(job.getString("0"),job.getString("4"),job.getString("1"),image));
status=true;
JSONObject job=new JSONObject(jsonstr);
if(job.getString("success").equalsIgnoreCase("1")){
lmgr.loginUser(new Login(job.getString("userid"),job.getString("username"),job.getString("useremail"),job.getString("userimage")));
status=true;
} 
}
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return status;
}

I have tried using return instead of echo in my code but that still did not work. There were no errors just an empty array.

asked Jun 23, 2014 at 14:24
5
  • Why are you removing backslashes from the json_encode? Commented Jun 23, 2014 at 14:25
  • Because there is a url in the returned array, and the json_encode appears to add backslashes to escape certain characters. Commented Jun 23, 2014 at 14:26
  • 1
    But it is no longer valid json. You can't decode it anymore. Commented Jun 23, 2014 at 14:28
  • 1
    @blank: don't mess with JSON. You NEVER directly modify a json string, because what you're doing is introducing javascript syntax errors. Commented Jun 23, 2014 at 14:31
  • Hello i tried all your suggestions but none worked for me. Commented Jun 23, 2014 at 14:39

3 Answers 3

1

This should solve your problem. Try to be consistent in what your script returns. It must always returns the same kind of data (JSON) even if it fails.

<?php
include('config.php');
include('functions.php');
include('password_hash_lib/password.php');
if (!isset($_REQUEST["device"]))
{
 $Email = $_POST['Email'];
 $Password = $_POST['Password'];
 try
 {
 if (authenticate($Email, $Password)) echo json_encode(array('auth' => true));
 else echo json_encode(array('auth' => false));
 }
 catch (Exception $e)
 {
 echo json_encode(array('error' => $e->getMessage()));
 }
}
else if (isset($_REQUEST["device"]))
{
 $device = $_REQUEST['device'];
 $Email = $_REQUEST['email'];
 $Password = $_REQUEST['password'];
 if ($device == 'mobi')
 {
 try
 {
 if (authenticate($Email, $Password))
 {
 $curruser = explode("+", $_SESSION['sess_user_auth']);
 $json = array();
 $json['userid'] = $curruser[0];
 $json['email'] = $curruser[1];
 $json['fullname'] = $curruser[2];
 $json['displaypic'] = $curruser[3];
 $json['displayname'] = $curruser[4];
 echo json_encode($json); 
 }
 else
 {
 echo json_encode(array('auth' => false));
 }
 }
 catch (Exception $e)
 {
 echo json_encode(array('error' => $e->getMessage()));
 }
 }
}

EDIT: Based on your last update, you've got some mistakes in your Android code. I've tried to improve it but I haven't tested it.

@Override
protected Boolean doInBackground(Void... params)
{
 boolean status = false;
 LoginMgr lmgr = new LoginMgr(getSherlockActivity().getBaseContext());
 try
 {
 // Connect to the remote server
 HttpClient httpclient = new DefaultHttpClient();
 HttpGet httpget = new HttpGet("http://www.xxxxx.com/login.php?device=mobi&[email protected]&password=xxxxxxx");
 HttpResponse response = httpclient.execute(httpget);
 int statuscode=response.getStatusLine().getStatusCode();
 if(statuscode==200)
 {
 // Read response
 InputStream is = response.getEntity().getContent();
 BufferedReader br = new BufferedReader(new InputStreamReader(is));
 final StringBuilder stringbuild= new StringBuilder();
 String curr_line = null;
 while ((curr_line = br.readLine()) != null)
 {
 stringbuild.append(curr_line);
 }
 getSherlockActivity().runOnUiThread(new Runnable() {
 @Override
 public void run()
 {
 Toast.makeText(getSherlockActivity(), stringbuild.toString(), Toast.LENGTH_LONG).show(); 
 }
 });
 // Parse response to JSON
 JSONObject json = new JSONObject( stringbuild.toString() );
 if (json.has("auth"))
 {
 if (json.getBoolean("auth"))
 {
 // Authentificate with success
 getSherlockActivity().runOnUiThread(new Runnable() {
 @Override
 public void run()
 {
 Toast.makeText(getSherlockActivity(), "Success", Toast.LENGTH_LONG).show(); 
 }
 });
 }
 else
 {
 // In this case, authentification has failed
 getSherlockActivity().runOnUiThread(new Runnable() {
 @Override
 public void run()
 {
 Toast.makeText(getSherlockActivity(), "Wrong user credentials", Toast.LENGTH_LONG).show(); 
 }
 });
 }
 }
 else if (json.has("userid"))
 {
 String userid = json.getString("userid");
 String email = json.getString("email");
 String fullname = json.getString("fullname");
 String displaypic = json.getString("displaypic").replace("\\/","/");
 String displayname = json.getString("displayname");
 // In this case, we got some data about the user
 String image = "http://www.xxxxx.com/img/timthumb.php?&h=50&w=50&src=" + displaypic;
 lmgr.loginUser(new Login(json.getString("0"), json.getString("4"), json.getString("1"), image));
 status = true;
 JSONObject job = new JSONObject(jsonstr);
 if(job.getString("success").equalsIgnoreCase("1"))
 {
 lmgr.loginUser(new Login(userid, fullname, email, displaypic));
 status = true;
 }
 }
 }
 }
 catch (Exception e)
 {
 e.printStackTrace();
 }
 return status;
}
answered Jun 23, 2014 at 14:36
Sign up to request clarification or add additional context in comments.

3 Comments

I just edited my post and added the android script as you requested.
Thank you i will try it out, also could you please tell me the mistakes that were made and how you corrected them and why? Just so that they do not happen again. :)
When you read the server response, you must loop on readLine, in your code you just read it once. Also, you were parsing the json 3 or 4 times in a row.
0

Replace : echo str_replace("\\", "", json_encode((object) $arr));

By this : echo json_encode(array('user'=>$arr));

answered Jun 23, 2014 at 14:35

Comments

0

I had a similar issue and I changed HttpGet to HttpPost and it worked. Hope this helps

answered Jun 24, 2014 at 8:53

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.