display json array in textview android not working - java

My JSON array don't work and I don't know why. In logs, it only show this: [] and nothing else. I won't use that in text view.
This is my code:
private void account(){
// get from the server
String url = "my url";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("uaccount");
Log.i("conso", jsonArray.toString());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject employee = jsonArray.getJSONObject(i);
Log.i("con", employee.toString());
//Log.i("con", name+ number+status+ age+ city+ town+ gender+weight +height);
String city = employee.getString("city");
String town = employee.getString("town");
txt_City.setText(""+city);
txt_Town.append(town);
//Log.i("co", city + town);
}
} catch (JSONException e) {
Log.i("console.logs e:", e.toString());
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("console.logs error:", error.toString());
error.printStackTrace();
}
});
requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(request);
}

i tried this code with id :
in onreate:
uAccount("3");
in method
private void uAccount(final String id){
// get from server
String url = "my url";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("uaccount");
Log.i("conso", jsonArray.toString());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject employee = jsonArray.getJSONObject(i);
Log.i("con", employee.toString());
//Log.i("con", name+ number+status+ age+ city+ town+ gender+weight +height);
String city = employee.getString("city");
String town = employee.getString("town");
txt_City.setText(""+city);
txt_Town.append(town);
//Log.i("co", city + town);
}
} catch (JSONException e) {
Log.i("console.logs e:", e.toString());
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("console.logs error:", error.toString());
error.printStackTrace();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("id",id);
return params;
}
};
requestQueue = Volley.newRequestQueue(getActivity());
requestQueue.add(request);
}

Related

I want to create an ArrayList with a dynamic index not starting from 0

public void jsonParse(){
jsonResArray = new ArrayList< >();
String url = "my-api-url";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new
Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("data");
if(jsonArray.length()!=0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int id =Integer.parseInt(jsonObject.getString("service_id"));
**jsonResArray.add(id, jsonObject.getString("service_name"));**
}}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getBaseContext() , e.toString() , Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getBaseContext(),error.getMessage(),Toast.LENGTH_SHORT).show();
}
});
mQueue.add(request);
}
I want to create dynamic index as i want to save service name against its id in string array but its giving me index out of bp
Thanks in advance
Use a Map<Integer, String> instead of an ArrayList<String>.

How to send params to json array request in android volley

I have a students table.
I am trying to send request to and REST APP using the HTTPS and JSON Array from the Android studio to My web-based application.
My request works fine.
The problem I am getting is how to send params in the request.
public void SyncRoutsAfterExport(){
//Send request to server to get routes
//Request que
RequestQueue mQueue = Volley.newRequestQueue(UserProfile.this);
//Json perse function
String url = "xxxxxxxxxxxxxxxxxx";
Map<String, String> params = new HashMap<String, String>();
params.put("name", "mark");
params.put("nam", "someOtherVal");
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++){
try {
JSONObject jresponse = response.getJSONObject(i);
String name= jresponse.getInt("name");
String age= jresponse.getString("age");
AddDatatotable(name,age);
if(i == response.length() -1){
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
}
so In the above code, I want to send couple of params name and age. How to send the above request with params.
I think you can try StringRequest and overload getParams Method
RequestQueue mQueue = Volley.newRequestQueue(UserProfile.this);
//Json perse function
String url = "xxxxxxxxxxxxxxxxxx";
Map<String, String> params = new HashMap<String, String>();
params.put("name", "mark");
params.put("nam", "someOtherVal");
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String requestResponse) {
JSONArray response
try {
array=new JSONArray(requestResponse);
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < response.length(); i++){
try {
JSONObject jresponse = response.getJSONObject(i);
String name= jresponse.getInt("name");
String age= jresponse.getString("age");
AddDatatotable(name,age);
if(i == response.length() -1){
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
return params;
}
};
mQueue.add(request);

how to POST raw type JSON Data in Body?

I'm sending a post request to server using Volley request and i have some raw Type JSON data that has to be sent. Here I have no idea how to send the
4th object students which is type of Array.
JSON data to be posted is
{
"course_id":1,
"batch_id":1,
"subject_id":1,
"students":[{"student_id":6,"present":0},{"student_id":17,"present":0}]
}
My code
private void fetchDataAndMarkAttendence() {
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
status = jsonObject.getString("status");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> map = new HashMap<String, String>();
SharedPreferences prefs = getApplicationContext().getSharedPreferences(MY_PREFS_NAME, Activity.MODE_PRIVATE);
token = prefs.getString("token","");
map.put("Authorization", "Token "+token);
return map;
}
}
}
So, any help regarding how can i post the JSON data mentioned above will be helpfull.
This is called JSONArray.
try {
JSONArray jsonArray = jsonObject.getJSONArray();
for (int i = 0; i < jsonArray.length(); i++) {
int student_id = jsonObject.getInt("student_id");
int present = jsonObject.getInt("present");
}
} catch (JSONException e) {
e.printStackTrace();
}
EDIT
as mention, you want to post the json. So create the json suing below code and post mainJsonObject.toString(); as parameter.
try {
JSONObject mainJsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
//if more than one then wrap inside loop
JSONObject jsonObject = new JSONObject();
jsonObject.put("student_id", value);
jsonObject.put("present", value);
jsonArray.put(jsonObject);
//end loop
mainJsonObject.put("course_id", value);
mainJsonObject.put("batch_id", value);
mainJsonObject.put("subject_id", value);
mainJsonObject.put("students", jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
hope it helps.
Replace your StringRequest with JsonObjectRequest
JSONObject postparams = new JSONObject();
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, postparams,
new Response.Listener() {
#Override
public void onResponse(JSONObject response) {
//Success Callback
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Failure Callback
}
});
can you try this? This probably will fix your problem.
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
status = jsonObject.getString("status");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
}){
#Override
public byte[] getBody() throws AuthFailureError {
String yourJSON = yourJsonObj.toString() ;
return yourJSON.getBytes();
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> map = new HashMap<String, String>();
SharedPreferences prefs = getApplicationContext().getSharedPreferences(MY_PREFS_NAME, Activity.MODE_PRIVATE);
token = prefs.getString("token","");
map.put("Authorization", "Token "+token);
return map;
}
};

Geting null from ArrayList in Android when extract JSONArray

I'm using Volley to get information from an SQL database, from server, and I get it in a JSONArray. When I extract values from the JSONArray so I can save values to an ArrayList, in the return statement I get null in my ArrayList. Can anyone help with the return statement?
#Override
public List<WorkItem> getWorkItem() {
final String url = "http://10.0.2.2:8080/items/all/items";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("Response", response.toString());
try {
arrayList = new ArrayList<>();
response = new JSONArray(response.toString());
for (int i = 0; i < response.length(); i++) {
JSONObject jsonobject = response.getJSONObject(i);
String title = jsonobject.getString("title");
String description = jsonobject.getString("description");
String state = jsonobject.getString("status");
String assignee = jsonobject.getString("assignee");
arrayList.add(new WorkItem(title, description, state, assignee));
arrayList.size();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error", error.getMessage());
}
});
jsonArrayRequest.setTag(REQUEST_TAG);
mQueue.add(jsonArrayRequest);
return arrayList;
}

Why do these two strings ( company_id & branch_id ) equal null in MyRequestQueue_Drivers?

**
the parameters of volley (company_id && branch_id)
equal null although I got its real data before via MyRequestQueue_Company so it causes volley response is nullpointer exception
Why do company_id and branch_id equal null in MyRequestQueue_Drivers? How can I solve this?
public class CheckinActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
String company_id, branch_id;
Spinner driver_name_spinner;
private String User_URL = "http://example.com/api/user?token=";
private String Drivers_URL = "http://example.com/api/getDrivers?company_id=1&branch_id=15";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checkin);
driver_name_spinner = (Spinner) findViewById(R.id.driver_name_spinner);
next = (Button) findViewById(R.id.next);
SharedPreferences sharedPref = getSharedPreferences("userinfo", getApplicationContext().MODE_PRIVATE);
final String token = sharedPref.getString("token", "");
final RequestQueue MyRequestQueue_Company = Volley.newRequestQueue(this);
// GET COMPANY_ID AND BRANCH_ID FORM API
StringRequest MyStringRequest_Company = new StringRequest(Request.Method.GET, User_URL + token, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("response", response);
try {
JSONObject jsono = null;
jsono = new JSONObject(response);
JSONObject jarray = jsono.getJSONObject("user");
company_id = jarray.getString("company_id");
branch_id = jarray.getString("branch_id");
Log.d("User Data", "company_id " + company_id + "\tbranch_id " + branch_id);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
//This code is executed if there is an error.
}
});
MyRequestQueue_Company.add(MyStringRequest_Company);
// CALL ANOTHER WEBSERVICES TO GET DRIVERS DATA
RequestQueue MyRequestQueue_Drivers = Volley.newRequestQueue(getApplicationContext());
StringRequest MyStringRequest_Drivers = new StringRequest(Request.Method.POST, Drivers_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("Drivers Response", response);
try {
JSONObject jsono = null;
jsono = new JSONObject(response);
JSONArray jarray = jsono.getJSONArray("Drivers");
List<String> drivers;
drivers = new ArrayList<String>();
for (int i = 0; i < jarray.length(); i++) {
JSONObject newobject = jarray.getJSONObject(i);
driver_name_txt = newobject.getString("name");
Log.d("Driver Name", driver_name_txt);
drivers.add(driver_name_txt);
}
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_spinner_item, drivers);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
driver_name_spinner.setAdapter(dataAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Drivers Error",error.toString());
}
}) {
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
// BRANCH_ID AND COMPANY_ID ARE EQUAL NULL !?
MyData.put("branch_id", branch_id);
MyData.put("company_id", company_id);
Log.d("Last User Data", "company_id " + company_id + "\tbranch_id " + branch_id);
return MyData;
}
};
MyRequestQueue_Drivers.add(MyStringRequest_Drivers);
driver_name_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long l) {
TextView tmpView = (TextView) driver_name_spinner.getSelectedView().findViewById(android.R.id.text1);
tmpView.setTextColor(Color.WHITE);
driver_name_txt = parent.getItemAtPosition(position).toString();
Log.d("driver_name_original", driver_name_txt);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
If you want to use getParams function, than I would suggest to define a flag and modify your function like:
#Override
public void onResponse(String response) {
Log.d("response", response);
try {
JSONObject jsono = null;
jsono = new JSONObject(response);
JSONObject jarray = jsono.getJSONObject("user");
company_id = jarray.getString("company_id");
branch_id = jarray.getString("branch_id");
Log.d("User Data", "company_id " + company_id + "\tbranch_id " + branch_id);
requestFinished = true;
} catch (JSONException e) {
e.printStackTrace();
}
}
And your getParams would look like :
protected Map<String, String> getParams() {
if(!requestFinished) return null;
Map<String, String> MyData = new HashMap<String, String>();
// BRANCH_ID AND COMPANY_ID ARE EQUAL NULL !?
MyData.put("branch_id", branch_id);
MyData.put("company_id", company_id);
Log.d("Last User Data", "company_id " + company_id + "\tbranch_id " + branch_id);
return MyData;
But I would suggest to you to use the Observer pattern instead.

Categories