Nothing happens when jsonResponse gets null data from mySQL-DB - java

im just new to java/android programming.
Im writing an app, where users can register themselves and login. data is saved in an online mysql-db. registering and login is working fine. The user stays loggig by using a session.
Even fetching the data from the mysql-db works but theres one issue when some db fields are responsing "null".
this is the code im working with
public class UserProfileSettingsFragment extends PreferenceFragment
{
SessionManager session;
#Override
public void onCreate(final Bundle savedInstanceState)
{
SharedPreferences prefs = this.getActivity().getSharedPreferences("JampSharedPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.usersettings);
session = new SessionManager(this.getActivity().getApplicationContext());
HashMap<String,String> user = session.getUserDetails();
final String sessionUsername = user.get(SessionManager.KEY_USERNAME);
// ResponseListener um Request Nutzerdaten auszulesen.
Response.Listener<String> UserDataResponseListener = new Response.Listener<String>(){
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
// Wenn Datenabfrage erfolgreich, JSONResponse auswerten.
if (success) {
String responseRealName = jsonResponse.getString("realname");
String responseStreetName = jsonResponse.getString("streetname");
int responsePostcode = jsonResponse.getInt ("postcode");
String responseCity = jsonResponse.getString("city");
String responseState = jsonResponse.getString("state");
int responseAge = jsonResponse.getInt ("age");
int responseIsPremium = jsonResponse.getInt ("isPremium"); // BOOLEAN
Preference prefUserData = (Preference) findPreference("preferencescreen_userdata");
prefUserData.setTitle(sessionUsername);
//prefUserData.setSummary(responseRealName+"\n"+responseStreetName+"\n"+responsePostcode + " " + responseCity);
Preference prefUsername = (Preference) findPreference("settings_username");
prefUsername.setTitle(sessionUsername);
Toast.makeText(getActivity(),sessionUsername, Toast.LENGTH_LONG);
if (responseIsPremium==1){
//ivPremiumIcon.setVisibility(View.VISIBLE);
}
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Konnte Nutzerdaten nicht abrufen.")
.setNegativeButton("Nochmal",null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
// Request an userdatarequest.php senden
UserDataRequest userDataRequest = new UserDataRequest(sessionUsername, UserDataResponseListener);
RequestQueue queue = Volley.newRequestQueue(this.getActivity());
queue.add(userDataRequest);
}
}
Php-Code:
$con = mysqli_connect("localhost","web506","lalala","usr_web506_1");
$username = $_POST["username"];
$statement = mysqli_prepare($con,"SELECT * FROM user WHERE username = ?");
mysqli_stmt_bind_param($statement,"s",$username);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement,
$userID,
$username,
$password,
$email,
$age,
$realname,
$streetname,
$postcode,
$city,
$state,
$isPremium,
$isLoggedIn);
$response = array();
$response["success"] = false;
while(mysqli_stmt_fetch($statement)){
$response["success"] = true;
$response["username"] = $username;
$response["password"] = $password;
$response["email"] = $email;
$response["age"] = $age;
$response["realname"] = $realname;
$response["streetname"] = $streetname;
$response["postcode"] = $postcode;
$response["city"] = $city;
$response["state"] = $state;
$response["isPremium"] = $isPremium;
$response["isLoggedIn"] = $isLoggedIn;
}
echo json_encode($response);
?>
So, when i fetch user data i can display them with Toast, change preference.summaries or whatsoever. But if some of the mysql entries are empty/null then nothing happens. the application doesn't crash but it seems that it doesnt get the "success" boolean from the php-file. whats the clue?
thanks in advance.
eirik
should i delete the $response["success"] = false;?
usually i get an alertmessage if the app can't connect to the database and the false bool reaches my application, so i thought its right there.
When i add blanks behind my variables from which i know their DB-cells are empty then jsonresponse delivers a "0" value as string result like this:
$response["realname"] = $realname+" ";
$response["streetname"] = $streetname+" ";
$response["postcode"] = $postcode+" ";
$response["city"] = $city+" ";
$response["state"] = $state+ " ";
i a textview are they displayed row by row as "0".
do i have to work around this inside my application or is there an easy way to filter empty cells somehow and skip to the next one?

$response["success"] = true;
$record_size = 0;
while(mysqli_stmt_fetch($statement)){
$response["success"] = true;
$response["username"] = $username;
$response["password"] = $password;
$response["email"] = $email;
$response["age"] = $age;
$response["realname"] = $realname;
$response["streetname"] = $streetname;
$response["postcode"] = $postcode;
$response["city"] = $city;
$response["state"] = $state;
$response["isPremium"] = $isPremium;
$response["isLoggedIn"] = $isLoggedIn;
$record_size++;
}
$response["record_size"] = $record_size;
echo json_encode($response);
For number of records I am using $record_size variable so that you can get the idea about records. because $response["success"] = true; means you are successfully able to get the DB and for records you can use $response["record_size"].. I hope it will help you..

My workaround looks now like this:
if i get 0 values i replace them with a "missing [...]" from an xml recource.
There was another mismatch too.. it seems that i get my jsonresponse always as a string, but i wanted to get the postcode in my first code as an integer, this didnt work too. so i will have to parse it to an int when i need it this way.
String responseRealName = jsonResponse.getString("realname"); if (responseRealName.equals("0")) {responseRealName = getResources().getString(R.string.MissingRealName);}
String responseStreetName = jsonResponse.getString("streetname"); if (responseStreetName.equals("0")) {responseStreetName = getResources().getString(R.string.MissingStreetName);}
String responsePostcode = jsonResponse.getString("postcode"); if (responsePostcode.equals("0")) {responsePostcode = getResources().getString(R.string.MissingPostcode);}
String responseCity = jsonResponse.getString("city"); if (responseCity.equals("0")) {responseCity = getResources().getString(R.string.MissingCity);}
String responseState = jsonResponse.getString("state"); if (responseState.equals("0")) {responseState = getResources().getString(R.string.MissingState);}
i think my question has been answered enough.

Related

Android studio isn't communicating to my php script

I have a 2 java scripts that should go to a php file located on http://localhost/phptesting/Register.php. My script's URL links it, but when I send a register request, nothing happens. Nothing even happens in the logs.
here is my registerrequest:
public class RegisterRequest extends StringRequest {
private static final String REGISTER_REQUEST_URL = "http://localhost/phptesting/Register.php";
private Map<String, String> params;
public RegisterRequest(String username, String password,String isAdmin, Response.Listener<String> listener){
super(Method.POST, REGISTER_REQUEST_URL,listener,null);
params = new HashMap<>();
params.put("username",username);
params.put("password",password);
params.put("isAdmin",isAdmin+"");
}
public Map<String, String> getparams() {
return params;
}
}
and here is my register activity script:
createuser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = username1.getText().toString();
final String password = password1.getText().toString();
final String isadmin = isAdmin.getText().toString();
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success){
Intent intent = new Intent(CreateUser.this, MainActivity.class);
CreateUser.this.startActivity(intent);
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(CreateUser.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry",null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(username,password,isadmin,responseListener);
RequestQueue queue = Volley.newRequestQueue(CreateUser.this);
queue.add(registerRequest);
}
});
my php script is this;
<?php
$db_host = 'localhost:3306';
$db_user = 'root';
$db_pass = '';
$db_name = 'test';
$con = mysqli_connect($db_host,'user',$db_pass,$db_name);
if($con){
echo "connection successful";
}else{
echo "connection failed";
}
$age = $_POST["isAdmin"];
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "INSERT INTO user (username,password,isAdmin) VALUES (?, ?, ?)");
mysqli_stmt_bind_param($statement, "siss",$username,$password,$isAdmin);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);
?>
All help is appreciated.
I see at least two errors on this code:
private static final String REGISTER_REQUEST_URL = "http://localhost/phptesting/Register.php";
Android doesn't like localhost you can read it here.
Best option is to do an ifconfig and get your ip address and instead of localhost put your ip address like
http://192.168.1.158/phptesting/Register.php
Also your localhost should have a port, right? So make sure you add it just in case in your BASE_URL, so it should look like this
http://192.168.1.158:8080/phptestig/Register.php
Then the call should work.
Then I see another problem with
mysqli_stmt_bind_param($statement, "siss",$username,$password,$isAdmin);
You are passing 4 values to an insert that requires 3.
I recommend you to go step by step, first make sure your api call is registering something (you can use PostMan or ARC to do it) and then go to Android side.

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"]

Value of type java.lang.String cannot be converted to JSONObject on Response.Listener

Hi i got this problem retrieving data, im using android volley and json to get data from web server.
heres my php file :
<?php
$con = mysqli_connect("***", "***", "***", "***");
// listing input entries for query
$city = $_POST["city"];
$term = $_POST["term"];
$p_type = $_POST["property_type"];
$min = $_POST["price_min"];
$max = $_POST["price_max"];
$bedrooms = $_POST["bedrooms"];
$bathrooms = $_POST["bathrooms"];
$query = "SELECT * FROM listing WHERE city = ? AND term = ? AND property_type = ? AND bedrooms = ? AND bathrooms = ?
AND price BETWEEN ? AND ?";
$statement = mysqli_prepare($con, $query);
mysqli_bind_param($statement, "sssiiii", $city, $term, $p_type, $bedrooms, $bathrooms, $min, $max);
mysqli_stmt_execute($statement);
mysqli_stmt_store_result($statement);
mysqli_stmt_bind_result($statement, $p_id, $p_name, $p_type, $term, $city, $address, $lot_area, $floor_area, $price,
$bedrooms, $bathrooms, $host_name, $host_contact_no, $host_details, $date_listed, $user_id);
$count = mysqli_stmt_num_rows($statement);
mysqli_stmt_close($statement);
$response = array();
$response["hasData"] = false;
if($count > 0){
$response["hasData"] = true;
while(mysqli_stmt_fetch($statement)){
$response["property_name"]= $p_id;
$response["property_type"] = $p_type;
$response["term"] = $term;
$response["city"] = $city;
$response["address"] = $address;
$response["lot_area"] = $lot_area;
$response["floor_area"] = $floor_area;
$response["price"] = $price;
$response["bedroom"] = $bedroom;
$response["bathroom"] = $bathroom;
$response["host_name"] = $host_name;
$response["host_contact_no"] = $host_contact_no;
$response["host_details"] = $host_details;
$response["date_listed"] = $date_listed;
}
}else{
$response["hasData"] = false;
}
echo json_encode($response);
?>
i have a java class name searchListingRequest.java
public class SearchListingRequest extends StringRequest {
private static final String SEARCH_REQUEST_URL = "http://homeseek.netau.net/searchLising.php";
private Map<String, String> params;
public SearchListingRequest(String city, String term, String p_type,
int price_min, int price_max, int bedrooms, int bathrooms, Response.Listener<String> listener){
super(Method.POST, SEARCH_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("city", city);
params.put("term", term);
params.put("property_type", p_type);
params.put("price_min", price_min + "");
params.put("price_max", price_max + "");
params.put("bedrooms", bedrooms + "");
params.put("bathrooms", bathrooms + "");
}
#Override
public Map<String, String> getParams() {
return params;
}
}
and in my other class ShowResults.java i call the class above to create instance and make a http request:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_results);
//unfocus on edittexts when starting
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
//gets data from home fragment
Intent intent = getIntent();
//initialize listview
data_listing = (ListView) findViewById(R.id.lv_data_listing);
retrieveData(showResults, intent, data_listing);
}
public void retrieveData(Activity activity,Intent intent, final ListView lv){
final String inputCity = intent.getStringExtra("city");
final String inputTerm = intent.getStringExtra("term");
final String inputType = intent.getStringExtra("type");
final int inputPMin = Integer.parseInt(intent.getStringExtra("price_min"));
final int inputPMax = Integer.parseInt(intent.getStringExtra("price_max"));
final int inputBedrooms = Integer.parseInt(intent.getStringExtra("bedrooms"));
final int inputBathrooms = Integer.parseInt(intent.getStringExtra("bathrooms"));
test = (TextView) findViewById(R.id.tv_test);
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
JSONArray responseArray = new JSONArray(response);
boolean hasData = jsonResponse.getBoolean("hasData");
// check if has data
if(hasData){
test.setText("have data");
}
else{// no data retrieved
showAlertDialog();
test.setText("no data");
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Can't connect to server.", Toast.LENGTH_SHORT).show();
test.setText("error");
}
}
};
SearchListingRequest searchListingRequest =
new SearchListingRequest(inputCity,inputTerm,inputType,inputPMin,inputPMax,inputBedrooms,inputBathrooms,responseListener);
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
queue.add(searchListingRequest);
}
and when i run the application the text displays "error" which means it has a jsonexception.
here's the logcat :
Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject
I really have no idea what this means. thanks for helping!
This is because by default volley will not send the POST body in JSON format and I think server is expecting the POST body in JSON. Hence you need to override getBody() method and change the format from application/x-www-form-urlencoded to json.
Please refer the below code :
#Override
public bytes[] getBody() {
new JSONObject(params).toString().getBytes();
}
Also consider overriding getBodyContentType and setting it to JSON.

Trying to display User info from a database in my Android application

I have been working on this for a while. The first thing I have tried is storing the logged in user in a session, and then trying to use that variable later such as the following:
Login.php
<?php
session_start();
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$sessionid = session_id();
require_once('connect.inc.php');
$sql = "SELECT username, password FROM USER WHERE username = ?";
$stmt = $conn->prepare($sql);
$username = $_POST["username"];
$password = $_POST["password"];
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->bind_result($user, $pass);
while($stmt->fetch()){
$verify = password_verify($password, $pass);
}
if($verify){
$_SESSION["username"] = $username;
echo 'connected';
echo $sessionid;
}else{
echo 'check details';
}
mysqli_close($conn);
}
?>
I am then taking the response of the login in message and splitting it into two variables. The login response and session id. I take the session id and store in shared preferences. I am trying to store the session ID in my java method so I can access the session user. Here is my java code for attempting to get the user:
GetUserData Java method
private void getUserData() {
SharedPreferences sharedPreferences = getSharedPreferences(Config.sharedPref, Context.MODE_PRIVATE);
String sessionId = sharedPreferences.getString(Config.SID, "SessionID");
StringRequest stringRequest = new StringRequest(Request.Method.GET, Config.SERVER_ADDRESS + "GetUserData.php?PHPSESSID=" + sessionId,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject jsonObject = null;
try {
//json string to jsonobject
jsonObject = new JSONObject(response);
//get json sstring created in php and store to JSON Array
result = jsonObject.getJSONArray(Config.json_array);
//get username from json array
getUserInfo(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void getUserInfo(JSONArray jsonArray){
for(int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject json = jsonArray.getJSONObject(i);
userInfo.add(json.getString(Config.getUsername));
} catch (JSONException e) {
}
}
}
Here is the php file the java method is attempting to call:
GetUserData.php
<?php
session_start();
if($_SERVER['REQUEST_METHOD'] == 'GET'){
$username = $_SESSION['username'];
$sql = "SELECT * FROM USER WHERE username = '$username'";
require_once('connect.inc.php');
$run = mysqli_query($conn, $sql);
$result = array();
while($row = mysqli_fetch_array($run)){
array_push($result, array(
'id' => $row['id'],
'fname' => $row['fname'],
'lname' => $row['lname'],
'username' => $row['username'],
'email' => $row['email'],
));
}
echo json_encode(array('result'=>$result));
mysqli_close($conn);
}
?>
When debugging, the 'result' array is empty, so for some reason,
$sql = "SELECT * FROM USER WHERE username = '$username'";
is not working. I know it has something to do with sessions, but Im not sure where the problem is.
My next attempt is going to try to just store the logged in user in shared preferences, and then call that variable from a php file and run a query to display user info with that variable. How would I do this?
Thank you.
What you will do is to send a request when a user enters username and password to the server as you have done here. Note I modified your code.
String enteredUsername = "username";
String enteredPassword = "xxxxxx";
String uri = String.format("http://somesite.com/some_endpoint.php?param1=%1$s&param2=%2$s", enteredUsername, enteredPassword);
StringRequest stringRequest = new StringRequest(Request.Method.GET, uri,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject jsonObject = null;
try {
// parse the response object and store user id and data in sharedpreference.
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Check the user has not been registered, add the user to your database and return the user database unique id plus other data you want.
then save the user id and username to SharedPreference
SharedPreferences sharedPreferences = getSharedPreferences(Config.sharedPref, Context.MODE_PRIVATE);
sharedPreferences.Editor edit = prefs.edit();
edit.putStringSet("Personal Information", set);
edit.commit();
You should first check if a user id is stored in preference to determine if the user is a registered user. if the user is not register show the login form else redirect user to profile activity page.
I already have a login class that makes sure the user is registered. I'm just trying to get the user information from the database as I have stated. Here is the login method as I probably should have provided it:
private void login(){
final String username = txtUsrnm.getText().toString().trim();
final String password = txtPswrd.getText().toString().trim();
//create string request
StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.SERVER_ADDRESS + "Login.php",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String responseOne = response.substring(0,9);
String responseTwo = response.substring(9);
if(responseOne.equalsIgnoreCase(Config.logInMessage)){
//create shared pref
SharedPreferences sharedPreferences = Login.this.getSharedPreferences(Config.sharedPref, Context.MODE_PRIVATE);
//editor stores values to the shared pref
SharedPreferences.Editor editor = sharedPreferences.edit();
//add values
editor.putBoolean(Config.sharedPrefBool, true);
editor.putString(Config.username, username);
editor.putString(Config.password, password);
editor.putString(Config.SID, responseTwo);
editor.commit();
Intent intent = new Intent(Login.this, Home.class);
startActivity(intent);
}else{
//display error message
Toast.makeText(Login.this, "Wrong Username or Password", Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//from android.com: A Map is a data structure consisting of a set of keys and
// values in which each key is mapped to a single value. The class of the objects
// used as keys is declared when the Map is declared, as is the class of the
// corresponding values.
Map<String,String> hashMap = new HashMap<>();
//maps specified string key, username and password, to specified string value
hashMap.put(Config.username, username);
hashMap.put(Config.password, password);
return hashMap;
}
};
//add string request to queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}

MySQL request from android error

I have MySQL database. I'm trying to get some data from android using PHP.
This is my PHP code: Here I'm trying to get User's info using his id.
<?php
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET["id"])) {
$id = $_GET['id'];
// get a product from products table
$result = mysql_query("SELECT * FROM app WHERE vk_id = $id");
//echo $result;
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$users = array();
$product["id"] = $result["id"];
$product["first_name"] = $result["first_name"];
$product["last_name"] = $result["last_name"];
$product["vk_id"] = $result["vk_id"];
$product["points"] = $result["points"];
// success
$response["success"] = 1;
// user node
$response["users"] = array();
array_push($response["users"], $product);
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No user found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
Testing with browser gives seccess result, it means PHP code working fine
So, here is the Android part:
public class DB_read_by_id extends AsyncTask<String, String, String> {
Context context;
private static String url_read_by_id = "http://women.egeshki.ru/blockphonedb/read_by_id.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String TAG_USERS = "users";
private static final String TAG_POINTS = "points";
JSONArray users = null;
String vk_id;
String points;
JSONParser jParser = new JSONParser();
public DB_read_by_id(String _vk_id, Context _context) {
vk_id = _vk_id;
context = _context;
url_read_by_id += "?id=" + vk_id;
Log.e("DB_read_by_id", "Constructor");
}
#Override
protected String doInBackground(String... strings) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_read_by_id, "GET", params);
Log.e("DB_read_by_id", "doInBackground");
Log.e("DB_read_by_id: ", url_read_by_id);
Log.e("DB_read_by_id json ", json.toString());
// Check your log cat for JSON response
//Log.e("Users_all: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
String message = json.getString(TAG_MESSAGE);
users = json.getJSONArray(TAG_USERS);
Log.e("DB_read_by_id", "Attempt to get from db");
if (success == 1) {
JSONObject c = users.getJSONObject(0);
points = c.getString(TAG_POINTS);
Log.e("DB_read_by_id Points", points);
} else if (message.equals("No user found")) {
Log.e("DB_read_by_id", "No user found");
} else if (message.equals("Required field(s) is missing")) {
Log.e("DB_read_by_id", "Required field(s) is missing");
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
Here is the logcat:
com.example.myapplication E/DB_read_by_id﹕ Constructor
com.example.myapplication E/DB_read_by_id﹕ doInBackground
com.example.myapplication E/DB_read_by_id:﹕ http://women.egeshki.ru/blockphonedb/read_by_id.php?id=150923434
com.example.myapplication E/DB_read_by_id json﹕ {"message":"No user found","success":0}
When I test from browser the link, which I get from logcat it's againg working fine. But from android it gives me an error. The problem is the link is ok, but android gives an error
Where is my mistake?
you didn't send the id to server
List<NameValuePair> params = new ArrayList<NameValuePair>();
//add this
params.add(new BasicNameValuePair("id","the value here));//
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_read_by_id, "GET", params);
Edit :after reading your comments
i think the problem is that you use your parametre in the link instead off using the right way .. just try to use this :
List<NameValuePair> params = new ArrayList<NameValuePair>();
//add this
params.add(new BasicNameValuePair("id","150923434"));//
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_read_by_id, "GET", params);
try this and report

Categories

Resources