Script executing two times - java

I am using PHP as my API for a messaging android app, I have created a script which will register the user by inserting data into the database when logging for the first time, I have tried this Link but my primary key is unique and still the script is executing two times and which causes an error
:-
[27-Feb-2018 17:44:12 UTC] PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '3bc91dab47aeb989' for key 'users_device_id_uindex'' in [My Api Url]/DbFunction.php:44
Which means that there is a duplicate entry in the table.Basically, It stores the value perfectly when executed for the first time but when it executes again it gives the error described above
Script for registration (register.php):-
<?php
require_once ("DbFunction.php");//Importing DbFunction Class
/*Initializing Variables*/
$response = array();
$db = new DbFunction();
$result = $device_id = $phone_number = $user_name = $email = $website =
$profile_picture = $token = $created_at = '';
/* Checking If REQUEST_METHOD is POST*/
if($_SERVER['REQUEST_METHOD'] == 'POST') {
/*Checking is variables are set*/
$device_id = isset($_POST['device_id']) ? $_POST['device_id']:null;
$phone_number = isset($_POST['phone_number']) $_POST['phone_number']:null;
$user_name = isset($_POST['user_name']) ? $_POST['user_name'] : null;
$email = isset($_POST['email']) ? $_POST['email'] : null;
$website = isset($_POST['website']) ? $_POST['website'] : null;
$profile_picture = isset($_POST['profile_picture']) ? $_POST['profile_picture'] : null;
$token = isset($_POST['token']) ? $_POST['token'] : null;
$created_at = isset($_POST['created_at']) ? $_POST['created_at'] : null;
/* Checking For Nulls*/
if (!isNull($device_id) || !isNull($phone_number) || !isNull($user_name) || !isNull($email) || !isNull($profile_picture) || !isNull($token) || !isNull($created_at)) {
/* Calling The createUser functions with required parameters*/
$result = $db->createUser($device_id, $phone_number, $user_name, $email, $website, $profile_picture, $token, $created_at);
$response['error'] = !$result;// Setting the value of error which is inverse of $result(if result == true which means user registered successfully and there is no error so inverse of result which is false and vice versa)
if($result)
{
$response['message'] = "User Registered Successfully";
}
else{
$response['message'] = "Registration Error";
}
}
/* Echoing The Reponse*/
echo json_encode($response);
}
function isNull($variable)
{
return is_null($variable);
}
script for functions (DbFunction.php):-
public function createUser($device_id,$phone_number,$user_name ,$email ,$website ,$profile_dp ,$token ,$created_at )
{
/* Calling the uploadImage funtion to upload the Image To Server which will Return Url Where Image Is Stored*/
$profile_picture = $this->uploadImage($profile_dp, $email);
$stmt = $this->conn->prepare("INSERT INTO users (device_id, phone_number, user_name, email, website, profile_picture, token, created_at) VALUES (:device_id, :phone_number, :user_name, :email, :website, :profile_picture, :token, :created_at)");
$stmt->bindValue(':device_id', $device_id);
$stmt->bindValue(':phone_number', $phone_number);
$stmt->bindValue(':user_name', $user_name);
$stmt->bindValue(':email', $email);
$stmt->bindValue(':website', $website);
$stmt->bindValue(':profile_picture', $profile_picture);
$stmt->bindValue(':token', $token);
$stmt->bindValue(':created_at', $created_at);
return $stmt->execute();
}
And now the Android code from where I am calling the request, I am using volley for that.
UserInfoActivity.java :-
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnNext:
if (isValidInput()) {
sendDataToServer();
dialog.setMessage("Loading....");
dialog.show();
}
}
}
private void sendDataToServer() {
StringRequest strreq = new StringRequest(Request.Method.POST,
Config.URL_REGISTER,
new Response.Listener<String>() {
#Override
public void onResponse(String Response) {
dialog.dismiss();
Log.d(TAG, Response);
Boolean error = null;
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(Response);
error = jsonObject.getBoolean("error");
if(!error)
{
Toast.makeText(UserInfoActivity.this,"User Registered Successfully",Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(UserInfoActivity.this, "Something Went Wrong While Registering", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(UserInfoActivity.this, "Something Went Wrong While Registering", Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError e) {
VolleyLog.e(TAG, e);
e.printStackTrace();
Toast.makeText(UserInfoActivity.this, "Something Went Wrong While Registering", Toast.LENGTH_LONG).show();
dialog.dismiss();
}
}) {
#SuppressLint("HardwareIds")
#Override
public Map<String, String> getParams() {
DateTime dateTime = new DateTime();
SharedPreferences pref = getApplicationContext().getSharedPreferences(Config.SHARED_PREF, 0);
Map<String, String> params = new HashMap<>();
params.put("phone_number", FirebaseAuth.getInstance().getCurrentUser().getPhoneNumber());
params.put("user_name", etName.getText().toString());
params.put("email", etEmail.getText().toString());
if (!TextUtils.isEmpty(etWebsite.getText().toString())) {
params.put("website", etWebsite.getText().toString());
}
params.put("token", pref.getString("token", null));
params.put("device_id", Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID));
params.put("created_at", dateTime.toString());
params.put("profile_picture", image_to_server);
return params;
}
};
AppSingleton.getInstance(UserInfoActivity.this).addToRequestQueue(strreq);
}
AppSingleton.java :-
public class AppSingleton {
private static AppSingleton mInstance;
private RequestQueue mRequestQueue;
private static Context mContext;
private AppSingleton(Context context){
// Specify the application context
mContext = context;
// Get the request queue
mRequestQueue = getRequestQueue();
}
public static synchronized AppSingleton getInstance(Context context){
// If Instance is null then initialize new Instance
if(mInstance == null){
mInstance = new AppSingleton(context);
}
// Return MySingleton new Instance
return mInstance;
}
public RequestQueue getRequestQueue(){
// If RequestQueue is null the initialize new RequestQueue
if(mRequestQueue == null){
mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext());
}
// Return RequestQueue
return mRequestQueue;
}
public<T> void addToRequestQueue(Request<T> request){
// Add the specified request to the request queue
getRequestQueue().add(request);
}
}
And after request, I get an error response which is null:-
02-28 14:58:20.690 14606-14606/com.dev.pigeon E/Volley: [1] 3.onErrorResponse: USERINFOACTIVITYTAG
UPDATE
After Watching the Log clearly I saw this:-
02-28 17:21:36.448 21212-21815/com.dev.pigeon D/Volley: [22348] BasicNetwork.logSlowRequests: HTTP response for request=<[ ] http://[My Api Url]/register.php 0xec86a58c NORMAL 1> [lifetime=8562], [size=1208], [rc=500], [retryCount=1]
02-28 17:21:36.449 21212-21815/com.dev.pigeon E/Volley: [22348] BasicNetwork.performRequest: Unexpected response code 500 for http://[My APi Url]/register.php
02-28 17:21:36.463 21212-21212/com.dev.pigeon E/Volley: [1] 3.onErrorResponse: USERINFOACTIVITYTAG
Above Error Says That Volley Is Retrying The Request, I don't know why?
Please help from where this error is occurring, I am working on this weird behavior of Volley for a long time but didn't get any solution.
P.S. Sorry For My Bad English And Badly Written Code!!

Related

How to send JSONArray to PHP server using Volley?

I'm fairly inexperienced with Android programming and am having issues sending a JSONArray to my PHP server. I am using the following code to generate the JSONArray from my cursor:
public JSONArray matrixJSON(){
Cursor cursor = db.rawQuery("SELECT columnID,rowID,value FROM Matrix WHERE PolicyID=" + curPolicy,null);
JSONArray resultSet = new JSONArray();
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
int totalColumn = cursor.getColumnCount();
JSONObject rowObject = new JSONObject();
for (int i = 0; i < totalColumn; i++) {
if (cursor.getColumnName(i) != null) {
try {
rowObject.put(cursor.getColumnName(i),
cursor.getString(i));
} catch (Exception e) {
Log.d(TAG, e.getMessage());
}
}
}
resultSet.put(rowObject);
cursor.moveToNext();
}
cursor.close();
return resultSet;
}
I believe I am misunderstanding how to properly send data via JsonARrayRequest. Here is the following code that I am using to send the data.
public void sendData(JSONArray data) {
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://10.123.20.180:8080/insertmatrix.php";
JsonArrayRequest dataReq = new JsonArrayRequest(Request.Method.POST, url, data,
response -> Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_LONG).show(),
error -> Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show()){
#Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
if (response.data == null || response.data.length == 0) {
return Response.success(null, HttpHeaderParser.parseCacheHeaders(response));
} else {
return super.parseNetworkResponse(response);
}
}
};
queue.add(dataReq);
}
Instead of sending the data, I am left with a blank array. The cursor to JSONarray function is working properly as I can see in debug, but the php server is receiving a blank array. I assume there is some essential functions I am missing.
Fixed it by switching my array into a string and then using a StringRequest to send the data.
Updated function:
public void sendData(JSONArray data) {
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://10.123.20.180:8080/insertmatrix.php";
String json = data.toString();
StringRequest dataReq = new StringRequest(Request.Method.POST,url,response -> Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_LONG).show(),
error -> Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show()){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String,String>();
params.put("data",json);
return params;
}
};
queue.add(dataReq);
}

PHP not return expected result

I'm getting a very weird result ! I posting an id from java class where the id will used in php script to retrieve specific data. The value should be 1, but it always display 2
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$id = $_POST['id'];
//Creating sql query
$sql = "SELECT xuenian FROM student WHERE sid='$id'";
//importing dbConnect.php script
require_once('db_config.php');
//executing query
$result = mysqli_query($con,$sql);
$value = mysqli_fetch_object($result);
$value->xuenian;
if($value === "1"){
echo "1";
}else{
echo "2";
}
mysqli_close($con);
}
I have tried ==, the result still same.
Java class
public void loadResults(final String id, final int xuenian) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, AppConfig.URL_CHECKID,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(getApplication(),response+"from php",Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplication(), error + "", Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
//Adding parameters to request
params.put(AppConfig.KEY_USERID, id);
//returning parameter
return params;
}
};
//Adding the string request to the queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
You're setting $value to an object here:
$value = mysqli_fetch_object($result);
Then this line does nothing:
$value->xuenian;
On the next line, $value is still an object, but you're comparing it to a string, which will always be false:
if($value === "1")
{
echo "1";
}else{
echo "2";
}
You probably want this:
if($value->xuenian === "1")

Send a value of variable in android studio to php

I got problem to pass the value inside the variable of Android Studio to the php code. In this case I want to pass the value inside the variable "group_id" in Message.java to the DbOperation.php. That means at the end, the function "getMessages" inside the DbOperation.php can get the value of variable "group_id" and select the particular table inside the MySQL database. I still new to Android Studio and please help me to solve this problem. Tq very much.
For example: the value of variable "group_id" is "ABC123", the "getMessages" function inside DbOperation.php will perform "SELECT a.id, a.message, a.sentat, a.users_id, b.name FROM ABC123_messages a, users b WHERE a.users_id = b.id ORDER BY a.id ASC;"
This code below is the java class of the Message.java
SharedPreferences sharedPreferences = getActivity().getSharedPreferences(Config.SHARED_PREF_GROUP, Context.MODE_PRIVATE);
group_id = sharedPreferences.getString(Config.GROUP_SHARED_PREF, "Not Available");
private void fetchMessages() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_FETCH_MESSAGES,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//dialog.dismiss();
try {
JSONObject res = new JSONObject(response);
JSONArray thread = res.getJSONArray("messages");
for (int i = 0; i < thread.length(); i++) {
JSONObject obj = thread.getJSONObject(i);
int userId = obj.getInt("userid");
String message = obj.getString("message");
String name = obj.getString("name");
String sentAt = obj.getString("sentat");
Message messagObject = new Message(userId, message, sentAt, name);
messages.add(messagObject);
}
adapter = new ThreadAdapter(getActivity(), messages, AppController.getInstance().getUserId());
recyclerView.setAdapter(adapter);
scrollToBottom();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("group_id", group_id);
return params;
}
};
AppController.getInstance().addToRequestQueue(stringRequest);
}
This is part of php code in index.php
$app->post('/messages', function () use ($app){
verifyRequiredParams(array('group_id'));
$group_id = $app->request()->post('group_id');
$db = new DbOperation();
$messages = $db->getMessages($group_id);
$response = array();
$response['error']=false;
$response['messages'] = array();
while($row = mysqli_fetch_array($messages)){
$temp = array();
$temp['id']=$row['id'];
$temp['message']=$row['message'];
$temp['userid']=$row['users_id'];
$temp['sentat']=$row['sentat'];
$temp['name']=$row['name'];
array_push($response['messages'],$temp);
}
echoResponse(200,$response);});
function verifyRequiredParams($required_fields){
$error = false;
$error_fields = "";
$request_params = $_REQUEST;
// Handling PUT request params
if ($_SERVER['REQUEST_METHOD'] == 'PUT') {
$app = \Slim\Slim::getInstance();
parse_str($app->request()->getBody(), $request_params);
}
foreach ($required_fields as $field) {
if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {
$error = true;
$error_fields .= $field . ', ';
}
}
if ($error) {
// Required field(s) are missing or empty
// echo error json and stop the app
$response = array();
$app = \Slim\Slim::getInstance();
$response["error"] = true;
$response["message"] = 'Required field(s) ' . substr($error_fields, 0, -2) . ' is missing or empty';
echoResponse(400, $response);
$app->stop();
}}
This is one of the function inside DbOperation.php
public function getMessages($group_id){
$stmt = $this->conn->prepare("SELECT a.id, a.message, a.sentat, a.users_id, b.name FROM ?_messages a, users b WHERE a.users_id = b.id ORDER BY a.id ASC;");
$stmt->bind_param("s",$group_id);
$stmt->execute();
$result = $stmt->get_result();
return $result;}
In Android code looks fine. But I think you haven't caught the send data in PHP. Using
$_POST["group_id"]

GCM Notification Receiver/Token Registration

EDIT: Figured it out -- see answer below
I'm attempting to generate registration tokens, store them in a server, and then use the tokens to send push notifications. At this point, I've successfully sent and stored registration tokens and am sending notifications from a web API, but they aren't arriving to my device. I was wondering if/what I should replace R.string.gcm_defaultSenderId with (i.e. the sender key from GCM?) I'm including my code for token registration as well as my notification listener below.
public class GCMRegistrationIntentService extends IntentService {
//Constants for success and errors
public static final String REGISTRATION_SUCCESS = "RegistrationSuccess";
public static final String REGISTRATION_ERROR = "RegistrationError";
private Context context;
private String sessionGUID = "";
private String userGUID = "";
//Class constructor
public GCMRegistrationIntentService() {
super("");
}
#Override
protected void onHandleIntent(Intent intent) {
context = getApplicationContext();
sessionGUID = RequestQueueSingleton.getInstance(context).getSessionGUID();
userGUID = RequestQueueSingleton.getInstance(context).getUserGUID();
//Registering gcm to the device
registerGCM();
}
//Registers the device to Google Cloud messaging and calls makeAPICall to send the registration
//token to the server
private void registerGCM() {
//Registration complete intent initially null
Intent registrationComplete;
//declare a token, try to find it with a successful registration
String token;
try {
//Creating an instanceid
InstanceID instanceID = InstanceID.getInstance(this);
//Getting the token from the instance id
token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
//Display the token, need to send to server
Log.w("GCMRegIntentService", "token:" + token);
String android_id = Settings.Secure.getString(context.getContentResolver(),
Settings.Secure.ANDROID_ID);
int osTypeCode = Constants.OST_ANDROID;
JSONObject parms = new JSONObject();
try {
parms.put("deviceID", android_id);
parms.put("OSTypeCode", osTypeCode);
parms.put("token", token);
} catch (JSONException e) {
e.printStackTrace();
}
Transporter oTransporter = new Transporter(Constants.TransporterSubjectUSER,
Constants.REGISTER_NOTIFICATION_TOKEN, "", parms, userGUID, sessionGUID);
oTransporter.makeAPICall(getApplicationContext(), "");
//on registration complete. creating intent with success
registrationComplete = new Intent(REGISTRATION_SUCCESS);
//Putting the token to the intent
registrationComplete.putExtra("token", token);
} catch (Exception e) {
//If any error occurred
Log.w("GCMRegIntentService", "Registration error");
registrationComplete = new Intent(REGISTRATION_ERROR);
}
//Sending the broadcast that registration is completed
LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}
}
And the listener service:
public class GCMPushReceiverService extends GcmListenerService {
private static final String TAG = "GCMPushReceiverService";
//with every new message
#Override
public void onMessageReceived(String from, Bundle data){
System.out.println("WE'VE RECIEVED A MESSAGE");
String message = data.getString("message");
Log.d(TAG, "From: " + from);
Log.d(TAG, "Message: " + message);
sendNotification(message);
}
private void sendNotification(String message) {
Intent intent = new Intent(this, LogInPage.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
int requestCode = 0;
PendingIntent pendingIntent =
PendingIntent.getActivity(this, requestCode, intent, PendingIntent.FLAG_ONE_SHOT);
Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder noBuilder = new NotificationCompat.Builder(this);
noBuilder.setContentTitle("title");
noBuilder.setContentText(message);
noBuilder.setContentIntent(pendingIntent);
noBuilder.setSound(sound);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, noBuilder.build()); //0 = ID of notification
}
}
Lastly, as it may be of some assistance, the information transporter/networking class:
public class Transporter {
private String subject;
private String request;
private String key;
private Date lastUpdateDate;
private boolean forceLoad = false;
private Date requestDate;
private Date responseDate;
private int status;
private String statusMsg = "";
private String tempKey = "";
private JSONObject additionalInfo = null;
private JSONObject parameters;
public static String sessionGUID = "";
public static String userGUID = "";
public static String SERVER = Constants.qa_api;
//transporter object to interact with the server, containing information about the request
//made by the user
public Transporter(String pSubject, String pRequest, String pKey,
JSONObject parms, String userGUID, String sessionGUID)
{
subject = pSubject;
request = pRequest;
key = pKey;
parameters = parms;
setUserGUID(userGUID);
setSessionGUID(sessionGUID);
}
//implements an API call for a given transporter, takes 2 arguments:
//the application context (call getApplicationContext() whenever it's called)
//and a String that represents the field that we are trying to update (if there is one)
//i.e. if we are calling getUserFromSession(), we want the user guid so jsonID = "userGUID"
public void makeAPICall(final Context context, final String jsonID) {
RequestQueue mRequestQueue =
RequestQueueSingleton.getInstance(context).getRequestQueue();
String targetURL = getServerURL() + "/Transporter.aspx";
StringRequest postRequest = new StringRequest(Request.Method.POST, targetURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String parseXML= parseXML(response);
System.out.println("response: " + parseXML);
JSONObject lastResponseContent = null;
try {
lastResponseContent = new JSONObject(parseXML);
} catch (JSONException e) {
e.printStackTrace();
}
try {
if (lastResponseContent != null && !jsonID.equals("")) {
String info = lastResponseContent.getString(jsonID);
if (jsonID.equals("userGUID")) {
userGUID = info;
RequestQueueSingleton.getInstance(context).setUserGUID(userGUID);
}
}
//put other things in here to pull whatever info
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}) {
#Override
public byte[] getBody() throws AuthFailureError {
String body = getXML(subject,
request, "",
sessionGUID, userGUID, null, parameters);
return body.getBytes();
}
};
postRequest.setTag("POST");
mRequestQueue.add(postRequest);
}
you need to send a post to the url "https://android.googleapis.com/gcm/send":
private void sendGCM() {
StringRequest strReq = new StringRequest(Request.Method.POST,
"https://android.googleapis.com/gcm/send", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
Log.e(TAG, "Volley error: " + error.getMessage() + ", code: " + networkResponse);
Toast.makeText(getApplicationContext(), "Volley error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("data", "message that you send");
params.put("to", "token gcm");
Log.e(TAG, "params: " + params.toString());
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
headers.put("Authorization", "key="google key");
return headers;
}
};
}
So the Volley calls are non-sequential so the first call (to get a userGUID) didn't return before the second call (to register for notifications), so while the token registration was "successful," there was no corresponding user information so it didn't know how/where to send the push notification. To resolve, I made a special case in the makeAPICall class which created another StringRequest which first basically did the normal getUserFromSession but then recursively called MakeAPICall with the new userGUID information. To avoid an infinite loop, I used an if else statement: (if userGUID == null || userGUID.equals("")) then I did the recursive call, so when the first call returned that conditional was always false and it would only make one recursive call. This answer may be a rambling a bit, but the key take away is using onResponse to make another Volley call for sequential requests. See: Volley - serial requests instead of parallel? and Does Volley library handles all the request sequentially

Can't update member variable

Somehow line mResponseText = response.body().string(); isn't writing member variable. Instead it appears to be creating and logging it locally.
Any ideas why? The more I look at it the more clueless I'm getting :(
public class Gateway {
private static final String TAG = Gateway.class.getSimpleName();
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
private String mResponseText = "[{'comment' : 'fake' , 'psn_nickname' : 'fake', 'created':'now', 'parent_class':''}]";
public Gateway (String url, String json, final Context context) {
if(isNetworkAvailable(context)) {
//if network is available build request
OkHttpClient client = new OkHttpClient();
// RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
//.post(body)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
//execute call
#Override
public void onFailure(Request request, IOException e) {
// if request failed
Toast.makeText(context, "request failed", Toast.LENGTH_LONG).show();
}
#Override
public void onResponse(Response response) throws IOException {
// if succeeded
if(response.isSuccessful()){
mResponseText = response.body().string();
Log.v(TAG, "SETTING RESPONSE");
// THIS LOGS PROPER JSON LOADED FROM NETWORK
Log.v(TAG, mResponseText);
} else {
//alertUserAboutError(context);
Toast.makeText(context, "Something wrong with response", Toast.LENGTH_LONG).show();
}
}
});
} else {
Toast.makeText(context, "Network is not available", Toast.LENGTH_LONG).show();
}
}
public String getResponse () {
Log.v(TAG, "GETTING RESPONSE");
// THIS LOGS FAKE SAMPLE JSON --- WTF???
Log.v(TAG, mResponseText);
return mResponseText;
}
// check if network is available
private boolean isNetworkAvailable(Context c) {
ConnectivityManager manager = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
/*
private void alertUserAboutError(Context c) {
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.show(c.getFragmentManager(), "error_dialog");
}
*/
}
Here's the code that's using this class
Gateway gateway = new Gateway(mCommentURL, "", this);
String mJsonData = gateway.getResponse();
EDIT Code update - removed extends Activity
You're calling getResponse() too early. The async operation has not completed yet and the value returned is the one you initialize there in the first place, not the one written in the Callback.
Put the code that uses the response in the Callback, or call that code from the callback.

Categories

Resources