GetterAndSetter returns empty ArrayList - java

I am adding String returned by Callback method from Volley's onRespond method.
I have already initialized GetterAndSetter Method inside OnCreate Method.
this is my code:
onRespond(){
...
AddtoList(CreateURL, new VolleyCallback() {
#Override
public void onSuccess(String result) {
getterAndSetter.addString(result);
}
});
....
}
My GetterAndSetter Class:
public class GetterAndSetter {
ArrayList<String> strings = new ArrayList<>();
public void addString(String string) {
this.strings.add(string);
}
public ArrayList<String> getList(){
return this.strings;
}
}
I tries to get all the strings added inside of this getterandsetter's ArrayList via following code inside my another method :
void LoadImages(MainActivity mainActivity){
...
List<String> details = getterAndSetter.getList();
Log.d("gs", getterAndSetter.getList().toString());
...
}
As seen above, I tried to print log, but it print "[]"(Empty String). I have seen alot of Answers on Stackoverflow, but can't solve my problem.
Update : I am adding more code so that you guys can understand the problem.
My OnCreate Method :
#Override
protected void onCreate(Bundle savedInstanceState) {
...
getterAndSetter = new GetterAndSetter();
LoadImages(this);
}
LoadImages :
private void LoadImages(MainActivity mainActivity) {
StringRequest stringRequest = new StringRequest(URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
mView.dismiss();
Log.d("Respone", "onResponse: " + response);
// Used to Get List of Images URLs
getResponse = ParseJSON(response);
List<String> urlList = getResponse.get(0);
List<String> titles = getResponse.get(1);
List<String> details = getterAndSetter.getList();
Log.d("gs", getterAndSetter.getList().toString());
for (String urls : urlList) {
Log.d("urls", urls);
}
for (String title : titles) {
Log.d("tts", title);
}
for (String dt : details) {
Log.d("dts", dt);
}
}
}, error -> {
Log.d(TAG, "onErrorResponse: Error Occured...");
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
ParseJSON method :
ArrayList<ArrayList<String>> ParseJSON(String URL) {
try {
JSONObject root = new JSONObject(URL);
JSONObject photos = root.getJSONObject("photos");
JSONArray photo = photos.getJSONArray("photo");
ArrayList<String> listURLS = new ArrayList<>();
ArrayList<String> Titles = new ArrayList<>();
ArrayList<ArrayList<String>> result = new ArrayList<>();
for (int i = 0; i < photo.length(); i++) {
JSONObject photosJSONObject = photo.getJSONObject(i);
String FarmID = photosJSONObject.getString("farm");
String ServerID = photosJSONObject.getString("server");
String ID = photosJSONObject.getString("id");
String SecretID = photosJSONObject.getString("secret");
String ImageTitle = photosJSONObject.getString("title");
listURLS.add(i, CreatePhotoURL(FarmID, ServerID, ID, SecretID));
Titles.add(i, ImageTitle);
String CreateURL = "https://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=" + API_Key + "&photo_id=" + ID + "&format=json&nojsoncallback=1";
AddtoList(CreateURL, new VolleyCallback() {
#Override
public void onSuccess(String result) {
getterAndSetter.addString(result);
}
});
result.add(listURLS);
result.add(Titles);
}
return result;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
AddtoList Method :
public void AddtoList(String CreateURL, VolleyCallback volleyCallback) {
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(CreateURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject root;
try {
root = new JSONObject(response);
JSONObject photo = root.getJSONObject("photo");
String username = photo.getJSONObject("owner").getString("username");
String DateTaken = photo.getJSONObject("dates").getString("taken");
String Views = photo.getString("views");
String str = "Date Taken : " + DateTaken + "\n" + "Views : " + Views + "\n" + "User Name : " + username + "\n";
volleyCallback.onSuccess(str);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "onErrorResponse: " + error.toString());
}
});
requestQueue.add(stringRequest);
}
My CallBack
public interface VolleyCallback {
void onSuccess(String result);
}

The problem is that you're trying to print the list BEFORE the callback is being invoked by Volley.
You parse a Json and for each element, you make a new request. After parsing the Json you print the list, it's empty because of the calls you make aren't ended at the moment you print the list.
You need to wait until all the request you start from inside the loop have ended.

Related

Android Studio variables not updating from function call

This is likely a basic Java question. All in same activity, I declare a String[] data, later update it succesfully, but when I attempt to set a textview to the updated data[1] from the calling funtion that updated data[1] - nothing showing. Here is the stripped down code.
public class MyClass extends AppCompatActivity {
String[] data = new String[4];
public void populateGrid() {}
getIndexData(indices);
final TextView test = (TextView) findViewById(R.id.textView0B);
test.post(new Runnable() {
#Override
public void run() {
test.setText(data[1]);
}
});
public void getIndexData(final String[] indices){
//lots of work accomplished, data[1] is updated, Log.d() logs good!
// Tried passing data[] as a parameter from populateGrid(), but that didn't work.
// Tried returning data[] to populateGrid(), also didn't work.
}
}
What is the proper method for accomplishing this task?
As requested, getIndexData()
public void getIndexData(final String indices){
mOkHttpClient = new OkHttpClient();
HttpUrl reqUrl = HttpUrl.parse("http://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=" +
indices +
"&outputsize=compact&apikey=" +
apiKey);
Request request = new Request.Builder().url(reqUrl).build();
mOkHttpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
// Show user error message if not connected to internet, et. al.
runOnUiThread(new Runnable() {
#Override
public void run() {
Context context = getApplicationContext();
CharSequence text = getResources().getString(R.string.Toast_1);
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
});
}
#Override
public void onResponse(Call call, Response response) throws IOException {
int j = 0;
String responseBody = response.body().string();
if (responseBody.contains("\"Error Message\"")) {
data[j] = "No Data";
data[j+1] = "No Data";
data[j+2] = "No Data";
data[j+3] = "No Data";
} else { // Extract data points from json object.
try {
JSONObject baseObject = new JSONObject(responseBody);
JSONObject timeSeriesObj = baseObject.optJSONObject("Time Series (Daily)");
Iterator<String> iterator = timeSeriesObj.keys();
List<Map<String, String>> tickerData = new ArrayList<Map<String, String>>();
while (iterator.hasNext()) {
String key = iterator.next();
if (key != null) {
HashMap<String, String> m = new HashMap<String, String>();
JSONObject finalObj = timeSeriesObj.optJSONObject(key);
m.put("1. open", finalObj.optString("1. open"));
m.put("2. high", finalObj.optString("2. high"));
m.put("3. low", finalObj.optString("3. low"));
m.put("4. close", finalObj.optString("4. close"));
m.put("5. volume", finalObj.optString("5. volume"));
tickerData.add(m);
}
}
int k = 0;
String str = tickerData.get(0).toString();
data[k] = StringUtils.substringBetween(str, "open=", ", ");
//Log.d("data[0]= ", data[0]);
data[k+1] = StringUtils.substringBetween(str, "close=", ", ");
Log.d("data[1]", data[1]); // logs 2431.7700
data[k+2] = "";
data[k+3] = "";
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
}
It would be something like this:
public class MyClass extends AppCompatActivity {
String[] data = new String[4];
public void populateGrid() {
getIndexData(indices);
}
public void getIndexData(final String indices) {
// set up http request
mOkHttpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
// ...
}
#Override
public void onResponse(Call call, Response response) throws IOException {
// process the response, populate data etc.
final TextView test = (TextView) findViewById(R.id.textView0B);
test.post(new Runnable() {
#Override
public void run() {
test.setText(data[1]);
}
});
}
}
}
}

How to access response value outside onResponse method in android

I am working on a android project. I got the response from google api and parsed the json. But i want to return the value outside of onResponse method which seems to be impossible for me now. Below is my code, I have already seen this answer here. But i want this value outside of this async method. Is it possible to access this value.
UPDATE - I have updated my code for more details. This is my full activity class. You can see what i want to achieve. Please help me how i can access value returned by Volley onResponse in method get_time_to_travel, inside method parseJson. This is really killing me now. My first android project and i am stuck here from last two days.
Any help on this would be appreciated.
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private LinearLayoutManager linearLayoutManager;
private CustomAdapter adapter;
private List<UserData> userData;
private LocationManager locationManager;
private LocationListener locationListener;
String origin, mode = "driving";
private String API = "APIKey";
TextView textView;
RequestQueue requestQueue;
RequestQueue requestQueue1;
String url = "https://url/users";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
recyclerView.setHasFixedSize(true);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lng = location.getLongitude();
origin = String.valueOf(lat)+","+String.valueOf(lng);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.INTERNET
}, 10);
}
return;
}
else{
locationManager.requestLocationUpdates("gps", 5000, 0, locationListener);
}
getData();
linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
adapter = new CustomAdapter(this, userData);
recyclerView.setAdapter(adapter);
}
private void getData(){
userData = new ArrayList<>();
requestQueue = Volley.newRequestQueue(this);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
parseJson(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", "ERROR");
}
}
);
requestQueue.add(jsonArrayRequest);
}
private void parseJson(JSONArray response){
try {
for (int i = 0; i < response.length(); i++) {
JSONObject users = response.getJSONObject(i);
String id = ("id: "+users.getString("id"));
String name = ("Name: "+users.getString("name"));
String username = ("Username: "+users.getString("username"));
String email = ("Email: "+users.getString("email"));
String address = parseAddress(users);
String destination = parseCoordinates(users);
String company = parseCompany(users);
String phone = ("Phone: "+users.getString("phone"));
String website = ("Website: "+users.getString("website"));
String eta = get_time_to_travel(origin, destination, API, mode);
UserData udata = new UserData(id, name, username, email, address, phone, website, company,eta);
userData.add(udata);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private String parseAddress(JSONObject users) {
JSONObject completeAdd = null;
String address = null;
try {
completeAdd = users.getJSONObject("address");
String street = completeAdd.getString("street");
String suite = completeAdd.getString("suite");
String city = completeAdd.getString("city");
String zipcode = completeAdd.getString("zipcode");
address = ("Address :" + street + ", " + suite + ", " + city + ", " + zipcode);
} catch (JSONException e) {
e.printStackTrace();
}
return address;
}
private String parseCoordinates(JSONObject users) {
JSONObject completeAdd = null;
String destination = null;
try {
completeAdd = users.getJSONObject("address");
JSONObject coordinates = completeAdd.getJSONObject("geo");
String latitude = coordinates.getString("lat");
String longitude = coordinates.getString("lng");
destination = latitude + "," + longitude;
} catch (JSONException e) {
e.printStackTrace();
}
return destination;
}
private String parseCompany(JSONObject users) {
JSONObject companyDetail = null;
String company = null;
try {
companyDetail = users.getJSONObject("company");
String company_name = companyDetail.getString("name");
String catchPhrase = companyDetail.getString("catchPhrase");
String bs = companyDetail.getString("bs");
company = ("Company: " + company_name + ", " + catchPhrase + ", " + bs);
} catch (JSONException e) {
e.printStackTrace();
}
return company;
}
private String get_time_to_travel(String origin, String destination, String API, String mode){
requestQueue1 = Volley.newRequestQueue(this);
String eta = null;
String google_api = "https://maps.googleapis.com/maps/api/distancematrix/json?origins="+origin+"&destinations="
+destination+"s&mode="+mode+"&language=fr-FR&key="+API;
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, google_api, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
eta = parseGoogleData(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", "ERROR");
}
}
);
requestQueue1.add(jsonObjectRequest);
return eta;
}
private String parseGoogleData(JSONObject response) {
String estimated_time_arrival = null;
try {
JSONArray rows = response.getJSONArray("rows");
JSONObject elements = rows.getJSONObject(0);
JSONArray elementsArr = elements.getJSONArray("elements");
JSONObject durationObj = elementsArr.getJSONObject(0);
JSONObject durationData = durationObj.getJSONObject("duration");
estimated_time_arrival = durationData.getString("text");
} catch (JSONException e) {
e.printStackTrace();
}
return estimated_time_arrival;
}
}
Async task is doing work on other thread. So if you want to access any variable out side that method, you need to wait until the task get completed. Otherwise the variable will be null.
eg: on on response method
#Override
public void onResponse(String response) {
res=response;
anyMethodtopassVar(DataType data);
}
in OnCreate() of activity, remove these 2 lines
adapter = new CustomAdapter(this, userData);
recyclerView.setAdapter(adapter);
in getData() remove this line
userData = new ArrayList<>();
put them in parseJson() as below:
private void parseJson(JSONArray response){
try {
if(userData==null){
userData = new ArrayList<>();
}else{
userData.clear();
}
for (int i = 0; i < response.length(); i++) {
JSONObject users = response.getJSONObject(i);
String id = ("id: "+users.getString("id"));
String name = ("Name: "+users.getString("name"));
String username = ("Username: "+users.getString("username"));
String email = ("Email: "+users.getString("email"));
String address = parseAddress(users);
String destination = parseCoordinates(users);
String company = parseCompany(users);
String phone = ("Phone: "+users.getString("phone"));
String website = ("Website: "+users.getString("website"));
String eta = get_time_to_travel(origin, destination, API, mode);
UserData udata = new UserData(id, name, username, email, address, phone, website, company,eta);
userData.add(udata);
}
if(adapter == null){
adapter = new CustomAdapter(this, userData);
recyclerView.setAdapter(adapter);
}else{
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
this way, when json call finish, parseJson() is called.
and after parsing the array into userData the adapter is initialized or notified.
EDIT:
Well, this is not the best sol. but it's just something from the top of my head
little nasty/dirty. i don't know but i think it will do the job
1- you don't have to reinit the queue every time, so in get_time_to_travel() put that line out of the method:
requestQueue1 = Volley.newRequestQueue(this);
add final int index param to the method and make it void:
private void get_time_to_travel(String origin, String destination, String API, String mode, final int index){...
make onResponse() in the method like this:
public void onResponse(JSONObject response) {
eta = parseGoogleData(response);
userData.get(index).setEta(eta);//add this setter to your data object if not exist.
}
remove return eta;
init udata with empty string as eta for now:
UserData udata = new UserData(id, name, username, email, address, phone, website, company,"");
userData.add(udata);
modify the call to get_time_to_travel() in parseJson() as below:
get_time_to_travel(origin, destination, API, mode, i);
when get_time_to_travel() is called at onResponse() the object will be modified to hold the eta value retrieved from the API
this is nasty, sometimes the adapter might be notified before all calls to google api is completed. so this is just to show you how to make it
Edit2
a workaround for this is
init userData object with label "Loading..." for eta
UserData udata = new UserData(id, name, username, email, address, phone, website, company,"Loading...");
and notify the adapter at end of onResponse() of get_time_to_travel():
public void onResponse(JSONObject response) {
eta = parseGoogleData(response);
userData.get(index).setEta(eta);//add this setter to your data object if not exist.
adapter.notifyDataSetChanged();
}
Do you want to get the result of parseJson inside onResponse?
Change the return type of parseJson to UserData, call return userDate; inside try block and return null; in catch block. This will help you catch the result of parseJson from where you are calling it.
Let me know if I did not understand your question properly.
public void getString(final VolleyCallback callback) {
StringRequest req = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
res=response;
callback.onSuccess(res);
}
}...
}}
public interface VolleyCallback{
void onSuccess(String result);
}
Now inside your mainactivity you can do like this.
public void onResume(){
super.onResume();
getString(new VolleyCallback(){
#Override
public void onSuccess(String res){
... //do something
}
});
}

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.

public List<Model> loadInBackground() method in android does not get data from jSon Array

I am developing an application using android and i'm trying to get the jSon Array displayed in Listfragment using the loadInBackground() method below in my DataListLoader class:
class DataListLoader extends AsyncTaskLoader<List<Model>> {
List<Model> mModels;
String jsonString;
String name = "Daniel Nyerere", phone = "0652400670";
public DataListLoader(Context context) {
super(context);
loadInBackground();
}
public List<Model> loadInBackground() {
// You should perform the heavy task of getting data from
// Internet or database or other source
// Here, we are generating some Sample data
// Create corresponding array of entries and load with data.
final List<Model> entries = new ArrayList<Model>(50);
StringRequest stringRequest = new StringRequest(
Request.Method.GET, "http://10.0.2.2/webapp/json_get_data.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.trim().contains("server_response")) {
jsonString = response.toString();
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
int count = 0;
while (count < jsonArray.length()) {
JSONObject jo = jsonArray.getJSONObject(count);
name = jo.getString("name");
phone = jo.getString("user_phone");
entries.add(new Model(name, phone));
System.out.println("DATA FROM JSON ARRAY: " + name + " " + phone);
count++;
return;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = VolleySingleton.getInstance().getRequestQueue();
requestQueue.add(stringRequest);
entries.add(new Model(name, phone));
return entries;
}
But when i try to run it the data from System.out.println("DATA ENTRIES: "+entries); comes as null list ,so no data get displayed in the fragment activity . Anyone who can help me to fix it so that i get data from json because it consume me a lot of time
//You can call it in UI thread
final List<Model> entries = new ArrayList<Model>(5);
StringRequest stringRequest = new StringRequest(
Request.Method.GET, "http://10.0.2.2/webapp/json_get_data.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//you need to update the `ListView` content here
//If you need you can create new thread here too e.g. using AsyncTask
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = VolleySingleton.getInstance().getRequestQueue();
requestQueue.add(stringRequest);

How Do I instantly refresh a component of a recyclerview in android studio?

I have a button and when the button is clicked, I would like it to automatically update the text, the catch is that the text is coming from a server and I am parsing it via JSON. My question is how can I automatically update the text when the button is clicked without a complete refresh?
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, URL_ANSWER, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
listblogs = parseJSONResponseQuestion(response);
mAdapterQuestion.setBloglist(listblogs);
System.out.println(response);
System.out.println("it worked!!!");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error);
}
});
mRequestQueue.add(request);
}
private ArrayList<Blogs> parseJSONResponseQuestion(JSONArray response) {
if (!response.equals("")) {
ArrayList<Blogs> blogsArrayList = new ArrayList<>();
try {
StringBuilder data = new StringBuilder();
for (int i = 0; i < response.length(); i++) {
JSONObject currentQuestions = response.getJSONObject(i);
String text = currentQuestions.getString("text");
String questionId = currentQuestions.getString("questionId");
String votes = currentQuestions.getString("votes");
String Answerid = currentQuestions.getString("id");
String selectedId = currentQuestions.getString("selected");
System.out.println(response.length() + "length");
data.append(text + Answerid + "\n");
System.out.println(data);
Blogs blogs = new Blogs();
blogs.setMtext(text);
blogs.setVotes(votes);
blogs.setId(Answerid);
blogs.setSelected(selectedId);
System.out.print(Answerid);
listblogs.add(blogs);
}
System.out.println(data.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
return listblogs;
}
The only thing I have tried it recalling the jsonarray in my listener
public void OnDown(View view) {
CharSequence IdDownVote = ((TextView) ((RelativeLayout) view.getParent()).getChildAt(1)).getText();
final RequestQueue mrequestQueue = VolleySingleton.getInstance().getRequestQueue();
final String PUT_VOTE_DOWN = "someURL";
StringRequest PostVoteUp = new StringRequest(Request.Method.PUT, PUT_VOTE_DOWN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println(response + "reponse");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
System.out.println("************Answer" + error + "error");
}
});
mrequestQueue.add(PostVoteUp);
System.out.println("VOTED DOWN");
}
public void ClickCardAnswer(View view) {
System.out.println("YOU CLICKED THE CARD");
}
}
Your question is a little ambiguous, but I'll try to answer the two possible problems you might have:
You have updated the item in the adapter but it won't display the new content: use notifyItemChanged(int position) of the adapter class
You want to update the item in the adapter. Apart from the setBloglist() of the adapter class you need to make a method to update a certain item in the dataset (either by position in list or looking it up via id - I usually use the ID version). After update, see point 1 above.

Categories