I would like to get String value from onResponse function in OkHttp3 using Android Studio, which is
final String title_name = jsonarray_news_extract_Data(jsonStr, index)
in below codes.
I've tried insert String variable "a" in argument, but it said
Variable is accessed within inner class. Needs to be declared final
so that I declared as final then it said
Cannot Assign a Value to Final Variable
I tried to put
a = title_name;
after removed Handler method but still not work.
If you have any idea please help me out.
Thank you
public void news_From_API_Title(String url_news, final int index, final TextView textView, String a){
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url_news)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(#NotNull Call call, #NotNull IOException e) {}
#Override
public void onResponse(#NotNull Call call, #NotNull Response response) throws IOException {
final String jsonStr = Objects.requireNonNull(response.body()).string();
final String title_name = jsonarray_news_extract_Data(jsonStr, index);
Handler mainHandler = new Handler(Looper.getMainLooper());
mainHandler.post(new Runnable() {
#Override
public void run() {
a = title_name;
}
});
}
});
}
private String jsonarray_news_extract_Data(String jsonString_News, int index){
try {
JSONObject jsonObject = new JSONObject(jsonString_News);
JSONArray jsonArray = jsonObject.getJSONArray("Data");
return jsonArray.getJSONObject(index).getString("title");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
You can use a custom interface like this:
interface ApiCallback{
void onOkHttpResponse(String data);
void onOkHttpFailure(Exception exception);
}
Then you pass not a String but an instance of ApiCallback into the method which is actually doing the call:
public void news_From_API_Title(String url_news, final int index, final TextView textView, ApiCallback callback){
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url_news)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(#NotNull Call call, #NotNull IOException e) {
callback.onOkHttpFailure(e);
}
#Override
public void onResponse(#NotNull Call call, #NotNull Response response) throws IOException {
final String jsonStr = Objects.requireNonNull(response.body()).string();
final String title_name = jsonarray_news_extract_Data(jsonStr, index);
Handler mainHandler = new Handler(Looper.getMainLooper());
mainHandler.post(new Runnable() {
#Override
public void run() {
callback.onOkHttpResponse(title_name);
}
});
}
});
}
Now you can use an implementation of ApiCallback as follows:
String url_news = "https://some.web.address/news";
int index = 7;
TextView textView;
news_From_API_Title(url_news, index, textView, new apiCallback(){
#Override
public void onOkHttpResponse(String data){
// do something with data here
Log.d("TEST", "data = " + data);
}
#Override
onOkHttpFailure(Exception exception){
// exception handling
}
});
Please note that it may be better from an architecture point of view if you don't pass the TextView as parameter into the method but instead set the text in onOkHttpResponse():
// TextView will be initialized before calling news_From_API_Title()
// either make TextView a field (then use "private")
// or declare it locally (then use "final")
private TextView textView;
// ... other code ...
String url_news = "https://some.web.address/news";
int index = 7;
// method will only take parameters which are not related to the UI
// since it's desirable to avoid tight coupling of networking and UI components
news_From_API_Title(url_news, index, new apiCallback(){
#Override
public void onOkHttpResponse(String data){
// do something with data here
// e.g. show data in TextView
textView.setText(data);
}
#Override
onOkHttpFailure(Exception exception){
// exception handling
}
});
Related
(note: I'm using the Android Volley library for the network connection)
public class PostureActivity extends AppCompatActivity {
private static final String LOG_TAG = PostureActivity.class.getName();
private static final String EMB_URL = "https://api.thingspeak.com/channels/xxxxxxx/feed/last.json?round=1";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
connect(); // call at the start
final Handler handler = new Handler();
Runnable scrape = new Runnable() {
#Override
public void run() {
connect(); // call every x ms
handler.postDelayed(this, 3000);
}
};
handler.postDelayed(scrape, 3000);
}
private void connect() {
MySingleton.getInstance(this.getApplicationContext()).getRequestQueue();
JsonObjectRequest collectData = new JsonObjectRequest(
Request.Method.GET, // HTTP method
EMB_URL, // URL string that returns the desired JSON // TODO: change appropriate url
null, // optional JSON to send as request
response -> { // retrieved data
try {
JSONObject myResponse = new JSONObject(response.toString());
// TODO: cast to double to show the average
String ultrasonic = myResponse.getString("field1");
String flex1 = myResponse.getString("field2");
String flex2 = myResponse.getString("field3");
TextView neck = findViewById(R.id.neck_number);
TextView back = findViewById(R.id.back_number);
TextView butt = findViewById(R.id.butt_number);
neck.setText(ultrasonic);
back.setText(flex1);
butt.setText(flex2);
} catch (JSONException e) { // what if response is null?
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Response values are empty.", Toast.LENGTH_LONG).show();
finishAffinity();
finishAndRemoveTask();
}
},
error -> { // retrieved error/failure
error.printStackTrace();
Toast.makeText(getApplicationContext(), "Could not connect to website.", Toast.LENGTH_LONG).show();
finishAffinity();
finishAndRemoveTask();
}
);
MySingleton.getInstance(this).addToRequestQueue(collectData);
}
As you can see, connect() essentially retrieves, parses, and displays the data, and I run it via a handler. How do split the code so that this entire function doesn't simply populate the UI thread? I'm not very familiar with handler/loopers or java threads outside of async tasks, so I was hoping that I could be pointed in the right direction as to how to optimize the function better.
Alright - Before you say this is a duplicate, I've looked over every stack overflow article I can find, and none of them work and/or answer the question properly/simply. All I need is to repeat a function with a volley request inside of it every x-seconds.
Basically, I have a fairly simple Volley request inside a function, which works absolutely perfectly on one call.
Volley function:
private void SetBusPositions() {
TextView textE = (TextView) findViewById(R.id.FirstInfo);
RequestQueue Queue = ServerRequestsQueue.getInstance(context.getApplicationContext()).getRequestQueue();
int SendMethod = Request.Method.GET;
String ServerURL = "my url";
JsonArrayRequest JOR = new JsonArrayRequest(SendMethod, ServerURL, null, new Listener<JSONArray>() {
#Override
public void onResponse(JSONArray resp) {
textE.setText(resp.toString());
System.out.println("Response is: " + resp.toString());
//for each object in JSON Array
for (int i = 0; i < resp.length(); i++) {
}
}
}, new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
//process
}
});
Queue.add(JOR);
}
I just want to call this function periodically, to receive data from the server and update my bus-position data. There has to be a fairly simple way to do this? I know I must be missing something, but none of the other answers seem to help.
Also, as I'm using Google maps, my class is already extending FragmentActivity. I've seen methods that extend Runnable to get this working -- but my Java is a bit rusty here. I've been doing too much JS.
private final class RepeatedOperation extends AsyncTask<Map, Void, String> {
#Override
protected String doInBackground(Map... params) {
SetBusPosition(params[0]);
}
#Override
protected void onPostExecute(String result) {
}
}
private void callAsynchronousTask() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
RepeatedOperation performBackgroundTask = new RepeatedOperation();
// RepeatedOperation this class is the class that extends AsyncTask
performBackgroundTask.execute(map);
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 50000); //execute in every 50000 ms
}
Try this out and add this in the same scope as SetBusPosition()
I want to display this textview "txtCalculate" which comes from the class CustomerMapActivity which is displayed in the activity_map_customer layout in another layout which is activity_bon_de_commande, of the class BonDeCommande.
the problem is I don't know how to do it
I'm new to java programming
thank you
public void readValues(){
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
Query lastQuery = ref.child("ride_info").orderByKey().limitToLast(1);
lastQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
double value0_float = ds.child("pickup").child("lat").getValue(Double.class);
double value1_float = ds.child("pickup").child("lng").getValue(Double.class);
double value2_float = ds.child("destination").child("lat").getValue(Double.class);
double value3_float = ds.child("destination").child("lng").getValue(Double.class);
String pickupLat = String.valueOf(value0_float);
String pickupLng = String.valueOf(value1_float);
String destiLat = String.valueOf(value2_float);
String destiLng = String.valueOf(value3_float);
String requestUrl=null;
try {
requestUrl = "https://maps.googleapis.com/maps/api/directions/json?"+
"mode=driving&"
+"transit_routing_preference=less_driving&"
+"origin="+pickupLat+","+pickupLng+"&"
+"destination="+destiLat+","+destiLng+"&"
+"key="+getResources().getString(R.string.google_maps_key);
Log.e("LINK",requestUrl);
mService.getPath(requestUrl).enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
try {
JSONObject jsonObject = new JSONObject(response.body().toString());
JSONArray routes = jsonObject.getJSONArray("routes");
JSONObject object = routes.getJSONObject(0);
JSONArray legs = object.getJSONArray("legs");
JSONObject legsObject = legs.getJSONObject(0);
//Get distance
JSONObject distance = legsObject.getJSONObject("distance");
String distance_text = distance.getString("text");
//use regex to extract double from string
//This regex will remove all text not digit
Double distance_value= Double.parseDouble(distance_text.replaceAll("[^0-9\\\\.]+",""));
//Get Time
JSONObject time = legsObject.getJSONObject("duration");
String time_text = time.getString("text");
Integer time_value = Integer.parseInt(time_text.replaceAll("\\D+",""));
String final_calculate = String.format("%.2f €",
TypeObject.getPrice(distance_value,time_value));
HERE -----> txtCalculate.setText(final_calculate);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
mCurrentRide.cancelRide();
endRide();
}
});
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
mCurrentRide.cancelRide();
endRide();
}
});
}
screenshot of my screen
You need to Create an Interface with an update method, declare in your Activity and after, pass as parameter to your handler object that gets the data.
Don't forget If you're getting the data in a different Thread, you need to update your views always in an UI Thread or in the Main Thread.
Here Follow some example code:
Your Activity or Fragment
public class MainActivity extends AppCompatActivity
implements UpdateViewCallback { // implement the interface here
private TextView textView = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
textView = findViewById(R.id.textView);
// Pass the interface in your Object that makes the async work
final AsyncWork asyncWork = new AsyncWork(this);
// Running
Thread thread = new Thread(asyncWork);
thread.start();
}
/**
* UpdateViewCallback
* #param result
*/
#Override
public void updateView(final String result) {
// Always update View on MainThread or an UI Thread, or else issues will start to happening
this.runOnUiThread(new Runnable() {
public void run() {
// Check if View is null since you're updating in a thread async
if (textView != null) {
textView.setText(result);
}
}
});
}
}
Your Interface:
public interface UpdateViewCallback {
void updateView(String result);
}
Your Object to handle the Async Work:
public class AsyncWork implements Runnable {
private UpdateViewCallback updateViewCallback;
public AsyncWork(UpdateViewCallback updateViewCallback) {
this.updateViewCallback = updateViewCallback;
}
/**
* Async Work here
*/
#Override
public void run() {
// Do some Work and after update using the interface you passed in the constructor
updateViewCallback.updateView("This is a test");
}
}
EDITED:
The real purpose of that is to have one activity and on class who fetch data and render it to the activity.
The problem is I have dropdown menu. When I clicked on an item of the menu it change my url but it does not load or fetch my data to the activity but when i clicked again it works but with the paramaters selected just before and if I clicked again it still works but still with the previous elements selected.
My "teacher" said I have to call build into my callback method.
But it doesen't work at all. And I still didn't find any solution :/.
As you recommended I changed everything for non-static method
I thought why not saving an history of the dropdown, compare the current value with the saved value and if it's diffrent it means it was changed so reload the app to make new fetch and displyed new data.
But I got :
Here my all code
PhotosActivity
public class PhotosActivity extends AppCompatActivity {
// Local variable
private OkHttpClient httpClient;
private ImageButton home_btn;
private ImageButton favorites_btn;
private ImageButton search_btn;
private ImageButton profil_btn;
// Constante variable
private static final String TAG = "PhotoActivity";
private static final String clientId = "bb0c749c6403fd2";
// Private shared variable
private static List<Photo> mPhotos;
private static JSONArray mItems;
private static String mAccessToken;
private static String userID;
static Activity activity;
// Shared variable
private static String selectedItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photos);
this.home_btn = findViewById(R.id.home_button);
this.favorites_btn = findViewById(R.id.favorites_button);
this.search_btn = findViewById(R.id.search_button);
this.profil_btn = findViewById(R.id.profil_button);
final HttpHandler httpHandler = new HttpHandler();
httpHandler.fetchData();
build();
activity = this;
Spinner spinner=(Spinner)findViewById(R.id.spinner);
String[] filters=getResources().getStringArray(R.array.filters);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,R.layout.spinner,R.id.text, filters);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
selectedItem = parent.getItemAtPosition(position).toString();
// httpHandler.fetchData();
// build();
}
public void onNothingSelected(AdapterView<?> parent)
{
Log.d("TAG", "Error");
}
});
home_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next_activity = new Intent(getApplicationContext(), PhotosActivity.class);
finish();
startActivity(next_activity);
}
});
favorites_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next_activity = new Intent(getApplicationContext(), FavoriteActivity.class);
finish();
startActivity(next_activity);
}
});
search_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next_activity = new Intent(getApplicationContext(), SearchActivity.class);
finish();
startActivity(next_activity);
}
});
profil_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent next_activity = new Intent(getApplicationContext(), ProfileActivity.class);
finish();
startActivity(next_activity);
}
});
}
public void Filters() {
String hSection;
String hSort;
String hShowV;
hSection = HttpHandler.section ;
hSort = HttpHandler.sort;
hShowV = HttpHandler.showV;
Intent next_activity = new Intent(getApplicationContext(), FavoriteActivity.class);
if(selectedItem != null) {
if (selectedItem.equals("Most Viral")) {
HttpHandler.sort = "viral/";
HttpHandler.section = "hot/";
if ( (!HttpHandler.sort.equals(hSort)) || (!HttpHandler.section.equals(hSection))) {
Log.d("TAG", "most: "+HttpHandler.section);
Log.d("TAG", "H most: "+hSection);
// activity.recreate();
// onRestart();
finish();
startActivity(next_activity);
}
} else if (selectedItem.equals("Newest")) {
HttpHandler.section = "top/";
HttpHandler.sort = "time/";
if ( (!HttpHandler.sort.equals(hSort)) || (!HttpHandler.section.equals(hSection))) {
Log.d("TAG", "new: "+HttpHandler.section);
Log.d("TAG", "H new: "+hSection);
finish();
startActivity(next_activity);
// activity.recreate();
// onRestart();
}
} else if (selectedItem.equals("Rising")) {
HttpHandler.section = "user/";
HttpHandler.sort = "rising/";
HttpHandler.showV = "?showViral=false";
if ( (!HttpHandler.sort.equals(hSort)) || (!HttpHandler.section.equals(hSection))) {
Log.d("TAG", "rising: "+HttpHandler.section);
Log.d("TAG", "H rising: "+hSection);
// onRestart();
// activity.recreate();
finish();
startActivity(next_activity);
}
} else {
Log.d(TAG, "Might be a problem");
}
} else {
activity.recreate();
}
}
public void build () {
try {
for(int i = 0; i < mItems.length(); i++) {
JSONObject item = mItems.getJSONObject(i);
Photo photo = new Photo();
if(item.getBoolean("is_album")) {
photo.id = item.getString("cover");
} else {
photo.id = item.getString("id");
}
photo.title = item.getString("title");
mPhotos.add(photo);
runOnUiThread(new Runnable() {
#Override
public void run() {
render(mPhotos);
}
});
}
} catch (Exception e) {
Log.e("JSONerr" , "Something went wrong.");
}
}
private static class PhotoVH extends RecyclerView.ViewHolder {
ImageView photo;
TextView title;
public PhotoVH(View itemView) {
super(itemView);
}
}
private void render(final List<Photo> photos) {
RecyclerView rv = (RecyclerView)findViewById(R.id.rv_of_photos);
rv.setLayoutManager(new LinearLayoutManager(this));
RecyclerView.Adapter<PhotoVH> adapter = new RecyclerView.Adapter<PhotoVH>() {
#NonNull
#Override
public PhotoVH onCreateViewHolder(ViewGroup parent, int viewType) {
PhotoVH vh = new PhotoVH(getLayoutInflater().inflate(R.layout.item, null));
vh.photo = (ImageView) vh.itemView.findViewById(R.id.photo);
vh.title = (TextView) vh.itemView.findViewById(R.id.title);
return vh;
}
#Override
public void onBindViewHolder(PhotoVH holder, int position) {
Picasso.with(PhotosActivity.this).load("https://i.imgur.com/" +
photos.get(position).id + ".jpg").into(holder.photo);
holder.title.setText(photos.get(position).title);
}
#Override
public int getItemCount() {
return photos.size();
}
};
rv.setAdapter(adapter);
}
public static void getUserID(String UserID) {
Log.d("TAG", UserID);
userID = UserID;
}
public void callBackPhoto( List<Photo> photos, JSONArray items)
{
mPhotos = photos;
mItems = items;
// build();
}
}
HttpHandler
public class HttpHandler {
private static final String TAG = "HttpHandler";
private static String clientId = "bb0c749c6403fd2";
private static OkHttpClient httpClient;
private static String mAccessToken;
// URL BUILDER VARIABLES
public static String section = "hot/";
public static String sort = "viral/";
public static String page;
public static String showV;
public static String mUrl;
public void fetchData() {
httpClient = new OkHttpClient.Builder().build();
photosActivity.Filters();
mUrl = "https://api.imgur.com/3/gallery/" + section + sort;
// Log.d("TAG", "Sort: " + sort + ": URl is" + mUrl);
Request request = new Request.Builder()
.url(mUrl + "0.json" + showV)
.addHeader("Authorization", "Client-ID " + clientId)
.header("User-Agent", "epicture")
.build();
httpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Log.e(TAG, "An error has occurred " + e);
}
#Override
public void onResponse(Call call, Response response) throws IOException {
try {
JSONObject data = new JSONObject(response.body().string());
JSONArray items = data.getJSONArray("data");
final List<Photo> photos = new ArrayList<Photo>();
photosActivity.callBackPhoto(photos, items);
} catch (Exception e) {
Log.e("JSONerr", "Something went wrong.");
}
}
});
}
public static void getLoginData(String accessToken) {
mAccessToken = accessToken;
}
}
It doesn't look like making sense to declare callBackPhoto as a static method. If you have put static keyword accidentally in its declaration, simply remove it to solve your problem i.e. replace
public static void callBackPhoto( List<Photo> photos, JSONArray items)
with
public void callBackPhoto( List<Photo> photos, JSONArray items)
Note that there is no way to call a non-static method from a static one directly (i.e. without calling it on an object/instance). Thus, if for any reason, you can't remove static keyword from the declaration of callBackPhoto, you are left with only two options:
Declare build too as static
Call build on an object/instance e.g. new PhotosActivity().build()
Though any of these two options will solve your problem, I don't think this is how you intend to design your class.
In java, a static method belongs to EVERY object of the class that defines it. Therefore, you can call it from the parent class without creating an object like so:
ParentClass.myMethod;
However, this is not the case the case with instance (non-static) methods. To call this type of method, you need to define it in a class, create an object from that class, and then call it from that object, like this:
//inside ParentClass definition
public void myMethod(){bla bla;}
//In some other class
ParentClass obj = new ParentClass;
obj.myMethod;
Suppose you have code calling a static member of a class without creating an instance of that class. If that method contained a non-static method, there would be no object in memory to call it on. This is why it isn't possible.
Static
The static methods are alive all the time. They live from the class is loaded. They don't need objects to live. I think of them as not really belonging to the class, but the class is just a nice way to organize those methods (the same for variables). The methods could be put in any other class definition and it would still work. But organizing them in classes where they will be used make it easy to prevent access from other parts of the program, like other objects or other static methods. They are called class methods or class variables.
Instance
The non-static "stuff" does not live unless there is an object. That's why you cannot call below methodOne or methodTwo from the static methods. You have to create an object first. They are called instance methods or instance variables, because you need an instance of an object to call them.
Error
error: non-static method <methodname> cannot be referenced from a static context basically means "There's no object"
Example
public class StackOverflowTest {
public static void main(String[] args) { // this is just another static method
// methodOne(); // error. There's no object
StackOverflowTest test = new StackOverflowTest();
test.methodOne(); // method called on object.
}
// methods live outside objects
static void staticMethodOne() {
System.out.println("staticMethodOne");
staticMethodTwo(); // no object required.
}
static void staticMethodTwo() {
System.out.println("staticMethodTwo");
// methodTwo(); // error. There's no object
}
// methods that only live inside objects
void methodOne() { // method can only be invoked if there's an object.
System.out.println("methodOne");
methodTwo(); // no problem. Already inside the object.
}
void methodTwo() {
System.out.println("methodTwo");
staticMethodTwo(); // no problem. Objects can access static methods.
}
}
Your case
So you either have to create a PhotosActivity object inside your build(), or you have to make callBackPhoto a static method. I can't see what your render does, but it's the same principle.
I am getting json from Websockets and showing in recyler view. How do i update the list in real time when getting data from websockets?
My WebSocket Class
public final class EchoWebSocketListener extends WebSocketListener {
private static final int NORMAL_CLOSURE_STATUS = 1000;
private static final String TAG = "DashBoardScreen.this";
#Override
public void onOpen(WebSocket webSocket, Response response) {
super.onOpen(webSocket, response);
initially when connection is established i send some text to server
webSocket.send(builder.toString());
}
#Override
public void onMessage(WebSocket webSocket, String text) {
super.onMessage(webSocket, text);
in return server sends me data
output(text);
}
#Override
public void onMessage(WebSocket webSocket, ByteString bytes) {
super.onMessage(webSocket, bytes);
}
#Override
public void onClosing(WebSocket webSocket, int code, String reason) {
super.onClosing(webSocket, code, reason);
Log.d(TAG, "onClosing: ");
}
#Override
public void onClosed(WebSocket webSocket, int code, String reason) {
super.onClosed(webSocket, code, reason);
Log.d(TAG, "onClosed: ");
}
#Override
public void onFailure(WebSocket webSocket, Throwable t,Response response) {
super.onFailure(webSocket, t, response);
Log.d(TAG, "onFailure: ");
}
}
Output Method
private void output(final String text) {
runOnUiThread(new Runnable() {
#Override
public void run() {
*parsing json inside recyler view*
try {
JSONObject object = new JSONObject(text);
StringBuilder builder = new StringBuilder();
if (object.getBoolean("status")) {
JSONArray jsonArray = object.getJSONArray("events");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject values = jsonArray.getJSONObject(i);
final EventsDataModel dataModel = new EventsDataModel(
values.getString("service_Room_Number"),
values.getString("service_Name"),
values.getString("service_AssignedTo"),
values.getString("service_ID")
);
eventsDataModels.add(dataModel);
adapter = new EventListAdapter(eventsDataModels, context);
eventRecyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
how exactly notifyDataSetChanged() works?
}
} else Toast.makeText(context, "No Events", Toast.LENGTH_SHORT).show();
System.out.println(builder.append(object.getString("status")));
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
Whenever your dataModel has the new data
eventsDataModels.add(dataModel);
adapter = new EventListAdapter(eventsDataModels, context);
eventRecyclerView.setAdapter(adapter);
If you perform the above operations and performing adapter.notifyDataSetChanged();
Will notify the adapter the new data has arrived and have to update the RecyclerView with new dataModel.