Send a value of variable in android studio to php - java

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

Related

Synchronize SQLite With MySql by sending array of available quotes and receive the missing Android Java

Synchronize SQLite With MySql by sending array of ids for the quotes available in the SQLite to php script that will compare it with the available in the database and receive the missing quotes
this method will work in every moment when the app started
btw i know i have mistakes in the php script for that i'm asking now
im facing this error !
D/error: org.json.JSONException: Value Arraynull of type java.lang.String cannot be converted to JSONArray
thank you !
DatabaseHelper.java
public Map<String,String> readIds(){
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor=db.rawQuery("SELECT * FROM "+TABLE_NAME_QUOTES,null);
Map<String,String> QuotesModuleArray = new HashMap<String, String>();
if (cursor.moveToFirst()){
do {
QuotesModuleArray.put("quote_id"+"["+cursor.getString(0)+"]", cursor.getString(0));
}while (cursor.moveToNext());
}
cursor.close();
return QuotesModuleArray;
}
MainActivity.java
public void Quotes_SQLITE() throws UnsupportedEncodingException {
String url=".../android/checkquotes.php";
Map<String,String> arrayListQuotes;
dbHandler = new DataBaseHelper(MainActivity.this);
arrayListQuotes = dbHandler.readIds();
System.out.println(Arrays.toString(new Map[]{arrayListQuotes}));
quotesListSQLite.clear();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null,
response -> {
Log.e("Quotesqlite : ",response.toString());
progressBar.setVisibility(View.GONE);
swipeRefreshLayout.setRefreshing(false);
for (int i = 0 ; i < response.length() ; i++){
try {
JSONObject jsonObject = response.getJSONObject(i);
int quote_id = jsonObject.getInt("quote_id");
String quote_name = jsonObject.getString("quote_name");
String quote_details = jsonObject.getString("quote_details");
String status = jsonObject.getString("status");
String parent_id = jsonObject.getString("parent_id");
int language_id = jsonObject.getInt("language_id");
QuoteSQLite quote = new QuoteSQLite(quote_id , quote_name , quote_details , status,parent_id, language_id);
dbHandler.Add_Quote(quote_id,quote_name,quote_details, status,parent_id, language_id);
quotesListSQLite.add(quote);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(context, error.getMessage()+"", Toast.LENGTH_SHORT).show();
Log.d("error",error.getMessage()+"");
if((error.getMessage()+"").equals("null")) {
try {
Quotes_SQLITE();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params;
params=arrayListQuotes;
return params;
}
};
requestQueue.add(jsonArrayRequest);
}
PHP Script
<?php
header('Content-Type: application/json; charset=utf-8');
define('DB_HOST', 'localhost');
define('DB_USER', 'ibnabita_alihaydar');
define('DB_PASS', '81336874');
define('DB_NAME', 'ibnabita_secure_imam');
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
mysqli_query($conn,"SET NAMES 'utf8'");
mysqli_query($conn,'SET CHARACTER SET utf8');
$allarray = array();
$toaddarray = array();
$flag = [];
$i = 0 ;
if(mysqli_connect_error($conn))
{
echo "Failed to connect to database ".mysqli_connect_error();
}
$sql="select quote_id from quotes";
$result2=mysqli_query($conn,$sql);
if($result2)
{
while($row=mysqli_fetch_array($result2,MYSQLI_BOTH))
{
array_push($allarray,$row["quote_id"]);
}
}
$ids = array();
foreach($_POST as $key=>$value){
$ids[] = $_POST[$key];
}
$data = json_decode($ids,true);
foreach($data as $item) { //foreach element in $arr
echo $item."\n" ;
}
foreach($allarray as $item) { //foreach element in $arr
//echo $item."\n" ;
if(in_array( $item ,$data))
{
}
else
{
$sql23="select * from quotes where quote_id=".$item;
$result23=mysqli_query($conn,$sql23);
$row23=mysqli_fetch_array($result23,MYSQLI_BOTH);
$flag[]=$row23;
}
}
print(json_encode($flag,JSON_UNESCAPED_UNICODE));
mysqli_close($conn);
?>

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

Nothing happens when jsonResponse gets null data from mySQL-DB

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.

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.

JSONArrayRequest and PHP pair not working

I am creating class which should send JSONArrayRequest using volley with specific params, then find mysql rows which equals these params and send it back. I wrote simple mysql function which receive POST params and Java method which send and receive JSONObjects. But it isn't working and I receive nothing.
This is my PHP file called details.php. It receive parameters from my Android App and send back an array.
require_once __DIR__ . '/db_connect.php'
$db = new DB_CONNECT();
$path= $_POST["path"];
$result = mysql_query("SELECT * FROM modx_ms2_product_files WHERE path = $path") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$json_response = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product ["file"] = $row["file"];
// push single product into final response array
array_push($json_response, $product);
}
// echoing JSON response
echo json_encode($json_response);
$conn->close();
}
This is my method getArray(), which send request and receive response:
public void getarray() {
String path = "1578/";
final String URL = "http://myurl.io/details.php";
HashMap<String, String> params = new HashMap<String, String>();
params.put("path", path);
JsonArrayRequest customarray = new JsonArrayRequest(Request.Method.POST,URL,new JSONObject(params),new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length() > 0) {
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject Obj = response.getJSONObject(i);
pics pic = new pics();
pic.setFile(Obj.getString("file"));
Log.i("cmon", Obj.getString("file"));
pics.add(pic);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
AppController.getInstance().addToRequestQueue(customarray);
}
This is my modx_ms2_product_files table:
http://i.imgur.com/yl1f7Ze.png
http://i.imgur.com/9V6PrBU.png
Have you tried using StringRequest? For some reason when i used JsonArrayRequest i didn't get any response back from the server. If you decide to create a StringRequest you could convert your response to a JSONArray like this:
StringRequest get = new StringRequest(Method.POST, URL, new Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray myArray = new JSONArray(response);
for(int i = 0; i < myArray.length(); i++)
{
JSONObject jObj = myArray.getJSONObject(i);
// get your data here
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Then of course add your request to the request queue.

Categories

Resources