failed jsonArrayRequest - android

MY function content to make jsonArrayRequest is:
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST,
FilesUsed.url_display_thought, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
JSONObject jsonObject1 = response.getJSONObject(0);
JSONObject jsonObject2 = response.getJSONObject(1);
if (jsonObject1.getBoolean("error")) {
ArrayList<String> list = new ArrayList<>();
list.add(jsonObject2.getString("message"));
displayThought(list);
} else {
int count = 0;
ArrayList<String> list = new ArrayList<>();
while (count < response.length()) {
try {
JSONObject jsonObject = response.getJSONObject(count);
String thought = jsonObject.getString("post");
list.add(thought);
count++;
} catch (JSONException e) {
e.printStackTrace();
}
}
displayThought(list);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
error.printStackTrace();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email", "sainiakshay04");
return params;
}
};
RequestHandler.getInstance(this).addToRequestQueue(jsonArrayRequest);
The content of the php it is using is:
require_once '../app/display_personal_account.php';
$response=array();
if(isset($_POST['email'])){
$db = new display_personal_account($_POST['email']);
$res=$db->get_info_added("shared_content");
if($res==1){
$response=$db->display_shared_content();}
else{
$response[]['error']=true;
$response[]['message']="No Content To Display ";}
}
else{
$response[]['error']=true;
$response[]['message']="ERROR: INVALID REQUEST";
}
echo json_encode($response);
?>
but the output it is displaying is ERROR:INVALID REQUEST, although I'm binding email using getParams, isset of php is not working and going to else part.
HELP!

You're checking isset($_POST['email']) but you send null parameter in the JsonArrayRequest.
For now, JsonArrayRequest only supports the JsonArray parameter.
There are two things that you need to do :
Send the email in the JsonArray parameter
JSONObject request = new JSONObject();
request.put("email", userEmail);
JSONArray arrayParam = new JSONArray();
arrayParam.put(request);
....
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST,
FilesUsed.url_display_thought, arrayParam, ...
Get the email in the PHP
require_once '../app/display_personal_account.php';
$response=array();
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE);
if(isset($input[0]['email'])){
$db = new display_personal_account($input[0]['email']);
....
After that, you should just work fine :)

Related

Volley POST request android

I am not sure i should use which type of content to POST to the api because I am very new to this developing world.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
button = (Button)findViewById(R.id.reg_btn_sign_up);
btnCancel = (Button)findViewById(R.id.reg_button_cancel);
Email = (EditText)findViewById(R.id.reg_email);
Name = (EditText)findViewById(R.id.reg_name);
Pass = (EditText)findViewById(R.id.reg_pass);
ConPass = (EditText)findViewById(R.id.reg_confirm_pass);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
email = Email.getText().toString();
name = Name.getText().toString();
password = Pass.getText().toString();
conPass = ConPass.getText().toString();
JSONObject jsonBody = new JSONObject();
try {
jsonBody.put("username", email);
jsonBody.put("password", password);
jsonBody.put("name", name);
} catch (JSONException e) {
e.printStackTrace();
}
final String mRequestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, reg_url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String status = jsonObject.getString("status");
String result = jsonObject.getString("result");
builder.setTitle("Server Response...");
builder.setMessage(result);
} catch (JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
})
{
#Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
}
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
};
MySingleton.getmInstance(RegisterActivity.this).addRequestQueue(stringRequest);
}
});
}
}
This is the log I get in logcat:
W/System.err: org.json.JSONException: Value
{"status":0,"result":"Access restricted"} of type org.json.JSONObject
cannot be converted to JSONArray
I do it correctly in POSTMAN but I failed to get the result I want in android.
API added in command.
try this
public void login(final String user, final String pass) {
Log.e("Constant.KEY_URL", String.valueOf(Constant.KEY_URL));
StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.KEY_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//you will get your response in log
Log.e("response", response);
if (user.equals("") || pass.equals("")) {
Toast.makeText(getApplicationContext(), "username or password is empty", Toast.LENGTH_LONG).show();
} else if (!response.equals("empty")) {
Log.e("isempty", "yes");
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
JSONArray array1 = array.getJSONObject(i).getJSONArray("data");
for (int j = 0; j < array1.length(); j++) {
startActivity(intent);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("isempty", "else");
Toast.makeText(getApplicationContext(), "Username or password is incorrect", Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "username or password is empty", Toast.LENGTH_LONG).show();
// Toast.makeText(getApplicationContext(), "Invalid username or password", Toast.LENGTH_SHORT).show();
Log.e("Error", "msg==>" + error);
}
}) {
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> reqMap = new LinkedHashMap<>();
reqMap.put("username", user);
reqMap.put("password", pass);
reqMap.put("method", "login");
Log.e("request","login" + reqMap);
return reqMap;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 30, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
if (requestQueue == null) {
requestQueue = Volley.newRequestQueue(getApplicationContext());
}
requestQueue.add(stringRequest);
stringRequest.setTag("TAG");
}
call this login method on your button click event
btnlogin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
user = editusername.getText().toString().trim();
pass = editpassword.getText().toString().trim();
login(user, pass);
}
});
I'm assuming that you are doing sign up function using volley request response..Relate to my code which i have used for login purpose,you can change it according to your needs..Hope it helps
The response you are getting is JSONObject and not JSONArray
try following code in onResponse method:
try {
JSONObject jsonObject = new JSONObject (response);
String status = jsonObject.getString("status");
String result = jsonObject.getString("result");
builder.setTitle("Server Response...");
builder.setMessage(result);
} catch (JSONException e){
e.printStackTrace();
}
Your are trying to parse an array from your response but you are getting an JSONObject.
So first change this line when you get the response
JSONObject jsonObject = new JSONObject(response);
and check the status
if(jsonObject.getString("status").equalsIgnoreCase("0")){
// show error message or whatever
}else if(jsonObject.getString("status").equalsIgnoreCase("1")){
// then parse your array if response has it
}
Use this
JSONObject jsonObject = new JSONObject (response.toString());
Instead of
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);

JsonArrayRequest Post Method isn't working

I did not use Volley before so I'm a newbie here. I try to do a JSONArrayRequest with Post Parameters.
A PHP script will check these parameters and answer with a JSON Array which is going to displayed in a list.
But somehow the Post Parameters don't send. So my PHP script says that the post parameters are missing.
So what did I do wrong that the post parameters don't send?
Here is my code:
private void getPersonsData(final String PhoneNr, final String Password) {
String url = "http://127.0.0.1:80/android_login_api/getmembers.php";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Method.POST, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
//Adding a person in the list
if (response.length() > 0) {
personList.clear();
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
Person person = new Person();
if (!jsonObject.isNull("fullname")) {
person.name = jsonObject.getString("fullname");
}
if (!jsonObject.isNull("location")) {
person.location = jsonObject.getString("location");
}
personList.add(i, person);
}
mAdapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("phonenr", PhoneNr);
params.put("password", Password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
And here are some parts of my PHP Code:
getmembers.php
<?php
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
$response = array("error" => FALSE);
if (isset($_POST['phonenr']) && isset($_POST['password'])) { //this goes on false
// receiving the post params
$phonenr = $_POST['phonenr'];
$password = $_POST['password'];
$user = $db->getUserByPhonenrAndPassword($phonenr, $password);
[...]
Would be great when someone finds out my mistake!
The normal $_POST method in php doesn't work in volley. You need to make this in your php file.
$post = json_decode(file_get_contents("php://input"), true);
$my_value = $post['param1'];
param1 is value that you put in volley.
Use this :
final Hashmap<String,String> param1 = new Hashmap<string,string>();
param1.put("param1",your value);
it works for me. You can try it
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Method.POST, url, **new JSonObject(param1)**, new Response.Listener<JSONArray>() { . . . ..

How to POST JSON Object In Android using Volly Library below type of Json?

Here is my code :
{
"VisitorDetails":[
{
"Name":"Ramesh",
"Gender":"Male",
"Age":24,
"MobileNo":9502230173,
"LandLine":"040140088",
"EmailId":"rameshkandula24#gmail.com",
"CreatedOn":"08-25-2016",
"Address":"Hyderabad",
"Profession":"Software",
"FamilyMembers":5,
"HomeTown":"Gannavaram",
"MedicalHealing":"Noooooo",
"Isinterestedwithcompanies":1,
"IsBetterlivingStandards":1,
"IsInterestedinConference":1,
"VisitorExcites":[1,2,3]
"jsonkey" : "rUinterested"
}
]
}
try {
JSONArray arry = new JSONArray();
JSONObject iner = new JSONObject();
iner.put("Name", "nmae");
//all detail to iner
arry.put(iner);
JSONObject outer = new JSONObject();
outer.put("VisitorDetails", arry);
}
catch (Exception e){
}
final JSONObject jsonObject=new JSONObject();
try {
JSONArray jsonArray=new JSONArray();
JSONObject innerobject=new JSONObject();
innerobject.put("Name",Name);
innerobject.put("Address",Country);
jsonArray.put(innerobject);
jsonObject.put("VisitorDetails",jsonArray);
}catch (Exception e){
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, URL,jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// do something...
Toast.makeText(MainActivity.this, "your data successfully register", Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// do something...
Toast.makeText(MainActivity.this, "your data not register", Toast.LENGTH_SHORT).show();
}
}) {
/**
* Passing some request headers
*/
#Override
protected Map<String, String> getParams() {
Map<String, String> param = new HashMap<String, String>();
param.put("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
return param;
}
};
Update : add this in your gradle(app level)
compile 'com.android.volley:volley:1.0.0'
developing from Bansal ans .
your json data
JSONArray arry = new JSONArray();
try {
JSONObject jsonobject_one = new JSONObject();
jsonobject_one.put("Name", "Name");
// add all details like this
arry.put(jsonobject_one);
JSONObject jsonobject_TWO = new JSONObject();
jsonobject_TWO.put("VisitorDetails", arry);
}catch (JSONException e) {
e.printStackTrace();
}
Then Your jsonRequest
JsonArrayRequest jsonArryReq = new JsonArrayRequest(
Request.Method.POST,url, arry,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
/**
* Passing some request headers
* */
#Override
protected Map<String, String> getParams()
{
Map<String, String> param = new HashMap<String, String>();
if (!GetMethod) {
param.put("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
return param;
}
return param;
}

How can I post a parameter through JsonObjectRequest

I asked this before but I did not get a solution,
I am trying to post a parameter to the php script and get its results as json array however every time I try I get all of the columns in my table. At first I though there is something wrong with my php, however I tried from postman and see that my php works. So there is a problem in my code, problem is I am building a searchview so every time user enters it searches the data from database and shows the result in a listview. But I cannot post my parameter to my php script by using JsonObjectRequest. So how can I do it?
public void findSearchedUsers(String s)
{
HashMap<String, String> params = new HashMap<String, String>();
params.put("keyword",s );
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,"http://ksdb.comlu.com/search.php", new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray= response.getJSONArray("users");
for(int i = 0; i < jsonArray.length(); i ++){
JSONObject user = jsonArray.getJSONObject(i);
String id = user.getString("u_id");
String name = user.getString("u_name");
String surname = user.getString("u_lname");
String email = user.getString("u_email");
String password = user.getString("u_pw");
String department = user.getString("u_dp");
User newUser = new User(id, name, surname, email, password, department);
userArrayList.add(newUser);
}
setUsersListView(userArrayList );
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
RequestQueue queue = Volley.newRequestQueue(MainUserPage.this);
queue.add(req);
}
here is my php code and I and I also changed the android code too
<?php
// include connect class
$response = array();
// include connect class
require_once 'connect.php';
// connecting to db
$db = new DB_CONNECT();
// connecting to db
$keyword=$_GET["keyword"];
$result = mysql_query("SELECT * FROM user WHERE u_name LIKE'%$keyword%' LIMIT 0, 20")
or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
$response["users"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$users= array();
$users["u_id"] = $row["u_id"];
$users["u_name"] = $row["u_name"];
$users["u_lname"] = $row["u_lname"];
$users["u_email"] = $row["u_email"];
$users["u_pw"] = $row["u_pw"];
$users["u_dp"] = $row["u_dp"];
array_push($response["users"], $users);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No idioms found";
// echo no users JSON
echo json_encode($response);
}
?>
You should override the "getParams()" method on your request object.
If it doesn't work for a JSONObjectRequest, then try using a StringRequest and override the getParams() method.
Here's an example from their help.
StringRequest sr = new StringRequest(Request.Method.POST,"http://api.someservice.com/post/comment", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
mPostCommentResponse.requestCompleted();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mPostCommentResponse.requestEndedWithError(error);
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("user",userAccount.getUsername());
params.put("pass",userAccount.getPassword());
params.put("comment", Uri.encode(comment));
params.put("comment_post_ID",String.valueOf(postId));
params.put("blogId",String.valueOf(blogId));
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Content-Type","application/x-www-form-urlencoded");
return params;
}
};

Hi, I have issue in my Volley post method

I want to post the data as json formatted,but i dont know how to do that please help me to solve this issue.Normally i use the Volley post method as below (Its not any formatted type),its perfectly working for me,but now my backend developer ask me to post details as json format.
String url=" http://10.10.4.27/teacherapp_dxb/index.php/teacher_app_cn/login?user_id=EMP263&password=thanzeel";
StringRequest strReq = new StringRequest(Request.Method.POST,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
}
else {
// order error
String responseMsg = jObj.getString("response");
Toast.makeText(Viewactivity.this,
"ooola kirane"+ responseMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Viewactivity.this,
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Post product to orderplacing url
Map<String, String> params = new HashMap<String, String>();
params.put("user_id,"EMP263")
params.put("password","thanzeel");
return params;
}
};
// Adding request to queue
AppController.getInstance().addToRequestQueue(strReq);
}
In the above code i send the data wit out any format,but the backend developer need get the data as json format.So please help me to solve this issue.
You can do it like below in your getParams()
Map<String, String> params = new HashMap<String, String>();
params.put("user_id","EMP263");
params.put("password","thanzeel");
JSONObject jsonObjectParam = new JSONObject(params);
Map<String,String > postParams = new HashMap<>();
postParams.put("key",""+jsonObjectParam);
you can ask for this "key" to your backend team.
Hope it helps!
If you want to send data in JSONArray from android app try this way :
public String makeJSON(String s1,String s2,String s3){
JSONArray jsonArray = new JSONArray();
JSONObject data = new JSONObject();
try {
data.put("dataparam1",s1);
data.put("dataparam2", s2);
data.put("dataparam3", s3);
} catch (JSONException e) {
e.printStackTrace();
}
jsonArray.put(data);
JSONObject jsonData = new JSONObject();
try {
jsonData.put("dataArray", jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
String jsonStr = jsonData.toString();
System.out.println("jsonString: "+jsonStr);
return jsonStr;
}
And if you just want to send data in JSONObject try this :
public String createjson(String s1,String s2,String s3)
{
JSONObject jsonObj = new JSONObject();
JSONArray jsonArr = new JSONArray();
JSONObject jsonObject = new JSONObject();
try {
jsonObj.put("dataparam1",s1);
jsonObj.put("dataparam2",s2);
jsonObj.put("dataparam3",s3);
jsonArr.put(jsonObj);
jsonObject.put("cartItems", jsonArr);
} catch (JSONException e) {}
return jsonObject.toString();
}

Categories

Resources