How to get data out of try catch block? - java

final ArrayList<String> pic = new ArrayList<String>();
final ArrayList<String> name = new ArrayList<String>();
RequestQueue mQueue = Volley.newRequestQueue(this);
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++)
{
JSONObject jobj = response.getJSONObject(i);
name.add(jobj.getString("name"));
pic.add(jobj.getString("pic"));
}
txt1.setText(name.toString());
}
catch (JSONException e) { }
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("TAG", "Error: " + error.getMessage());
}
});
txt.setText(pic.toString());
mQueue.add(req);
name.toString in try is not empty(ex: [a,b,c,d]),but if i move this out of try like pic.toString array is empty (ex:[]).

Related

HOW to Get item ID on Spiner Mysql

Hy Friend i have a problem to save id on item selected
i have a table klasis = klasis_id,klasis_name,klasis_kode.
now how i get klasis_id when i click on spinner
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("klasis");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String klasisName = jsonObject.optString("klasis_name");
// String klasisId = jsonObject.optString("klasis_id");
klasisList.add(klasisName);
klasisAdapter = new ArrayAdapter<>(AddGereja.this,
android.R.layout.simple_spinner_item, klasisList);
klasisAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerKlasis.setAdapter(klasisAdapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
spinnerKlasis.setOnItemSelectedListener(this);
}

I have to show a list of Objects from a JSON array. But i cant seem to print it out

// I've declared everything here, everything looks fine from here. I don't think i have problems here
public class MainActivity extends AppCompatActivity {
private TextView mTextViewResult;
private RequestQueue mQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextViewResult = findViewById(R.id.text_view_result);
Button buttonParse = findViewById(R.id.button_parse);
mQueue = Volley.newRequestQueue(this);
buttonParse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
jsonParse();
}
});
}
private void jsonParse(){
String url = "https://fetch-hiring.s3.amazonaws.com/hiring.json";
// I don't know what my problem is here, i've declared everything and nothing is showing up, I was thinking i should've declared an array instead of an Object, but im still having difficulties
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("");
for (int i = 0; i < jsonArray.length(); i++){
JSONObject list = jsonArray.getJSONObject(i);
int id = list.getInt("id");
int listId = list.getInt("listId");
String name = list.getString("name");
mTextViewResult.append(String.valueOf(id) + ", " + String.valueOf(listId) + ", " + name + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
}
}
Since the response is a Json Array, you need to use JsonArrayRequest instead of JsonObjectRequest, and receive a JSONArray in onResponse.
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<org.json.JSONArray>() {
#Override
public void onResponse(org.json.JSONArray response) {
try {
for (int i = 0; i < response.length(); i++){
..... etc.
See https://javadoc.io/static/com.android.volley/volley/1.1.1/com/android/volley/toolbox/JsonArrayRequest.html
Try with following code.
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++){
JSONObject list = jsonArray.getJSONObject(i);
int id = list.getInt("id");
int listId = list.getInt("listId");
String name = list.getString("name");
mTextViewResult.append(String.valueOf(id) + ", " + String.valueOf(listId) + ", " + name + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
}
}

How to return the value of an asynchronous callback?

This is my code, it's a query to mysql for return 1 or 0, if exist a element in database. I want to know how I get the value?
private void comprobarUsuario(String url){
JsonArrayRequest jsonArrayRequest=new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject jsonObject = null;
for (int i = 0; i < response.length(); i++) {
try {
String ob = "IF(EXISTS (SELECT * FROM `loginusuario` WHERE `idusuario`='" + id.getText() + "' and `contrasena`='" + contra.getText() + "'), '1', '0')";
jsonObject = response.getJSONObject(i);
jsonObject.getString(ob) //I want return this value *-*-*-*
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Error de conexion",Toast.LENGTH_SHORT).show();
}
});
requestQueue=Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}

Json data array request keeps skipping onResponse

I keep trying to look up and find a solution for my problem.
I am populating a Spinner with json data from a URL, the Json data is nameless and I'm trying to get the data into an ArrayList so I can populate the Spinner.
Whenever I debug I can see that it skips my onResponse() method after making either StringRequest or JSONArrayRequest, Please look at my code and see what am I doing wrong
yearsp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(ySelect)
{
selectedYear = yearsp.getSelectedItem().toString();
URL1 = URL + "/" + selectedYear;
loadSpinnerDataMake();
adapterMake.clear();
adapterMake.addAll(makesName);
}
else
ySelect = true;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
String URL1 = http://carmakemodeldb.com/vehicle/makes/2011 //this is here for you to see the link
public void loadSpinnerDataMake()
{
makesName = new ArrayList<String>();
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(URL1, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int x = 0; x < response.length(); x++) {
JSONObject obMake = response.getJSONObject(x);
String nMake = obMake.getString("make");
makesName.add(nMake);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
requestQueue.add(jsonArrayRequest);
}
here is my json data from URL1
[{"make":"Acura"},{"make":"Aston Martin"},{"make":"Audi"},{"make":"Bentley"},{"make":"BMW"},{"make":"Bugatti"},{"make":"Buick"},{"make":"Cadillac"},{"make":"Chevrolet"},{"make":"Chrysler"}]
Try below function and let me know.
private void parseJSONDataMAke() {
try {
JSONArray dataMakeArray = new JSONArray("[{\"make\":\"Acura\"},{\"make\":\"Aston Martin\"},{\"make\":\"Audi\"},{\"make\":\"Bentley\"},{\"make\":\"BMW\"},{\"make\":\"Bugatti\"},{\"make\":\"Buick\"},{\"make\":\"Cadillac\"},{\"make\":\"Chevrolet\"},{\"make\":\"Chrysler\"}]");
ArrayList<String> stringArrayList = new ArrayList<>();
for (int i = 0; i < dataMakeArray.length(); i++) {
JSONObject jsonObject = dataMakeArray.getJSONObject(i);
stringArrayList.add(jsonObject.getString("make"));
}
//Please set "stringArrayList" array into spinner
} catch (JSONException e) {
e.printStackTrace();
}
}
Your request is async hence you need to notify your spinner adapter when you get response like this.
String URL1 = http://carmakemodeldb.com/vehicle/makes/2011 //this is here for you to see the link
public void loadSpinnerDataMake()
{
makesName = new ArrayList<String>();
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(URL1, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
makesName.clear(); //To avoid duplication of data
for (int x = 0; x < response.length(); x++) {
JSONObject obMake = response.getJSONObject(x);
String nMake = obMake.getString("make");
makesName.add(nMake);
}
adapterMake.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
requestQueue.add(jsonArrayRequest);
}
You are not notifying adapter that's why you didn't get your result.
I fixed my issue thank you everyone who has helped but i figured it out by removing where im adding the arraylist to the adapter and placing it in the OnResponse
public void loadSpinnerDataMake()
{
makesName = new ArrayList<String>();
JsonArrayRequest jsonObjectRequest = new JsonArrayRequest(URL1, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
JSONArray jsonArray = response;
for (int x = 0; x < jsonArray.length(); x++) {
JSONObject obMake = jsonArray.getJSONObject(x);
String nMake = obMake.getString("make");
makesName.add(nMake);
adapterMake.clear();
adapterMake.addAll(makesName);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(jsonObjectRequest);
}

How i can cache the jsonobjectrequest?

My RecyclerView adapter is declared as
adapterlist = new AdapterList(getActivity(),getData());
and the getData() function is defined as
public List<Information> getData(){
final List<Information> data = new ArrayList<>();
showpDialog();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
(Request.Method.GET, urlfood, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
for (int i = 0; i < 10; i++) {
try {
JSONArray items = jsonObject.getJSONObject("response").getJSONArray("groups").getJSONObject(0).getJSONArray("items");
if (jsonObject.getJSONObject("response").getJSONArray("groups").getJSONObject(0).getJSONArray("items").getJSONObject(i).getJSONObject("venue").has("location")) {
if(jsonObject.getJSONObject("response").getJSONArray("groups").getJSONObject(0).getJSONArray("items").getJSONObject(i).getJSONObject("venue").getJSONObject("location").has("address")){
JSONObject location = jsonObject.getJSONObject("response").getJSONArray("groups").getJSONObject(0).getJSONArray("items").getJSONObject(i).getJSONObject("venue").getJSONObject("location");
Address[i] = location.getString("address");}}
Name[i] = items.getJSONObject(i).getJSONObject("venue").getString("name");
String rtg=items.getJSONObject(i).getJSONObject("venue").getString("rating");
Rating[i]=Float.parseFloat(rtg);
Information current = new Information();
current.name = Name[i];
current.address = Address[i];
current.ratings = Rating[i];
data.add(current);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
recyclerView.setAdapter(adapterlist);
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(),
"error:"+error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
}
);
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
return data;
}
These things are defined in the class that extends fragment.
How can I cache the raw response or the parsed response? Please help.
I already checked many answers on StackOverflow but I am not able to understand how I can integrate them in my fragment class.

Categories

Resources