How to update json data using volley method on Android? - android

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

Related

Textview not showing anything from JSON Object

Response from android is good which is the database i choose based on some value
Response: {"users":[{"id":"6","unique_id":"5f8fb2d3ee71c9.27038026","name":"siapa","email":"aku","encrypted_password":"G2HXPazvWEKRdm6lo5IDs4KSDEQ5ZTdlYjgyODBj","salt":"9e7eb8280c","created_at":"2020-10-21 11:02:27","updated_at":"2020-10-21 20:24:19"}]}
i need to show only object "updated_at" in textview but didnt show anything
this is my json code
private void getData() {
String tag_string_req = "get";
ArrayList<HashMap<String, String>> list_data;
list_data = new ArrayList<HashMap<String, String>>();
StringRequest strReq = new StringRequest(Method.GET,
AppConfig.URL_GET, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("users");
for (int a = 0; a < jsonArray.length(); a++) {
JSONObject json = jsonArray.getJSONObject(a);
HashMap<String, String> map = new HashMap<String, String>();
map.put("updated_at", json.getString("updated_at"));
list_data.add(map);
}
update_time.setText(list_data.get(0).get("updated_at"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
});
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
what could be wrong?

Adding volley response to global variables

I have using volley library for fetching data. I used a HashMap to store response data. When I fetch the data out of the volley request it is showing empty. I knew I should use this Hashmap inside the response method. But I need to get that in a global variable. Any suggestions?
String liveURL = BASE_URL + "livescores?api_token=" + API_KEY;
HashMap<String, String> hashMap = new HashMap<>();
JsonObjectRequest livescoresRequest = new JsonObjectRequest(Request.Method.GET,
liveURL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
final JSONArray liveArray = response.getJSONArray("data");
for (int i = 0; i < liveArray.length(); i++) {
JSONObject data = liveArray.getJSONObject(i);
String liveID = data.getString("id");
final String league_id = data.getString("league_id");
hashMap.put(league_id, liveID);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error", error.toString());
}
});
Volley.newRequestQueue(getContext()).add(livescoresRequest);
Log.i("HASHMAP", hashMap.toString());

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

Append json array request with a sessionaid

I am sending a request to retrieve an array of information from a mysql database using php script. At first it worked with just the url only, but I am struggling to add sessionID to the JsonArrayRequest as a parameter. How can I add my parameter sessionID with the array request?
public class MainActivity extends AppCompatActivity {
RequestQueue rq;
String sessionID;
TextView email, fullname , contact;
String emailStr, fullnameStr, contactStr;
String url = "http://kutso011.000webhostapp.com/RetrieveData.php";
String jsonResponse;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rq = Volley.newRequestQueue(this);
email = (TextView)findViewById(R.id.txtemaill);
fullname = (TextView)findViewById(R.id.txtFullnamee);
contact = (TextView)findViewById(R.id.txtContactt);
sessionID = getIntent().getStringExtra("UserID");
sendjsonrequest();
}
private void sendjsonrequest() {
JsonArrayRequest req = new JsonArrayRequest(url, sessionID,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
String emailStr = person.getString("email");
String contactStr = person.getString("Contact");
String fullnameStr = person.getString("FullName");
email.setText(emailStr);
fullname.setText(fullnameStr);
contact.setText(contactStr);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error)
{
}
});
// Adding request to request queue
//AppController.getInstance().addToRequestQueue(req);
rq.add(req);
//rq.add(jsonObjectRequest);
}
}
public class Profile extends AppCompatActivity {
private String sessionID;
RequestQueue rq;
String jsonResponse;
String url = "http://kutso011.000webhostapp.com/October/retrieveData.php";
EditText fname_,lname_,contact_,email_;
public void initViews()
{
fname_ = (EditText)findViewById(R.id.etFName);
lname_ = (EditText)findViewById(R.id.etLName);
contact_ = (EditText)findViewById(R.id.etContact);
email_ = (EditText)findViewById(R.id.etMail);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
rq = Volley.newRequestQueue(this);
initViews();
sessionID = getIntent().getStringExtra("sessionID");
sendjsonrequest(sessionID);
}
private void sendjsonrequest(final String sessionID)
{
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try
{
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
JSONObject profileInfo = (JSONObject) response
.get(i);
String fname = profileInfo.getString("FirstName"); //
String lname = profileInfo.getString("LastName");
String contact = profileInfo.getString("Contact");
String email = profileInfo.getString("Email");
Toast.makeText(getApplicationContext(), fname , Toast.LENGTH_LONG).show();
fname_.setText("fname");
lname_.setText(lname);
contact_.setText(contact);
email_.setText(email);
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Toast.makeText(getApplicationContext(),"Could not fetch data, connection error " , Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams()
{
// Posting parameters to retrieve profile url
Map<String, String> params = new HashMap<String, String>();
params.put("sessionID", sessionID);
return params;
}
};
// Adding request to request queue
//AppController.getInstance().addToRequestQueue(req);
rq.add(req);
//rq.add(jsonObjectRequest);
}
}

How to Get String from JSON Array [duplicate]

This question already has answers here:
JSON Array of strings (no objects), extracting data
(4 answers)
Closed 6 years ago.
its actually a simple code, cuz of lack of basic I still cant manage to handle this.
After I made a Post JSON Method on my own Api, I get the following response
[{"id":"2"}]
What I'm trying to achieve is that I would like to get the value of this "id" which is "2".
I've tried the following code in my private void method
private void getUserID() {
StringRequest stringRequest = new StringRequest(Method.POST,Constants.GET_USER_ID,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
try {
JSONObject jsonRootObject = new JSONObject(strJson);
//Get the instance of JSONArray that contains JSONObjects
JSONArray jsonArray = jsonRootObject.optJSONArray("");
//Iterate the jsonArray and print the info of JSONObjects
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
int id = Integer.parseInt(jsonObject.optString("id").toString());
String idUser = jsonObject.optString("id").toString();
}
output.setText(idUser);
} catch (JSONException e) {e.printStackTrace();}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
map.put(Constants.KEY_A, username);
map.put(Constants.KEY_B, password);
return map;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
I get it from here.
It's a bit of waste, because I only have one list object in my array, and I thinks for loop is not really important in here.
replace your try block with following
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String idUser = jsonObject.getString("id");
Log.e("id is: ", idUser);
}
Try this way you will get
private void makeJsonArrayRequest() {
showpDialog();
JsonArrayRequest req = new JsonArrayRequest( delprourl,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("ress", response.toString());
// Parsing json
try {
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
System.out.println("person" + person);
//get your id here
String id = person.getString("id");
Log.e("id: ", id);
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
// notifying list adapter about data changes
// so that it renders the list view with updated data
//adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("ErrorVolley", "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
});
MyApplication.getInstance().addToReqQueue(req, "jreq");
}
private void showpDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hidepDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}

Categories

Resources