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);
Related
public class Login extends AppCompatActivity {
private static String LOGIN_URL = "http://172.26.154.132:75";
private EditText username;
private EditText password;
private Button buttonLogin;
private ProgressBar loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
username = (EditText) findViewById(R.id.input_email1);
password = (EditText) findViewById(R.id.input_password);
buttonLogin = (Button) findViewById(R.id.btn_login);
loading = findViewById(R.id.loading);
buttonLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mEmail = username.getText().toString().trim();
String mPass = password.getText().toString().trim();
if(!mEmail.isEmpty() || !mPass.isEmpty()){
Login1(mEmail, mPass);
} else {
username.setError("Please insert email");
password.setError("Please insert password");
}
}
});
}
private void Login1(final String username, final String password) {
loading.setVisibility(View.VISIBLE);
buttonLogin.setVisibility(View.GONE);
StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("data");
JSONArray jsonArray = jsonObject.getJSONArray("data");
if (success.equals("data")) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
Intent intent = new Intent(Login.this, MainActivity.class);
startActivity(intent);
loading.setVisibility(View.GONE);
}
}
} catch (JSONException e) {
e.printStackTrace();
loading.setVisibility(View.GONE);
buttonLogin.setVisibility(View.VISIBLE);
Toast.makeText(Login.this, "error" + e.toString(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.setVisibility(View.GONE);
buttonLogin.setVisibility(View.VISIBLE);
Toast.makeText(Login.this, "error" + error.toString(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("username", username);
params.put("password", password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
The response:
{
"status": true,
"message": "User login successful.",
"data": [
{
"sno": "165",
"username": "khushboo.iit#gmail.com",
"user_id_generate": "khushbu#Paswan2018782",
"password": "25f9e794323b453885f5181f1b624d0b",
"is_verified": "1",
"hash": "",
"user_type": "icb_user",
"user_role": "admin"
}
]
}
If your API successfully return data then the problem is JSON parsing. JSON data not parsed successfully. Because "data" contains an array not a single String value.
Try this
try {
JSONObject jsonObject = new JSONObject(response);
boolean success = jsonObject.getBoolean("status");
JSONArray jsonArray = jsonObject.getJSONArray("data");
if (success) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
Intent intent = new Intent(Login.this, MainActivity.class);
startActivity(intent);
loading.setVisibility(View.GONE);
}
}
} catch (JSONException e) {
e.printStackTrace();
loading.setVisibility(View.GONE);
buttonLogin.setVisibility(View.VISIBLE);
Toast.makeText(Login.this, "error" + e.toString(), Toast.LENGTH_SHORT).show();
}
I didnt understood question properly but i think i know what you meant.
As there are two functions one is for success and one is for failure you can handle cases like this..
Use JSONObjectRequest instead of string request, It will return you a JSONObject string instead of a string response. Or You can convert the string into a JSONObject like this
JSONObject response = new JSONObject(response)
and then you can parse the jsonObject like this.
if(respose.optString("status")==true)
//success
else
//failed
If you want to print the error msg which is coming from server... do it like this:
error.networkResponse.statusCode
error.networkResponse.message
I get the error no value for city.
I'm new to Android. I was unable to pass the spinner data using PHP URL, volley method. And in my XML I'm using the spinner and text views city, id and pass the city list through spinner URL.
Here is my activity:
private void spinnerapi(){
sprCoun = (Spinner) findViewById(R.id.spinner);
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
String serverURL = "server url";
final StringRequest getRequest = new StringRequest(Request.Method.POST, serverURL,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("officerResponse", response);
try {
JSONObject jsonObject = new JSONObject(response);
String str_status = jsonObject.getString("status");
String str_message = jsonObject.getString("message");
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjectGuest = jsonArray.getJSONObject(i);
city_name = jsonObjectGuest.getString("cityname");
city_id = jsonObjectGuest.getString("cityid");
listarraylist.add(new CityModel(city_name));
}
sprCoun.setAdapter(new ArrayAdapter<String>
(RegistrationActivity.this, android.R.layout.simple_spinner_dropdown_item, list));
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "" + e, Toast.LENGTH_LONG).show();
}
}
},
new com.android.volley.Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
// Toast.makeText(context, "" + error, Toast.LENGTH_LONG).show();
Log.d("tyghj", String.valueOf(error));
}
}
) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
queue.add(getRequest);
}
I have a big problem with volley request sequence and making json array out of first request response for second request.
this is the code :
JSONObject imageAddedResponse = new JSONObject();
JSONArray imagesAddedResponse = new JSONArray();
public void postImageData(Context applicationContext, String title, String note, ArrayList<ContentData> mImages, String videoPath, final Listeners.APIPostDataListener listener) {
//Instantiate the RequestQueue.
RequestQueue requestQueue = Volley.newRequestQueue(applicationContext);
Settings settings = new Settings(applicationContext);
String selectedURL = settings.getChosenUrl();
final String token = settings.getTokenKey();
String url = "http://" + selectedURL + "/databox/api/v1/upload/files";
HashMap<String, String> params = new HashMap<String, String>();
params.put("Authorization", "Bearer " + token);
params.put("Content-Disposition", "form-data" + "; charset=utf-8");
//POST data to CMS to get JSONObject back
for (int i = 0; i < mImages.size(); i++) {
String path = String.valueOf(mImages.get(i).getPath());
File file = new File(path);
MultipartRequest request = new MultipartRequest(url, file, Response.class, params, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (listener != null) {
listener.onAPIPostData(String.valueOf(response), true);
}
if (response != null || response != "") {
try {
imageAddedResponse = new JSONObject(response);
JSONObject jsonArraydata = imageAddedResponse.getJSONObject("data");
JSONArray jsonArrayImages = jsonArraydata.getJSONArray("images");
imagesAddedResponse.put(jsonArrayImages);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley Request Error", error.toString());
if (listener != null) {
listener.onAPIPostData("", false);
}
}
});
requestQueue.add(request);
}
//POST request to add entity to CMS
JSONObject jsonimages = new JSONObject();
JSONArray jsonArrayimages = new JSONArray();
for (int i = 0 ; i < imagesAddedResponse.length() ; i++){
try {
JSONObject getObjectValues = imagesAddedResponse.getJSONObject(i);
jsonimages.put("id",getObjectValues.getString("id"));
jsonimages.put("src",getObjectValues.getString("src"));
jsonimages.put("size",getObjectValues.getString("size"));
jsonimages.put("baseName",getObjectValues.getString("baseName"));
jsonimages.put("type",getObjectValues.getString("type"));
jsonimages.put("db_languages_id", "1");
jsonimages.put("title",String.valueOf(mImages.get(i).getTitle()));
} catch (JSONException e) {
e.printStackTrace();
}
}
JSONObject json = new JSONObject();
JSONArray jsonArray = new JSONArray();
JSONObject finalobject = new JSONObject();
try {
json.put("title", title);
json.put("description", note);
json.put("db_languages_id", "1");
json.put("db_user_id", "3");
jsonArray.put(json);
finalobject.put("data", jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
String urlFinal = "http://" + selectedURL + "/databox/api/v1/1/entity";
JsonObjectRequest postRequest = new JsonObjectRequest(urlFinal, json, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// response
if (listener != null) {
listener.onAPIPostData(String.valueOf(response), true);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
if (listener != null) {
listener.onAPIPostData("", false);
}
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Authorization", "Bearer " + token);
params.put("Content-Type", "application/json; charset=utf-8");
return params;
}
};
postRequest.setShouldCache(false);
requestQueue.add(postRequest);
}
first request post to CMS and get some information for images posted and then I need to add those information to next post to make entity based on response I got back from first post request.
int totalSuccesfulImagePost = 0; //this variable increment when each succesful response from multipart-request
public void postImageData(Context applicationContext, String title, String note, ArrayList<ContentData> mImages, String videoPath, final Listeners.APIPostDataListener listener) {
//Instantiate the RequestQueue.
RequestQueue requestQueue = Volley.newRequestQueue(applicationContext);
Settings settings = new Settings(applicationContext);
String selectedURL = settings.getChosenUrl();
final String token = settings.getTokenKey();
String url = "http://" + selectedURL + "/databox/api/v1/upload/files";
HashMap<String, String> params = new HashMap<String, String>();
params.put("Authorization", "Bearer " + token);
params.put("Content-Disposition", "form-data" + "; charset=utf-8");
//POST data to CMS to get JSONObject back
for (int i = 0; i < mImages.size(); i++) {
String path = String.valueOf(mImages.get(i).getPath());
File file = new File(path);
MultipartRequest request = new MultipartRequest(url, file, Response.class, params, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (listener != null) {
listener.onAPIPostData(String.valueOf(response), true);
}
if (response != null || response != "") {
try {
imageAddedResponse = new JSONObject(response);
JSONObject jsonArraydata = imageAddedResponse.getJSONObject("data");
JSONArray jsonArrayImages = jsonArraydata.getJSONArray("images");
imagesAddedResponse.put(jsonArrayImages.getJSONObject(0));
totalSuccesfulImagePost++; //here we increase the count
postRequest(token); //call this method and check wheather all the image uploaded or not
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley Request Error", error.toString());
if (listener != null) {
listener.onAPIPostData("", false);
}
}
});
requestQueue.add(request);
}
}
//make this as seperate method and call when all multipart-request call succesful
public void postRequest(String token){
if(totalSuccesfulImagePost != mImages.size()) {
//this means not all the images posted yet, hence return the method
return;
}
//POST request to add entity to CMS
JSONObject jsonimages = new JSONObject();
JSONArray jsonArrayimages = new JSONArray();
for (int i = 0 ; i < imagesAddedResponse.length() ; i++){
try {
JSONObject getObjectValues = imagesAddedResponse.getJSONObject(i);
jsonimages.put("id",getObjectValues.getString("id"));
jsonimages.put("src",getObjectValues.getString("src"));
jsonimages.put("size",getObjectValues.getString("size"));
jsonimages.put("baseName",getObjectValues.getString("baseName"));
jsonimages.put("type",getObjectValues.getString("type"));
jsonimages.put("db_languages_id", "1");
jsonimages.put("title",String.valueOf(mImages.get(i).getTitle()));
} catch (JSONException e) {
e.printStackTrace();
}
}
JSONObject json = new JSONObject();
JSONArray jsonArray = new JSONArray();
JSONObject finalobject = new JSONObject();
try {
json.put("title", title);
json.put("description", note);
json.put("db_languages_id", "1");
json.put("db_user_id", "3");
jsonArray.put(json);
finalobject.put("data", jsonArray);
} catch (JSONException e) {
e.printStackTrace();.getJSONObject(0)
}
String urlFinal = "http://" + selectedURL + "/databox/api/v1/1/entity";
JsonObjectRequest postRequest = new JsonObjectRequest(urlFinal, json, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// response
if (listener != null) {
listener.onAPIPostData(String.valueOf(response), true);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
if (listener != null) {
listener.onAPIPostData("", false);
}
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Authorization", "Bearer " + token);
params.put("Content-Type", "application/json; charset=utf-8");
return params;
}
};
postRequest.setShouldCache(false);
requestQueue.add(postRequest);
}
updated your code. Hope this may help you.
I've created new method for JsonObjectRequest with the name postRequest();
totalSuccesfulImagePost variable holds the no. of succesfull response for image upload
new method postRequest() calls at each multipart-request response
postRequest() methods check if not all response process yet than skip the 2nd api call
Also see how fb do this batch request https://developers.facebook.com/docs/android/graph/ -> Batch Reqest
Note -
Ive increment the variable totalSuccesfulImagePost and handle in each response, although you need to Response.ErrorListener()
Although you can go with the ThreadPoolExecutor option where each thread is created to handle each multipart-request upload and after all thread execution , call the method postRequest()
Work-around using ThreadPoolExecutor
a) Create ThreadPoolExecutor & initialize min/max pool size
b) Asign each mulitpart-request to upload image to each thread
c) Add all thread (contain image upload multipart-request) to ThreadPoolExecutor
d) Execute pool
e) call postRequest() method when ThreadPoolExecutor is empty i.e. this means all the thread execution is done and ready to call postRequest()
it is possible using Priority Of each Request.
private Priority priority = Priority.HIGH;
StringRequest strReq = new StringRequest(Method.GET,
Const.URL_STRING_REQ, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
msgResponse.setText(response.toString());
hideProgressDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hideProgressDialog();
}
}) {
#Override
public Priority getPriority() {
return priority;
}
};
MyApplication.getInstance().addToRequestQueue(strReq);
i have a problem with my code and other post cannot helped me that's why i post here.
I'm getting some json from my php like
{
"lesMots":{
"1":{
"id":"4",
"wordFrench":"bite",
"wordEnglish":"dick"
},
"2":{
"id":"7",
"wordFrench":"pute",
"wordEnglish":"whore"
},
"3":{
"id":"2",
"wordFrench":"ordinateur",
"wordEnglish":"computer"
},
"4":{
"id":"1",
"wordFrench":"bonjour",
"wordEnglish":"hello"
},
"5":{
"id":"3",
"wordFrench":"monde",
"wordEnglish":"world"
}
}
}
Here is my Volley Request, i know i must use JSONObject for my JSONArray, but when i change it, the second JSONObject word ask me string and not int !
i'm trying to get 5 random french word and english word
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://ent-ifsi.com/Projet/Application_Android/pendu_android.php",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("lesMots");
for (int i = 0; i < jsonArray.length();i++){
JSONObject word = jsonArray.getJSONObject(i);
String wordFrench = word.getString("wordFrench");
String wordEnglish = word.getString("wordEnglish");
textView.append(wordFrench+" "+wordEnglish+" "+" \n ");
Toast.makeText(getApplicationContext(), wordFrench +"",Toast.LENGTH_LONG).show();
}
}catch (JSONException e){
e.printStackTrace();
Toast.makeText(getApplicationContext(), e +"",Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "ERROR");
Toast.makeText(getApplicationContext(), error +"",Toast.LENGTH_LONG).show();
}
}
);
queue.add(jsonObjectRequest);
}
});
Thank for your help, i'm blocked on this problem and i'm kind of new in this.
If you need something more tell me
Try this, it will loop through the object based on the keys:
try {
JSONObject lesMots = response.getJSONObject("lesMots");
Iterator<?> keys = lesMots.keys();
while(keys.hasNext()) {
String key = (String)keys.next();
if (lesMots.get(key) instanceof JSONObject ) {
JSONObject obj = (JSONObject) lesMots.get(key);
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e +"",Toast.LENGTH_LONG).show();
}
You have to change jsonarray to jsonobject.
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://ent-ifsi.com/Projet/Application_Android/pendu_android.php",
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject jsonArray = response.getJSONObject("lesMots");
for (int i = 0; i < jsonArray.length();i++){
JSONObject word = jsonArray.getJSONObject(i);
String wordFrench = word.getString("wordFrench");
String wordEnglish = word.getString("wordEnglish");
textView.append(wordFrench+" "+wordEnglish+" "+" \n ");
Toast.makeText(getApplicationContext(), wordFrench +"",Toast.LENGTH_LONG).show();
}
}catch (JSONException e){
e.printStackTrace();
Toast.makeText(getApplicationContext(), e +"",Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "ERROR");
Toast.makeText(getApplicationContext(), error +"",Toast.LENGTH_LONG).show();
}
}
);
queue.add(jsonObjectRequest);
}
});
the issue is that you have an obaject not an array solution can be this:
(where you response is the same you receive from the callback)
for example to mock this you can do:
String responseJson = "{\"lesMots\":{\"1\":{\"id\":\"4\",\"wordFrench\":\"bite\"," +
"\"wordEnglish\":\"dick\"},\"2\":{\"id\":\"7\",\"wordFrench\":\"pute\"," +
"\"wordEnglish\":\"whore\"},\"3\":{\"id\":\"2\"," +
"\"wordFrench\":\"ordinateur\",\"wordEnglish\":\"computer\"}," +
"\"4\":{\"id\":\"1\",\"wordFrench\":\"bonjour\",\"wordEnglish\":\"hello\"}," +
"\"5\":{\"id\":\"3\",\"wordFrench\":\"monde\",\"wordEnglish\":\"world\"}}}";
JSONObject response = new JSONObject(responseJson);
then in your callback
#Override
public void onResponse(JSONObject response) {
try {
JSONObject lesMotsObject = response.getJSONObject("lesMots");
JSONArray jsonArray = lesMotsObject.toJSONArray(lesMotsObject.names());
for (int i = 0; i < jsonArray.length();i++){
JSONObject word = jsonArray.getJSONObject(i);
String wordFrench = word.getString("wordFrench");
String wordEnglish = word.getString("wordEnglish");
...
I have an obstacle by changing the data string into a jsonobject, is his org.json.JSONException script error: Value
This coding I am trying
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String username = inputUser.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
// Check for empty data in the form
if (username.trim().length() > 0 && password.trim().length() > 0) {
Map<String,String> params = new HashMap<>();
params.put("username", inputUser.getText().toString());
params.put("password", inputPassword.getText().toString());
sendPostRequest(params);
} else {
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(),
"Silahkan Masukan Username dan Password!", Toast.LENGTH_LONG)
.show();
}
}
});
public void sendPostRequest(Map<String, String> params) {
showDialog();
RequestQueue queue = Volley.newRequestQueue(this);
String url = "http://www.chris-chris.webege.com/login.php";
mCustomRequest = new CustomRequest(Request.Method.POST,
url, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Intent intent = new Intent(Login.this,
Coba.class);
startActivity(intent);
finish();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error", error.getMessage());
hidepDialog();
Toast.makeText(Login.this, "Belum Terhubung Internet! ", Toast.LENGTH_SHORT).show();
}
});
mCustomRequest.setRetryPolicy(new DefaultRetryPolicy(Template.VolleyRetryPolicy.SOCKET_TIMEOUT,
Template.VolleyRetryPolicy.RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(mCustomRequest);
}
There are two conditions to convert a string to JSONObject :
1 . The string should be in proper Json format .
2 . Put code in try catch block .
Example:
String jsonString = "{"status":"1","message":"Login successfully","data":{"uid":"1","email":"baleshwar#gmail.com","password":"202cb962ac59075b964b07152d234b70","name":"","role":"1","gender":"","address":"","image":"","is_active":"0","last_login":"0000-00-00 00:00:00","device_id":"0","created_at":"2015-06-03 06:01:02","updated_at":"2015-06-03 11:01:02","location":"","dob":"0000-00-00","descriptions":""}}"
Now convert this string to JSONObject
try{
JSONObject jsonResponse = new JSONObject(result);
}catch(Exception e){
e.printStackTrace();
}
Try this,
If you call your service and try to paste that code inside your isSucsess part
JSONObject jObject = jsonObject.getJSONObject("jsonobjectname");
tvTitle.setText(jObject.getString("your string name"));