0

I am having some really strange problems. So in my app, when someone logs into Google Plus, the name, profile picture, and id are sent in JSON to a webpage, where a PHP script takes the JSON and gets all the data from it, checks in the database if such a user already exists, and if not, adds him.

So I've already done this before, for a different purpose, and now when I'm trying to copy what I did before, it doesn't work. I'm not exactly sure what's going on, because the same code works for something else.

So this is my Android code. I've checked with the log to make sure that the JSON Object has everything.

public void updateData(String url, JSONObject jobj){
    DefaultHttpClient defaultHttpClient = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(defaultHttpClient.getParams(), 100000);
    HttpPost httpPost = new HttpPost(url);

    JSONArray sendJSON = new JSONArray();
    sendJSON.put(jobj);

    httpPost.setHeader("json", jobj.toString());
    httpPost.getParams().setParameter("jsonpost", sendJSON);

    try {
        HttpResponse httpResponse = defaultHttpClient.execute(httpPost);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

And here is my PHP code:

<?php
require_once('connection.php');

if( isset($_SERVER['HTTP_JSON']) )
{

    $data = json_decode($_SERVER['HTTP_JSON'], true);

    $name = $data['name'];
    $profilePicture = $data['profilePicture'];
    $googleId = $data['googleId'];

    //First see if the user is already in the database
    $find_existing_query = "SELECT * FROM users WHERE googleId = $googleId";
    $result = mysql_query($find_existing_query);

    //Add user if there are no rows returned
    if(mysql_num_rows($result) == 0)
    {
        $add_user_query = "INSERT INTO users (name, profilePicture, googleId) VALUES ($name, $profilePicture, $googleId)"
        mysql_query($add_user_query);
    }

    $qry = "SELECT * FROM users";

    $result = mysql_query($qry);
    $rows = array();
    while($r = mysql_fetch_assoc($result)){
        $rows[] = $r;
    }
    echo json_encode($rows);

    mysql_close();
}

else{
    echo 'no JSON sent';
}

?>

Also, strangely, when I visit the webpage, I should be seeing "No JSON sent", but I am seeing a blank page. And any echo statements placed at the top of the file is not being done. Also, when I am running the SELECT * FROM users query, it outputs data from a different table in the database.

I really have no idea what is going on. Any help would be greatly appreciated!

6
  • Do you have some kind of error reporting enabled ? Also, instead $_SERVER['HTTP_JSON'] you probably meant $_POST['HTTP_JSON'] ? Commented Jan 30, 2015 at 21:53
  • How do I check if I have error reporting enabled? Sorry, I'm really new to this. I'll try $_POST, but on my other PHP script, I have it as $_SERVER and it works fine Commented Jan 30, 2015 at 22:00
  • Ok. Error reporting can be enabled in your script by adding at the top of the .php file error_reporting(E_ALL); ini_set('display_errors',1); Commented Jan 30, 2015 at 22:04
  • Ok, I did that. Now where can I find these error logs? Commented Jan 30, 2015 at 22:11
  • You should see the errors, if there are any, right on the webpage you are running... Commented Jan 30, 2015 at 22:18

1 Answer 1

1

Ok, here is an elegant way to do it with WebServices.

STEP #1: Create a generic class that can handle AsynTask safely.

public class WebServiceRestTask extends AsyncTask<HttpUriRequest, Void, Object> {
    private static final String TAG = "WebServiceRestTask";
    private AbstractHttpClient mClient;
    private WeakReference<WebServiceRestCallback> mCallback;
    private int ws_task;

    public WebServiceRestTask(int ws_task) {
        this(new DefaultHttpClient(), ws_task);

    }

    public WebServiceRestTask(AbstractHttpClient client, int task_number) {
        mClient = client;
        this.ws_task = task_number;
    }

    public interface WebServiceRestCallback {
        public void onRequestSuccess(String response);

        public void onRequestError(Exception error);
    }

    public void setResponseCallback(WebServiceRestCallback callback) {
        mCallback = new WeakReference<WebServiceRestCallback>(callback);
    }

    @Override
    protected Object doInBackground(HttpUriRequest... params) {
        try {
            HttpUriRequest request = params[0];
            HttpResponse serverResponse = mClient.execute(request);

            BasicResponseHandler handler = new BasicResponseHandler();
            String response = handler.handleResponse(serverResponse);
            return response + ws_task;
        } catch (Exception e) {
            Log.w(TAG, e);
            return e;
        }
    }

    @Override
    protected void onPostExecute(Object result) {
        if (mCallback != null && mCallback.get() != null) {
            if (result instanceof String) {
                mCallback.get().onRequestSuccess((String) result);
            } else if (result instanceof Exception) {
                mCallback.get().onRequestError((Exception) result);
            } else {
                mCallback.get().onRequestError(
                        new IOException("Unknown Error Contacting Host"));
            }
        }
    }

}

STEP 2: Create a method that will consume your WebService class. Here you will pass your JSON as follow.

private void sendJSONTask(String uri, String jsonString,
        int task_case) {
    try {

        HttpPost httpPost = new HttpPost(uri);
        httpPost.setHeader("content-type", "application/json");

        HttpEntity entity;

        StringEntity s = new StringEntity(jsonString);
        entity = s;
        httpPost.setEntity(entity);

        WebServiceRestTask task = new WebServiceRestTask(task_case);
        task.setResponseDataCallback(LastActivity.this);
        task.execute(httpPost);

        Log.e("Sending JSON task : " + task_case,
                jsonString);

    } catch (Exception e) {
        Log.e("ERROR sending JSON task: ", e.getMessage());
    }
}

STEP #3 Call your task this way.(the parameter task_number is and unique identifier in case you have several type of JSON requests and you need to handle each one based on their ID).

sendJSONTask(uri_target, jsonData, 1);
Sign up to request clarification or add additional context in comments.

7 Comments

Oh wow did not know this. Now is there anything I'll have to change in my PHP code?
Also, what is task_case?
Plaase, see the STEP #3
Should I put the sendJSONTask method in the WebServiceRestTask class?
Also, anything I need to change in the PHP file? Or is what I'm doing with $_SERVER['HTTP_JSON'] correct?
|

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.