Json object returned from php is empty - java

I'm writing a script using php to upload images to my local server.
user will upload the images from android application and I'm using retrofit library to do so. I want to return the path and name generated for the image in php for further processing in android. The problem is the php script always return an empty json
PHP Script
<?php
if (isset($_POST['image'])) {
$upload_folder = "Signatures"; // Name of the folder.
$unique_name = microtime().uniqid(); // Name of the image. use time method to make it unique.
$path = "$upload_folder/$unique_name.jpg";
$Image = $_POST['image'];
if (file_put_contents($path,base64_decode($Image)) != false) {
$data = [ 'imagePath' => $path];
header('Content-type: application/json');
echo json_encode( $data );
exit;
}
else {
$data = [ 'imagePath' => 'No image path'];
header('Content-type: application/json');
echo json_encode( $data );
exit;
}
}
else {
$data = [ 'imagePath' => 'No image path'];
header('Content-type: application/json');
echo json_encode( $data );
exit;
}
?>
Retorift method signature
#FormUrlEncoded
#POST ("Images.php")
Call<JSONObject> uploadImage (#Field("image") String image );
Upload image method
public void uploadImage(){
String image = imageToString(signatureView.getSignatureBitmap());
IAPI iAPI = Application.getImage();
Call<JSONObject> call = iAPI.uploadImage(image);
call.enqueue(new Callback<JSONObject>() {
#Override
public void onResponse(Call<JSONObject> call, Response<JSONObject> response) {
if (response.isSuccessful()) {
Log.d("test" , "is succ");
try {
JSONObject responseJSON = response.body();
Log.d("test" , responseJSON.toString());
String path = responseJSON.getString("path");
if (path == null) {
Log.d("test" , "path is null");
} else {
Log.d("test" , "path not null");
}
} catch (JSONException e) {
Log.d("test" , e.toString());
e.printStackTrace();
}
} else {
Log.d("test" , "not succ");
}
}
#Override
public void onFailure(Call<JSONObject> call, Throwable t) {
Log.d("test", " in onFailure - load image :" + t.getMessage() + t.toString());
}
});
}
It always throws an exception saying that there is no value for path.
And responseJSON.toString() in log prints empty [].
EDIT :
I have created my own model that contains property called imagePath and now it's wroking. Thank you all

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);
?>

Facing Issue while uploading images using android Retrofit 2

i am having some issues regarding upload image using retrofit 2 . i have an api to upload three kind of images like(Profile images , Banner images , Other images). i need to pass three parameters (user_id , type(profile / banner / other) , media(file) )... i am not understanding how to do it ...
here is my interface...
#Multipart
#POST("media/upload_media")
Call<ServerRespose> upload(
#Part MultipartBody.Part file ,
#Query("user_id") int user_id ,
#Query("type") String type
);
and here is my coe where i am trying to do it...
private void uploadFile(String path, Uri fileUri, final int type) {
// create upload service client
uid = DatabaseUtil.getInstance().getUser().getData().getID();
String username = SharedPreferenceUtil.getStringValue(this, Constants.USERNAME);
String password = SharedPreferenceUtil.getStringValue(this, Constants.PASSWORD);
if (!username.isEmpty() && !password.isEmpty()) {
Api service =
RetrofitUtil.createProviderAPIV2(username, password);
//
try {
// use the FileUtils to get the actual file by uri
showProgressDialog("Uploading");
File file = new File(path);
RequestBody requestFile =
RequestBody.create(
MediaType.parse(getContentResolver().getType(fileUri)),
file
);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body =
MultipartBody.Part.createFormData("file", file.getName(), requestFile);
// finally, execute the request
Call<ServerRespose> call = service.upload(body , uid , "profile_image");
call.enqueue(new Callback<ServerRespose>() {
#Override
public void onResponse(Call<ServerRespose> call,
Response<ServerRespose> response) {
hideProgressDialog();
Log.v("Upload", "success");
ServerRespose item = response.body();
try {
if (item != null) {
// item.setSuccess(true);
if (type == SELECT_PROFILE_PIC) {
profileImageRecyclerViewAdapter.addNewItem(item);
profileImageRecyclerViewAdapter.notifyDataSetChanged();
} else {
bannerImageRecyclerViewAdapter.addNewItem(item);
bannerImageRecyclerViewAdapter.notifyDataSetChanged();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ServerRespose> call, Throwable t) {
AppUtils.showDialog(Profile_Activity.this, "There is some Error", null);
Log.e("Upload error:", t.getMessage());
}
});
} catch (Exception e) {
e.printStackTrace();
}
} else {
showDialogSignedUp("Session Expired Please Login Again...", null);
}
}
Note: My code is not working just pick image and showing uploading and it is also not returning any kind of response ... Any one please help with the correct code i need to do this work on a very short notice.
check the parameters here...
function save_image($request)
{
if(!empty($request['user_id'])){
$user_identity = $request['user_id'];
$submitted_file = $_FILES['media'];
$uploaded_image = wp_handle_upload( $submitted_file, array( 'test_form' => false ) );
$type = $request[ 'type' ];
//return $submitted_file;
if ( !empty( $submitted_file )) {
$file_name = basename( $submitted_file[ 'name' ] );
$file_type = wp_check_filetype( $uploaded_image[ 'file' ] );
// Prepare an array of post data for the attachment.
$attachment_details = array(
'guid' => $uploaded_image[ 'url' ],
'post_mime_type' => $file_type[ 'type' ],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $file_name ) ),
'post_content' => '',
'post_status' => 'inherit'
);
Try this way..
#Multipart
#POST(NetworkConstants.WS_REGISTER)
Call<UserResponseVo> registerUser(#Part MultipartBody.Part file, #PartMap Map<String, RequestBody> map);
after that..
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), mFile);
RequestBody userName = RequestBody.create(MediaType.parse("text"), mEtUserName.getText().toString());
RequestBody userEmail = RequestBody.create(MediaType.parse("text"), mEtEmail.getText().toString().trim());
RequestBody userPassword = RequestBody.create(MediaType.parse("text"), mEtPassword.getText().toString().trim());
Map<String, RequestBody> map = new HashMap<>();
map.put(NetworkConstants.KEY_FIRST_NAME, userName);
map.put(NetworkConstants.KEY_EMAIL, userEmail);
map.put(NetworkConstants.KEY_PASSWORD, userPassword);
retrofit.create(ApiInterface.class).registerUser(fileToUpload, map);
Try this
1)Declare method in interface class
#Multipart
#POST("media/upload_media")
Call<AddImageResponseClass> upload(#Part("user_id") RequestBody user_id, #Part("media\"; filename=\"myfile.jpg\" ") RequestBody profile_pic,#Part("type") RequestBody type);
Then in java class
String BASE_URL=base_url;
final OkHttpClient okHttpClient = new OkHttpClient.Builder().writeTimeout(2, TimeUnit.MINUTES).retryOnConnectionFailure(true)
.readTimeout(2, TimeUnit.MINUTES)
.connectTimeout(2, TimeUnit.MINUTES)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL).client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
Api service =
RetrofitUtil.createProviderAPIV2(username, password);
File file = new File(path);
RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file );
String user_id= user_id_here;
String type= type_here;
RequestBody reqUserId= RequestBody.create(MediaType.parse("text/plain"), user_id);
RequestBody reqType= RequestBody.create(MediaType.parse("text/plain"), type);
Call<ServerRespose> userCall = service.upload(reqUserId, reqFile,reqType);
userCall.enqueue(new Callback<ServerRespose>() {
#Override
public void onResponse(Call<ServerRespose> call, Response<ServerRespose> response) {
if (response.body() == null) {
//handle here
return;
}
}
#Override
public void onFailure(Call<ServerRespose> call, Throwable t) {
System.out.println("response failure" + t.getMessage());
t.printStackTrace();
}
});
And import these
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.google.code.gson:gson:2.8.2'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'com.squareup.retrofit2:converter-scalars:2.3.0'

Script executing two times

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!!

Failed multipart upload using retrofit 2

I'm new at retrofit and I want to upload using retrofit 2. Every uploading the file the response is
Fail Upload
from the php but if I'm using Postman it always success.
Below is my code.
Main Activity
File zip = new File(Environment.getExternalStorageDirectory() + "/test.zip");
RequestBody reqBody = RequestBody.create(MediaType.parse("multipart/form-file"), zip);
MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", zip.getName(), reqBody);
ApiServices api = RetroClient.getApiServices();
Call<ResponseApiModel> upload = api.fileUpload(filePart);
upload.enqueue(new Callback<ResponseApiModel>() {
#Override
public void onResponse(Call<ResponseApiModel> call, Response<ResponseApiModel> response) {
if (response.body().getCode().equals("1")) {
Toast.makeText(MainActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResponseApiModel> call, Throwable t) {
Log.d("RETRO", "ON FAILURE : " + t.getMessage());
}
});
Api Services
#Multipart
#POST("getzip.php")
Call<ResponseApiModel> fileUpload (#Part MultipartBody.Part File);
PHP Code
$part = "./upload/";
$filename = rand(9,9999).".zip";
$res = array();
$code = "";
$message = "";
if($_SERVER['REQUEST_METHOD'] == "POST")
{
if(isset($_FILES['file'])){
$destinationfile = $part.$filename;
$data = $_FILES['file'];
if(move_uploaded_file($data['tmp_name'], $destinationfile)) {
$code = 1;
$message = "Success Upload";
}else {
$code = 0;
$message = "Fail Upload";
}
}else{
$code = 0;
$message = "request error";
}
}else
{
$code = 0;
$message = "Request Not Vaild";
}
$res['code'] = $code;
$res['message'] = $message;
echo json_encode($res);
I don't know PHP but I know Retrofit. Here is how I do it and works perfectly, this uploads the whole folder, you may change accordingly to handle your files.
You need to use Multipart Format.
Here is a code sample below:
#Multipart
#POST("sync/contact/image")
Call<Response> ImageUpload(#Part MultipartBody.Part file);
#Multipart
#POST("sync/image")
Call<ResponseBody> MultiImageUpload(#PartMap() Map<String, RequestBody> mapFileAndName);
public static HashMap<String, RequestBody> GetAllImage(Context context) {
File files = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "/.ELMEX");
File[] filesArray = files.listFiles();
List<File> listOfNames = Arrays.asList(filesArray);
HashMap<String, RequestBody> map = new HashMap<>(listOfNames.size());
RequestBody file = null;
for (int i = 0, size = listOfNames.size(); i < size; i++) {
file = RequestBody.create(MediaType.parse("multipart/form-data"), listOfNames.get(i));
map.put("file\"; filename=\"" + listOfNames.get(i).getName() + ".jpg", file);
file = null;
}
return map;
}
HashMap<String, RequestBody> map = UtilImage.GetAllImage(context);
Call<ResponseBody> call = Retro.getRetroWS().MultiImageUpload(map);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.d(TAG, "onResponse: ");
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.d(TAG, "onFailure: ");
}
});
You can check all the suggestions given in this answer. Check out all the answers and comments, not just the accepted answer, because there are some really good ideas on what could be wrong, as well as good ideas on how to debug the problem.

Android Volley - POST-Parameter not reaching PHP-Script

I want to get Infos from a Database. When i use a Query without parameters (e.g. "Select * from users;" my script works fine.
Now i have the following script which returns an empty Array. When i replace the $groupId in script with a string value (e.g. "Group1") it returns the expected Items.
<?php
$sql = "";
if($_SERVER['REQUEST_METHOD']== 'POST') {
$flag = array();
$groupId = $_POST['groupId'];
require_once('dbConnect.php');
$sql = "SELECT * FROM users where groupId = '$groupId'";
if($out = mysqli_query($con,$sql)){
//echo "Successfully Registered";
while($row = mysqli_fetch_array($out))
{
$flag[] = $row;
}
print(json_encode($flag));
}else{
echo "Could not register";
}
}else{
echo 'error';
}
//mysqli_close($con);
?>
When i call the following function with the hashmap hashMapGetNames.put("groupId", "Group#1");
then i get an empty array and the info: "No, Group ID is not set"
public ArrayList<String> get(String url, final HashMap<String, String> hashMap, final Context context) {
//Download the items from DB
final ArrayList<String> items = new ArrayList<>();
RequestQueue queue = Volley.newRequestQueue(context);
JSONObject parameters = new JSONObject(hashMap);
final JsonRequest<JSONArray> jsonArrayRequest = new
JsonRequest<JSONArray>(Request.Method.GET, url, parameters.toString(),
new com.android.volley.Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
if(jsonArray == null){
Log.d("Downloader", "FAIL: NO NAMES FOUND");
}
else {
for (int zähler = 0; zähler < jsonArray.length(); zähler++){
try {
Log.d("Downloader", "sind bei zähler " + zähler);
JSONObject object = jsonArray.getJSONObject(zähler);
String name = object.getString("name");
Log.d("Name", name);
items.add(name);
}
catch (JSONException e) {
Log.d("Downloader", "Catching exception");
e.printStackTrace();
}
}
}
}
}, new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Downloader", "Error: " + error.toString());
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Log.d("Downloader", "gettingParams");
return hashMap;
}
#Override
protected Response<JSONArray> parseNetworkResponse(NetworkResponse response) {
Log.d("Downloader", "parsing Network response");
try {
String jsonString = new String(response.data,
HttpHeaderParser
.parseCharset(response.headers));
Log.d("Downloader", "Parsing success");
return Response.success(new JSONArray(jsonString),
HttpHeaderParser
.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
Log.d("Downloader", e.toString());
return Response.error(new ParseError(e));
} catch (JSONException je) {
Log.d("Downloader", je.toString());
return Response.error(new ParseError(je));
}
}
};
queue.add(jsonArrayRequest);
return items;
}
So the Script seems right but the parameter does not reach the Script. Any Ideas where the error could hide?
EDIT: I edited the code like shown in the tutorial commented below and use the same dbConnect.php file. but it prints out error - so the problem still exist. That means that the Request Method is not "Post".
Android Monitor prints out:
parsing Network response
Downloader: Parsing success
Error: com.android.volley.ParseError: org.json.JSONException: End of input at character 0
try this code...
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Creating parameters
Map<String,String> params = new Hashtable<String, String>();
//Adding parameters
params.put("groupId", "122");
//returning parameters
return params;
}

Categories

Resources