I want to connect my RecyclerView to my API response.. as too many depreciated code I had to make the two separately but I still can't figure out how to put them together I am putting the code if anyone would like to see it or having a problem with RecyclerView.. what I really want is giving me info or a thread or even a tutorial or how to combine both with the latest method as most of the codes online have problems, depreciated not detailed enough to show you the exact way to learn from it
code to connect to the database using httpUrlConnect
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle saveInstanceState) {
super.onCreate(saveInstanceState);
setContentView(R.layout.activity_main);
new GetMethodDemo().execute("http://YourIPAddress/android/search.php");
}
public class GetMethodDemo extends AsyncTask<String, Void, String> {
String server_response;
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
server_response = readStream(urlConnection.getInputStream());
Log.v("CatalogClient", server_response);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("Response", "" + server_response);
}
}
// Converting InputStream to String
private String readStream(InputStream in) {
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return response.toString();
}
code for RecyclerView
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
List<ModelClass> modelClassList = new ArrayList<>();
modelClassList.add(new ModelClass(R.drawable.ic_launcher_background,"1","day use","cairo","ain shokhna","take a day use from cairo to ain sokhna asdoibasidoasbd asodasidou asidua sdiuas dgpasidu agspiudasdiuasidgasiodgasiudgasoidugasdoiuasgdoiusagdasoiudgsaiudgasiodgasidgasiudgasiudgasoiudgasoidgasoiudasgdoiausdgaouisgduiasg uisag aisoug asiug aosiugdasiudgsauio gasuio gsaiodgasiud gasiug aosi","11/4/2019","20/4/2019","1000EGP"));
modelClassList.add(new ModelClass(R.drawable.ic_launcher_background,"2","day use","cairo","ain shokhna","take a day use from cairo to ain sokhna","11/4/2019","20/4/2019","1000EGP"));
modelClassList.add(new ModelClass(R.drawable.ic_launcher_background,"3","day use","cairo","ain shokhna","take a day use from cairo to ain sokhna","11/4/2019","20/4/2019","1000EGP"));
modelClassList.add(new ModelClass(R.drawable.ic_launcher_background,"4","day use","cairo","ain shokhna","take a day use from cairo to ain sokhna","11/4/2019","20/4/2019","1000EGP"));
modelClassList.add(new ModelClass(R.drawable.ic_launcher_background,"5","day use","cairo","ain shokhna","take a day use from cairo to ain sokhna","11/4/2019","20/4/2019","1000EGP"));
modelClassList.add(new ModelClass(R.drawable.ic_launcher_background,"6","day use","cairo","ain shokhna","take a day use from cairo to ain sokhna","11/4/2019","20/4/2019","1000EGP"));
modelClassList.add(new ModelClass(R.drawable.ic_launcher_background,"7","day use","cairo","ain shokhna","take a day use from cairo to ain sokhna","11/4/2019","20/4/2019","1000EGP"));
modelClassList.add(new ModelClass(R.drawable.ic_launcher_background,"8","day use","cairo","ain shokhna","take a day use from cairo to ain sokhna","11/4/2019","20/4/2019","1000EGP"));
modelClassList.add(new ModelClass(R.drawable.ic_launcher_background,"9","day use","cairo","ain shokhna","take a day use from cairo to ain sokhna","11/4/2019","20/4/2019","1000EGP"));
modelClassList.add(new ModelClass(R.drawable.ic_launcher_background,"10","day use","cairo","ain shokhna","take a day use from cairo to ain sokhna","11/4/2019","20/4/2019","1000EGP"));
modelClassList.add(new ModelClass(R.drawable.ic_launcher_background,"11","day use","cairo","ain shokhna","take a day use from cairo to ain sokhna","11/4/2019","20/4/2019","1000EGP"));
Adapter adapter = new Adapter(modelClassList);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
code for adapter
public class Adapter extends RecyclerView.Adapter<Adapter.Viewholder> {
private List<ModelClass> modelClassList;
public Adapter(List<ModelClass> modelClassList) {
this.modelClassList = modelClassList;
}
#NonNull
#Override
public Viewholder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_layout,viewGroup,false);
return new Viewholder(view);
}
#Override
public void onBindViewHolder(#NonNull Viewholder viewholder, int position) {
int resource = modelClassList.get(position).getImageResource();
String search_id = modelClassList.get(position).getSearch_id();
String activity = modelClassList.get(position).getActivity();
String origin = modelClassList.get(position).getOrigin();
String destination = modelClassList.get(position).getDestination();
String description = modelClassList.get(position).getDescription();
String date_from = modelClassList.get(position).getDate_from();
String date_to = modelClassList.get(position).getDate_to();
String price = modelClassList.get(position).getPrice();
viewholder.setData( resource, search_id,activity,origin,destination,description,date_from,date_to,price);
}
#Override
public int getItemCount() {
return modelClassList.size();
}
public class Viewholder extends RecyclerView.ViewHolder{
private ImageView imageView;
private TextView search;
private TextView mactivity;
private TextView morigin;
private TextView mdestination;
private TextView mdescription;
private TextView mdate_from;
private TextView mdate_to;
private TextView mprice;
public Viewholder(#NonNull View itemView) {
super(itemView);
imageView =itemView.findViewById(R.id.image_view);
search= itemView.findViewById(R.id.search_id);
mactivity= itemView.findViewById(R.id.activity);
morigin= itemView.findViewById(R.id.origin);
mdestination= itemView.findViewById(R.id.destination);
mdescription= itemView.findViewById(R.id.description);
mdate_from= itemView.findViewById(R.id.date_from);
mdate_to= itemView.findViewById(R.id.date_to);
mprice =itemView.findViewById(R.id.price);
}
private void setData(int resource, String search_id,String activity,String origin,String destination,String description,String date_from,String date_to,String price){
imageView.setImageResource(resource);
search.setText(search_id);
mactivity.setText(activity);
morigin.setText(origin);
mdestination.setText(destination);
mdescription.setText(description);
mdate_from.setText(date_from);
mdate_to.setText(date_to);
mprice.setText(price);
}
}
}
volley code doesn't work
public class redirectFragment extends Fragment {
private static final String URL_PRODUCTS = "http://ipAddress/android/search.php";
private RecyclerView recyclerView;
private List<ModelClass> modelClassList;
public redirectFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_redirect, container, false);
recyclerView = v.findViewById(R.id.recyclerView);
LinearLayoutManager layoutManager = new LinearLayoutManager(this.getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
List<ModelClass> modelClassList = new ArrayList<>();
loadModelClass();
Adapter adapter = new Adapter(modelClassList);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
return v ;
}
private void loadModelClass() {
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_PRODUCTS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONArray array = new JSONArray(response);
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting product object from json array
JSONObject product = array.getJSONObject(i);
//adding the product to product list
modelClassList.add(new ModelClass(
product.getInt("activity_img"),
product.getString("search_id"),
product.getString("activity"),
product.getString("description"),
product.getString("origin"),
product.getString("destination"),
product.getString("date_from"),
product.getString("date_to"),
product.getString("price")
));
}
//creating adapter object and setting it to RecyclerView
Adapter adapter = new Adapter(modelClassList);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this.getActivity()).add(stringRequest);
}
}
code for retrofit and still doesnt work
private Adapter adapter;
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*Create handle for the RetrofitInstance interface*/
RetrofitInstance.GetEmployeeDataService service = RetrofitInstance.getRetrofitInstance().create(RetrofitInstance.GetEmployeeDataService.class);
/*Call the method with parameter in the interface to get the employee data*/
Call<SearchList> call = service.getSearchData(100);
/*Log the URL called*/
Log.wtf("URL Called", call.request().url() + "");
call.enqueue(new Callback<SearchList>() {
#Override
public void onResponse(Call<SearchList> call, Response<SearchList> response) {
generateEmployeeList(response.body().getSearchArrayList());
}
#Override
public void onFailure(Call<SearchList> call, Throwable t) {
Toast.makeText(MainActivity.this, "Something went wrong...Please try later!", Toast.LENGTH_SHORT).show();
}
});
}
/*Method to generate List of employees using RecyclerView with custom adapter*/
private void generateEmployeeList(ArrayList<search> modelClassList) {
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
adapter = new Adapter(modelClassList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(MainActivity.this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
I tried both codes and they work perfectly for the RecyclerView and for HTTPURLCONNECTION .. I hope someone helps me with the issue of combining the two of them
I tried volley but results in the comeback as null so someone suggested that I have to work with HTTPURLCONNECTION and since then I don't know how to combine the two together. I will add the volley I used to work with
Try this #diaa,
public class redirectFragment extends Fragment {
private static final String URL_PRODUCTS =
"http://IPADDRESS/android/search.php";
private RecyclerView recyclerView;
List<ModelClass> modelClassList;
private RecyclerView.Adapter adapter; //new line
public redirectFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_redirect, container, false);
//getting the recyclerview from xml
recyclerView = v.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getContext()));
//initializing the productlist
List<ModelClass> modelClassList = new ArrayList<>();
adapter = new Adapter(modelClassList); //new line
recyclerView.setAdapter(adapter); //new line
//this method will fetch and parse json
//to display it in recyclerview
loadModelClass();
return v;
}
private void loadModelClass() {
StringRequest stringRequest = new StringRequest(Request.Method.GET,
URL_PRODUCTS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONArray array = new JSONArray(response);
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting product object from json array
JSONObject product = array.getJSONObject(i);
int search_id = product.getInt("search_id");
String activity = product.getString("activity");
String descp = product.getString("description");
String image = product.getString("activity_img");
String origin = product.getString("origin");
String destination =
product.getString("destination");
String date_from = product.getString("date_from");
String date_to = product.getString("date_to");
String price = product.getString("price");
ModelClass list = new ModelClass(search_id,
activity,
descp,image,
origin, destination, date_from, date_to,
price);
modelClassList.add(list);
}
adapter = new Adapter(list); //new line
recyclerView.setAdapter(adapter); //new line
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this.getActivity()).add(stringRequest);
}
Related
I am populating RecyclerView's adapter with ArrayList. List contain model object class which holds data from server. And it needs to be loaded into Tab Fragment.
I have tried everything I know about life cycle of a list and it seems that this list is deleted from memory at some point in that cycle.
Here is relevant part of code:
public class TrueFragment extends Fragment {
public static List<AllPositiveModel> newsList = new ArrayList<>();
private RecyclerView recyclerView;
private NewsAdapterTrue adapter;
private OnFragmentInteractionListener mListener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_true, container, false);
recyclerView = rootView.findViewById(R.id.recycler_view_true);
newsList = getResult();
adapter = new NewsAdapterTrue(newsList, getActivity());
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
return rootView;
}
public List<AllPositiveModel> getResult(){
final List<AllPositiveModel> items = new ArrayList<>();
GETAll getApiService;
getApiService = ApiUtils.getAPIServiceFetchAll();
getApiService.getAllNews().enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
Log.i("onSuccess", response.body());
String jsonresponse = response.body();
try {
//getting the whole json object from the response
JSONObject obj = new JSONObject(response.body());
JSONArray dataArray = obj.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
String title, desc, link, date, img, paper;
final Integer id, positive, negative;
JSONObject dataobj = dataArray.getJSONObject(i);
AllPositiveModel item = new AllPositiveModel(dataobj.getInt("id"), dataobj.getString("title"),
dataobj.getString("description"), dataobj.getString("link"),
dataobj.getString("date"), dataobj.getString("image"),
dataobj.getInt("positive_votes"), dataobj.getInt("negative_votes"),
dataobj.getString("paper"));
id = dataobj.getInt("id");
title = dataobj.getString("title");
desc = dataobj.getString("description");
link = dataobj.getString("link");
date = dataobj.getString("date");
img = dataobj.getString("image");
positive = dataobj.getInt("positive_votes");
negative = dataobj.getInt("negative_votes");
paper = dataobj.getString("paper");
items.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.i("onEmptyResponse", "Returned empty response");
}
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
}
});
return items;
}
}
When I print in Log values of list inside of getResult() method, it works fine. But after it gets out from the method, list is empty.
You have already a list on Global level, no need to create a new list. i have updated your code try to run it and test hopefully it will work.
public class TrueFragment extends Fragment {
public static List<AllPositiveModel> newsList = new ArrayList<>();
private RecyclerView recyclerView;
private NewsAdapterTrue adapter;
private OnFragmentInteractionListener mListener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_true, container, false);
recyclerView = rootView.findViewById(R.id.recycler_view_true);
getResult();// Call this method
adapter = new NewsAdapterTrue(newsList, getActivity());
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
return rootView;
}
public void getResult(){
// final List<AllPositiveModel> items = new ArrayList<>(); no need for this as you have a list on global level
GETAll getApiService;
getApiService = ApiUtils.getAPIServiceFetchAll();
getApiService.getAllNews().enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
Log.i("onSuccess", response.body());
String jsonresponse = response.body();
try {
//getting the whole json object from the response
JSONObject obj = new JSONObject(response.body());
JSONArray dataArray = obj.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
String title, desc, link, date, img, paper;
final Integer id, positive, negative;
JSONObject dataobj = dataArray.getJSONObject(i);
AllPositiveModel item = new AllPositiveModel(dataobj.getInt("id"), dataobj.getString("title"),
dataobj.getString("description"), dataobj.getString("link"),
dataobj.getString("date"), dataobj.getString("image"),
dataobj.getInt("positive_votes"), dataobj.getInt("negative_votes"),
dataobj.getString("paper"));
id = dataobj.getInt("id");
title = dataobj.getString("title");
desc = dataobj.getString("description");
link = dataobj.getString("link");
date = dataobj.getString("date");
img = dataobj.getString("image");
positive = dataobj.getInt("positive_votes");
negative = dataobj.getInt("negative_votes");
paper = dataobj.getString("paper");
newsList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.i("onEmptyResponse", "Returned empty response");
}
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
}
});
// return items;
}
}
Try this.I modified the code.
public class TrueFragment extends Fragment {
public static List<AllPositiveModel> newsList; //changed here
private RecyclerView recyclerView;
private NewsAdapterTrue adapter;
private OnFragmentInteractionListener mListener;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_true, container, false);
recyclerView = rootView.findViewById(R.id.recycler_view_true);
newsList = getResult(); //no changes here
adapter = new NewsAdapterTrue(newsList, getActivity());
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
return rootView;
}
public List<AllPositiveModel> getResult(){
final List<AllPositiveModel> items = new ArrayList<>();
GETAll getApiService;
getApiService = ApiUtils.getAPIServiceFetchAll();
getApiService.getAllNews().enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
if (response.isSuccessful()) {
if (response.body() != null) {
Log.i("onSuccess", response.body());
String jsonresponse = response.body();
try {
//getting the whole json object from the response
JSONObject obj = new JSONObject(response.body());
JSONArray dataArray = obj.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
String title, desc, link, date, img, paper;
final Integer id, positive, negative;
JSONObject dataobj = dataArray.getJSONObject(i);
AllPositiveModel item = new AllPositiveModel(dataobj.getInt("id"), dataobj.getString("title"),
dataobj.getString("description"), dataobj.getString("link"),
dataobj.getString("date"), dataobj.getString("image"),
dataobj.getInt("positive_votes"), dataobj.getInt("negative_votes"),
dataobj.getString("paper"));
id = dataobj.getInt("id");
title = dataobj.getString("title");
desc = dataobj.getString("description");
link = dataobj.getString("link");
date = dataobj.getString("date");
img = dataobj.getString("image");
positive = dataobj.getInt("positive_votes");
negative = dataobj.getInt("negative_votes");
paper = dataobj.getString("paper");
items.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.i("onEmptyResponse", "Returned empty response");
}
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
}
});
return items;
}
}
I have managed to solve the problem:
I have initialized adapter and recyclerview inside method getResult()
adapter = new NewsAdapterTrue(TrueNewsList, getActivity());
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
But I am still confused why my list is getting deleted from memory after it's being populated. I have almost same fragment and there is working just fine. I hope someone will answer me.
I have a MySQL database of two columns displayed in an android ListView. I use Retrofit 1.9 to get the data from MySQL. The adapter for the ListView is a BaseAdapter and I don't have a DatabaseHelperclass. When I add a data in the ListView from my mobile phone, it doesn't refresh the ListView. I have to close and restart the app. I try to refresh with listViewAdapter.notifyDataSetChanged();.
This is the fragment where the listview is:
public class rightFragment extends Fragment {
String BASE_URL = "http://awebsite.com";
View view;
ListView listView;
ListViewAdapter listViewAdapter;
Button buttondisplay;
Button buttonadd;
EditText new_id;
EditText newWordFra;
EditText newWordDeu;
ArrayList<String> id = new ArrayList<>();
ArrayList<String> fra = new ArrayList<>();
ArrayList<String> deu = new ArrayList<>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(com.example.geeko.Deu.R.layout.fragment_right, container, false);
listView = (ListView) view.findViewById(com.example.geeko.Deu.R.id.listView); //<<<< ADDED NOTE use your id
listViewAdapter = new ListViewAdapter(getActivity(), id, fra, deu);
displayData();
buttondisplay = (Button) view.findViewById(com.example.geeko.Deu.R.id.buttondisplay);
buttonadd = (Button) view.findViewById(com.example.geeko.Deu.R.id.buttonadd);
buttondelete = (Button) view.findViewById(com.example.geeko.Deu.R.id.newID);
newWordFra = (EditText) view.findViewById(com.example.geeko.Deu.R.id.newWordFra);
newWordDeu = (EditText) view.findViewById(com.example.geeko.Deu.R.id.newWordDeu);
buttonadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Toast.makeText(MainActivity.this , "button add", Toast.LENGTH_LONG).show();
insert_data();
listViewAdapter.notifyDataSetChanged();
}
});
buttondisplay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (buttondisplay.getText().toString().contains("Show")) {
listView.setAdapter(listViewAdapter);
buttondisplay.setText("Hide");
} else {
listView.setAdapter(null);
buttondisplay.setText("Show");
}
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long ids) {
new_id.setText(id.get(position));
newWordFra.setText(fra.get(position));
newWordDeu.setText(deu.get(position));
}
});
return view;
}
public void insert_data() {
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(BASE_URL) //Setting the Root URL
.build();
AppConfig.insert api = adapter.create(AppConfig.insert.class);
api.insertData(
newWordFra.getText().toString(),
newWordDeu.getText().toString(),
new Callback<Response>() {
#Override
public void success(Response result, Response response) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(result.getBody().in()));
String resp;
resp = reader.readLine();
Log.d("success", "" + resp);
JSONObject jObj = new JSONObject(resp);
int success = jObj.getInt("success");
if(success == 1){
Toast.makeText(getActivity(), "Successfully inserted", Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(getActivity(), "Insertion Failed", Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
Log.d("Exception", e.toString());
} catch (JSONException e) {
Log.d("JsonException", e.toString());
}
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(getActivity(), error.toString(), Toast.LENGTH_LONG).show();
}
}
);
}
public void displayData() {
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(BASE_URL) //Setting the Root URL
.build();
AppConfig.read api = adapter.create(AppConfig.read.class);
api.readData(new Callback<JsonElement>() {
#Override
public void success(JsonElement result, Response response) {
String myResponse = result.toString();
Log.d("response", "" + myResponse);
try {
JSONObject jObj = new JSONObject(myResponse);
int success = jObj.getInt("success");
if (success == 1) {
JSONArray jsonArray = jObj.getJSONArray("details");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jo = jsonArray.getJSONObject(i);
id.add(jo.getString("id"));
fra.add(jo.getString("fra"));
deu.add(jo.getString("deu"));
}
listView.setAdapter(listViewAdapter);
} else {
Toast.makeText(getActivity(), "No Details Found", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Log.d("exception", e.toString());
}
}
#Override
public void failure(RetrofitError error) {
Log.d("Failure", error.toString());
Toast.makeText(getActivity(), error.toString(), Toast.LENGTH_LONG).show();
}
}
);
}
}
This is the listViewAdpater class :
public class ListViewAdapter extends BaseAdapter {
private final Context context;
private ArrayList<String> id = new ArrayList<String>();
private ArrayList<String> fra = new ArrayList<String>();
private ArrayList<String> deu = new ArrayList<String>();
LayoutInflater layoutInflater;
public ListViewAdapter(Context ctx, ArrayList<String> id, ArrayList<String> fra, ArrayList<String> deu) {
this.context = ctx;
this.id = id;
this.fra = fra;
this.deu = deu;
}
#Override
public int getCount() {
return id.size();
}
#Override
public Object getItem(int position) {
return id.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint("ViewHolder")
#Override
public View getView(final int position, View view, ViewGroup parent) {
final Holder holder;
if (view == null) {
layoutInflater = (LayoutInflater) context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.list_item, null);
holder = new Holder();
holder.txt_fra = (TextView) view.findViewById(R.id.fra);
holder.txt_deu = (TextView) view.findViewById(R.id.deu);
view.setTag(holder);
} else {
holder = (Holder) view.getTag();
}
holder.txt_fra.setText(fra.get(position));
holder.txt_deu.setText(deu.get(position));
return view;
}
static class Holder {
TextView txt_fra, txt_deu;
}
}
Should I create a method to refresh my ListView?
First of all I would suggest to remove the unnecessary initialization of your variables inside the Adapter:
private ArrayList<String> id = new ArrayList<String>();
private ArrayList<String> fra = new ArrayList<String>();
private ArrayList<String> deu = new ArrayList<String>();
By assigning the pointer from your fragment you will already assign an initialized ArrayList. You want both pointers to point at the same ArrayList Object so changes apply to both.
Apparently, the data stored in the Adapter is not being updated correctly. I would suggest to debug your app - setting the breakpoint so that you can see the data that the Adapter stores after an update.
The idea of writing a method for updates has already been implemented with the notifyDataSetChanged(). Just override the method in your adapter and do eventual changes before calling the super.notifyDataSetChanged().
If you have any success with those changes let us know.
buttonadd.setOnClickListener(new View.OnClickListener() {
...
insert_data();
listViewAdapter.notifyDataSetChanged();
}
});
In your onClickListener, you are calling insert_data(), followed by listViewAdapter.notifyDataSetChanged()
insert_data() method is sending a network request to retrieve the data to populate the list. BUT, you are calling notifyDataSetChanged BEFORE the network request is done. That's why the listView is empty, and will stay empty. You need to wait AFTER the network request and AFTER you have populated your ArrayList with the data to call notifyDataSetChanged.
How do we know the network request is done? Simply at the end of the callback (which you've implemented):
new Callback<Response>() {
#Override
public void success(Response result, Response response) {...
At the end of the success method, you call listViewAdapter.notifyDataSetChanged() method.
Hope that makes sense! Try it and let us know what happens
I've founded a solution. I've added getActivity.recreate(); in the method insert_data.
public void success(Response result, Response response) {
try {
BufferedReader reader = new BufferedReader
(new InputStreamReader(result.getBody().in()));
String resp;
resp = reader.readLine();
Log.d("success", "" + resp);
JSONObject jObj = new JSONObject(resp);
int success = jObj.getInt("success");
if(success == 1){
Toast.makeText(getActivity(), "Successfully inserted",
Toast.LENGTH_SHORT).show();
getActivity().recreate();
} else{
Toast.makeText(getActivity(), "Insertion Failed",
Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
Log.d("Exception", e.toString());
} catch (JSONException e) {
Log.d("JsonException", e.toString());
}
}
I'm not sure that is the best solution but it works.
Please help me out to load more data from the server upon scrolling my RecyclerView . Here I have successfully created RecyclerView by loading data from my Mysql server by using volley string request.
Here is my code.
private void populateRecycleView() {
if (Utility.checkNetworkConnection(this)) {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Searching...");
progressDialog.setMessage("Searching for the blood donor. Please wait a moment.");
progressDialog.setCancelable(false);
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, Constants.GET_DONORS_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressDialog.dismiss();
try {
JSONArray jsonArray = new JSONArray(response);
int count = 0;
while (count < jsonArray.length()) {
JSONObject jsonObject = jsonArray.getJSONObject(count);
String firstName = jsonObject.getString("fName");
String secondName = jsonObject.getString("sName");
String email = jsonObject.getString("emailid");
String password = jsonObject.getString("pass");
String mobile = jsonObject.getString("mobile");
String bloodRt = jsonObject.getString("blood");
String age = jsonObject.getString("age");
String gender = jsonObject.getString("gender");
String country = jsonObject.getString("country");
String location = jsonObject.getString("location");
String latitude = jsonObject.getString("latitude");
String longitude = jsonObject.getString("longitude");
String profilePicFIleName = jsonObject.getString("picname");
String profilePicURL = jsonObject.getString("pic");
Donor donor = new Donor(firstName, secondName, email, password, mobile, bloodRt, age, gender,
country, location, latitude, longitude, profilePicFIleName, profilePicURL);
donorsList.add(donor);
count++;
}
donorsAdapter = new DonorsAdapter(FindDonorResult.this, donorsList);
recyclerView = (RecyclerView) findViewById(R.id.rv_search_result_donor);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(FindDonorResult.this));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(donorsAdapter);
donorsAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(FindDonorResult.this, "Active data network is not available.", Toast.LENGTH_LONG).show();
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("bloodGroup", bloodGroup);
return params;
}
};
NetworkRequestSingleTon.getOurInstance(this).addToRequestQue(stringRequest);
} else {
Utility.checkNetworkConnectionFound(this);
}
}
And this is my RecyclerView adapter...
public class DonorsAdapter extends RecyclerView.Adapter<DonorsAdapter.CustomViewHolder> {
private Context context;
private ArrayList<Donor> donorList;
private String bloodGroup;
public DonorsAdapter(Context context, ArrayList<Donor> donorList) {
this.context = context;
this.donorList = donorList;
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.rv_blood_donors_result,
parent, false);
return new CustomViewHolder(view);
}
#Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
final Donor donor = donorList.get(position);
String displayName = donor.getFirstName() + " " + donor.getSecondName();
holder.tvDisplayName.setText(displayName);
holder.tvEmailID.setText(donor.getEmail());
String userProfileURL = donor.getProfilePicURL();
if (!userProfileURL.equals("")) {
Picasso.with(context).load(userProfileURL).resize(80, 80).centerCrop().
into(holder.ivProfilePic);
} else {
holder.ivProfilePic.setImageResource(R.drawable.ic_person_white_24dp);
}
bloodGroup = donor.getBloodGroup();
if (bloodGroup.equals("A+"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.a_);
else if (bloodGroup.equals("A-"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.a_negative);
else if (bloodGroup.equals("B+"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.b_positive);
else if (bloodGroup.equals("B-"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.b_negative);
else if (bloodGroup.equals("O+"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.o_positive);
else if (bloodGroup.equals("O-"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.o_negative);
else if (bloodGroup.equals("AB+"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.ab_positive);
else if (bloodGroup.equals("AB-"))
holder.ivBloodTypeDisplay.setImageResource(R.drawable.ab_negative);
if(Utility.isNetworkEnabled){
holder.constraintLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, DisplayDonorDetails.class);
intent.putExtra("donor", donor);
context.startActivity(intent);
}
});
}else {
Toast.makeText(context, "Network not available.", Toast.LENGTH_SHORT).show();
}
}
#Override
public int getItemCount() {
if(donorList != null){
return donorList.size();
}else {
return 0;
}
}
public class CustomViewHolder extends RecyclerView.ViewHolder {
ImageView ivProfilePic, ivBloodTypeDisplay, ivArrow;
TextView tvDisplayName;
TextView tvEmailID;
ConstraintLayout constraintLayout;
public CustomViewHolder(View itemView) {
super(itemView);
ivProfilePic = (ImageView) itemView.findViewById(R.id.civ_user_profile_picture);
ivBloodTypeDisplay = (ImageView) itemView.findViewById(R.id.civ_user_blood_type_display);
ivArrow = (ImageView) itemView.findViewById(R.id.civ_arrow);
tvDisplayName = (TextView) itemView.findViewById(R.id.tvUserNameOnRV);
tvEmailID = (TextView) itemView.findViewById(R.id.tvEmailDisplayOnRV);
constraintLayout = (ConstraintLayout) itemView.findViewById(R.id.recycle_view_item_container);
}
}
}
Populate your donorsAdapter only with the 50 first elements of your donorsList, create a function that save the position of the latest element displayed and add other 50 donors to your adapter starting from the latest position saved when you need it.
Hope it helps.
EDIT
First create an emptyList:
List<Donor> subElements = new ArrayList<>();
and pass it to your adapter:
donorsAdapter = new DonorsAdapter(FindDonorResult.this, subElements);
Now you can create a method like this (you can call in onClick event for example):
private int LAST_POSITION = 0;
private int DONORS_NUM_TOSHOW = 50;
public void showMoreDonors(){
if(donarsList.size() > Last_postion+50){
List<Donor> tempList = new ArrayList<Donor>(donorsList.subList(Last_postion,Last_postion+DONORS_NUM_TOSHOW));
for(Donor a : tempList){
subElements.add(a);
}
Last_postion += DONORS_NUM_TOSHOW;
donorsAdapter.notifyDataSetChanged();
}else{
List<Donor> tempList = new ArrayList<Donor>(donorsList.subList(Last_postion,donorsList.size()));
for(Donor a : tempList){
subElements.add(a);
}
donorsAdapter.notifyDataSetChanged();
}
}
Remember to check when donorsList is over.
I didn't test it, but i hope it is usefull to understand the idea.
Finally, I sort this out. I have got an awesome tutorial from this blog.
http://android-pratap.blogspot.in/2015/06/endless-recyclerview-with-progress-bar.html.
I made some changes to populate the list because my data is on a remote server and by using volley library I fetched the data into the list. Remaining things are same.
I want to get the JSON response onto a RecyclerView. Though I am getting the correct response through the REST API I have used , but the response is not coming on the RecyclerView after parsing. Below is the code. Please help !!
RepoActivity.java
public class RepoActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private ProgressDialog pDialog;
private List<RepoList> repoList = new ArrayList<>();
String data = "";
private RecyclerView recyclerView;
private static String url;
private RepoAdapter adapter;
RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_repo);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Bundle bundle = getIntent().getExtras();
String message = bundle.getString("message");
adapter = new RepoAdapter(repoList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
url = "https://api.github.com/users/" + message + "/repos";
parsingMethod();
}
private void parsingMethod() {
Log.d("hello1", url);
pDialog = new ProgressDialog(this);
// Showing progress dialog
pDialog.setMessage("Loading...");
pDialog.show();
// Creating volley request obj
JsonArrayRequest cityReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
hidePDialog();
// Parsing json
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = null;
try {
obj = jsonArray.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
RepoList repoList = new RepoList();
try {
repoList.setRepoName(obj.getString("name"));
Log.d("zxcv",obj.getString("name") );
repoList.setRepoDesc(obj.getString("description"));
Log.d("zxcv",obj.getString("description") );
} catch (JSONException e) {
e.printStackTrace();
}
}
recyclerView.setAdapter(adapter);
}
},new Response.ErrorListener()
{
#Override
public void onErrorResponse (VolleyError error){
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(cityReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
RepoAdapter.java
public class RepoAdapter extends RecyclerView.Adapter<RepoAdapter.MyViewHolder> {
private List<RepoList> repoLists;
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.repo_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
RepoList repoList = repoLists.get(position);
holder.repoName.setText(repoList.getRepoName());
holder.repoDesc.setText(repoList.getRepoDesc());
}
#Override
public int getItemCount() {
return repoLists.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView repoName, repoDesc;
public MyViewHolder(View view) {
super(view);
repoName = (TextView) view.findViewById(R.id.repoName);
repoDesc = (TextView) view.findViewById(R.id.repoDesc);
}
}
public RepoAdapter( List<RepoList> repoList) {
this.repoLists = repoList;
}
}
RepoList.java
package com.example.lenovo.boxme;
/**
* Created by lenovo on 16-12-2016.
*/
public class RepoList {
private String repoName,repoDesc;
public RepoList(String repoDesc, String repoName) {
this.repoDesc = repoDesc;
this.repoName = repoName;
}
public RepoList(){};
public String getRepoDesc() {
return repoDesc;
}
public void setRepoDesc(String repoDesc) {
this.repoDesc = repoDesc;
}
public String getRepoName() {
return repoName;
}
public void setRepoName(String repoName) {
this.repoName = repoName;
}
}
adapter = new RepoAdapter(repoList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(adapter);
//notify data set after list item changed
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = null;
try {
obj = jsonArray.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
RepoList repo= new RepoList();
try {
repo.setRepoName(obj.getString("name"));
Log.d("zxcv",obj.getString("name") );
repo.setRepoDesc(obj.getString("description"));
Log.d("zxcv",obj.getString("description") );
repoList.add(repo);//you missed
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChange();
you're passing in repoList when creating adapter
adapter = new RepoAdapter(repoList);
but are then creating/populating new list before calling setAdapter
RepoList repoList = new RepoList();
...
recyclerView.setAdapter(adapter);
Remove this line :
RepoList repoList = new RepoList();
Put this line in onCreate
recyclerView.setAdapter(adapter);
And after fetching the data call :
adapter.notifyDataSetChange()
Here is my code, I have to call method getServerResponse() for first time to get store in arraylist and when I scrolls down I have to call method getServerResponseScroll(). I got result and notify adapter but after scrolling down and up data changes position or may be not visible or get changed. I had created custom adapter for chat. Please help me how to sort out this kind of problem.
public class ChatDetailActivity extends AppCompatActivity {
String macAddress;
RecyclerView recyclerView;
Activity context;
ChatAdapter adapter;
EditText etText;
DatabaseAdapter db;
NetClient nc;
EditText edtSend;
Button btnSend;
DataPref mDataPref;
static int page = 0;
SwipeRefreshLayout mSwipeRefreshLayout;
JSONArray chatDetailListJsonArray;
String toId, channelId, toProfilePic, deviceToken, deviceOsType;
static ArrayList<ChatDetailModel> chatDetailModels = new ArrayList<ChatDetailModel>();
// User mchatUSer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_detail);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
recyclerView = (RecyclerView) findViewById(R.id.card_recycler_view);
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
edtSend = (EditText) findViewById(R.id.edtSend);
btnSend = (Button) findViewById(R.id.btnSend);
db = new DatabaseAdapter(this);
mDataPref = DataPref.getInstance(this);
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
macAddress = wInfo.getMacAddress();
etText = (EditText) findViewById(R.id.etText);
toId = getIntent().getStringExtra("toId");
channelId = getIntent().getStringExtra("channelId");
toProfilePic = getIntent().getStringExtra("toProfilePic");
deviceToken = getIntent().getStringExtra("deviceToken");
deviceOsType = getIntent().getStringExtra("deviceOsType");
getServerResponse(this);
connectionForSend();
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessage();
}
});
}
void getServerResponse(final Context context){
StringRequest strReqNewsList = new StringRequest(Request.Method.POST, Constants.getChatDetailListUrl, new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("GetNewsList Response POST " + response);
/*
if (progressDialog != null) {
if (progressDialog.isShowing())
progressDialog.dismiss();
}*/
String message = "";
try {
JSONObject jsonObjectResponse = new JSONObject(response);
String responseStatus = jsonObjectResponse.getString("status");
message = jsonObjectResponse.getString("message");
if (responseStatus.equals("true")) {
chatDetailListJsonArray = jsonObjectResponse.getJSONArray("data");
if(page==0) {
GetChat.getInstance(context).deleteAllTableData("tbl_chat_detail", channelId);
}
// JSONObject chatListJsonObject= new JSONObject(gson.toJson(chatListJsonArray));
ArrayList<ChatDetailModel> chatlistModels = new Gson()
.fromJson(chatDetailListJsonArray.toString(),
new TypeToken<List<ChatDetailModel>>() {
}.getType());
for (int i = 0; i < chatDetailListJsonArray.length(); i++) {
ChatDetailModel chatlistModel = chatlistModels.get(i);
chatlistModel.setChannel_id(channelId);
GetChat.getInstance(context).addChatDetailList(new JSONObject(new Gson().toJson(chatlistModel)));
}
JSONArray chatListJsonArray = GetChat.getInstance(ChatDetailActivity.this).getChatDetailListJsonArray(channelId);
chatDetailModels = new Gson().fromJson(chatListJsonArray.toString(), new TypeToken<List<ChatDetailModel>>() {
}.getType());
implemantation();
}
} catch (JSONException e) {
e.printStackTrace();
JSONArray chatListJsonArray = GetChat.getInstance(ChatDetailActivity.this).getChatDetailListJsonArray(channelId);
chatDetailModels = new Gson().fromJson(chatListJsonArray.toString(), new TypeToken<List<ChatDetailModel>>() {
}.getType());
implemantation();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
/* if (progressDialog != null) {
if (progressDialog.isShowing())
progressDialog.dismiss();
}*/
error.printStackTrace();
JSONArray chatListJsonArray = GetChat.getInstance(ChatDetailActivity.this).getChatDetailListJsonArray(channelId);
chatDetailModels = new Gson().fromJson(chatListJsonArray.toString(), new TypeToken<List<ChatDetailModel>>() {
}.getType());
implemantation();
// DatabaseAdapter.deleteDatabase(context);
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("to_id", toId);
params.put("from_id", mDataPref.getUserId());
params.put("page",page+"");
params.put("last_sync_date_time", "");
return params;
}
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
strReqNewsList.setRetryPolicy(new DefaultRetryPolicy(40 * 1000, 1, 1.0f));
AppController.getInstance(context).addToRequestQueue(strReqNewsList);
}
void getServerResponseScroll(final Context context) {
StringRequest strReqNewsList = new StringRequest(Request.Method.POST, Constants.getChatDetailListUrl, new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("GetNewsList Response POST " + response);
String message = "";
try {
JSONObject jsonObjectResponse = new JSONObject(response);
String responseStatus = jsonObjectResponse.getString("status");
message = jsonObjectResponse.getString("message");
if (responseStatus.equals("true")) {
chatDetailListJsonArray = jsonObjectResponse.getJSONArray("data");
// JSONObject chatListJsonObject= new JSONObject(gson.toJson(chatListJsonArray));
ArrayList<ChatDetailModel> chatlistModels = new Gson()
.fromJson(chatDetailListJsonArray.toString(),
new TypeToken<List<ChatDetailModel>>() {
}.getType());
for (int i = 0; i < chatDetailListJsonArray.length(); i++) {
ChatDetailModel chatlistModel = chatlistModels.get(i);
chatlistModel.setChannel_id(channelId);
GetChat.getInstance(context).addChatDetailList(new JSONObject(new Gson().toJson(chatlistModel)));
}
JSONArray chatListJsonArray = GetChat.getInstance(ChatDetailActivity.this).getChatDetailListJsonArray(channelId);
// chatDetailModels.clear();
ArrayList<ChatDetailModel> chatDetailModels1 = new ArrayList<ChatDetailModel>();
chatDetailModels1 = new Gson().fromJson(chatListJsonArray.toString(), new TypeToken<List<ChatDetailModel>>() {
}.getType());
chatDetailModels.clear();
chatDetailModels.addAll(chatDetailModels1);
mSwipeRefreshLayout.setRefreshing(false);
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
/* if (progressDialog != null) {
if (progressDialog.isShowing())
progressDialog.dismiss();
}*/
error.printStackTrace();
// DatabaseAdapter.deleteDatabase(context);
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("to_id", toId);
params.put("from_id", mDataPref.getUserId());
params.put("page", page + "");
params.put("last_sync_date_time", "");
return params;
}
#Override
public Map<String, String> getHeaders() {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
};
strReqNewsList.setRetryPolicy(new DefaultRetryPolicy(40 * 1000, 1, 1.0f));
AppController.getInstance(context).addToRequestQueue(strReqNewsList);
}
void implemantation() {
RecyclerView.LayoutManager manager = new LinearLayoutManager(this.getApplicationContext());
recyclerView.setLayoutManager(manager);
adapter = new ChatAdapter(this.getApplicationContext(), chatDetailModels);
recyclerView.setAdapter(adapter);
recyclerView.scrollToPosition(chatDetailModels.size() - 1);
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, recyclerView, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Intent i = new Intent(ChatDetailActivity.this, ProfilesDetailActivity.class);
// i.putExtra("profileId",ChatlistModel.get(position).getId());
startActivity(i);
}
#Override
public void onItemLongClick(View view, int position) {
}
}));
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
page++;
getServerResponseScroll(ChatDetailActivity.this);
}
});
}
// Adapter for chat
public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.ViewHolder> {
private ArrayList<ChatDetailModel> chatDetailModels;
private Context context;
public ChatAdapter(Context context, ArrayList<ChatDetailModel> chatDetailModels) {
this.context = context;
this.chatDetailModels = chatDetailModels;
}
#Override
public ChatAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.chat_lsit_row, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
if (chatDetailModels.get(position).getFrom_username().equalsIgnoreCase(mDataPref.getUsername())) {
viewHolder.messageTextRight.setText(chatDetailModels.get(position).getMessage());
viewHolder.chatLeftLayout.setVisibility(View.GONE);
if (mDataPref.getProfilePicFullUrl().equals("null") || mDataPref.getProfilePicFullUrl().equals("")) {
viewHolder.fromImageView.setImageResource(R.drawable.default_profile_pic);
} else {
Picasso.with(context).load(mDataPref.getProfilePicFullUrl()).placeholder(R.drawable.default_profile_pic).transform(new CircleTransform()).resize(40, 40).into(viewHolder.fromImageView);
}
} else {
viewHolder.messageTextLeft.setText(chatDetailModels.get(position).getMessage());
viewHolder.chatRightLayout.setVisibility(View.GONE);
if (toProfilePic.equals("null") || toProfilePic.equals("")) {
viewHolder.toImageView.setImageResource(R.drawable.default_profile_pic);
} else {
Picasso.with(context).load(toProfilePic).placeholder(R.drawable.default_profile_pic).transform(new CircleTransform()).resize(40, 40).into(viewHolder.toImageView);
}
}
}
#Override
public int getItemCount() {
return chatDetailModels.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private LinearLayout chatLeftLayout;
private ImageView toImageView;
private TextView messageTextLeft;
private LinearLayout chatRightLayout;
private TextView messageTextRight;
private ImageView fromImageView;
public ViewHolder(View view) {
super(view);
chatLeftLayout = (LinearLayout) view.findViewById(R.id.chatLeftLayout);
toImageView = (ImageView) view.findViewById(R.id.toImageView);
messageTextLeft = (TextView) view.findViewById(R.id.message_text_left);
chatRightLayout = (LinearLayout) view.findViewById(R.id.chatRightLayout);
messageTextRight = (TextView) view.findViewById(R.id.message_text_right);
fromImageView = (ImageView) view.findViewById(R.id.fromImageView);
}
}
}
}
From onSaveInstanceState documentation:
Called when the LayoutManager should save its state. This is a good time to save your
* scroll position, configuration and anything else that may be required to restore the same
* layout state if the LayoutManager is recreated.
* RecyclerView does NOT verify if the LayoutManager has changed between state save and
* restore. This will let you share information between your LayoutManagers but it is also
* your responsibility to make sure they use the same parcelable class.
To get current state of recyclerview:
private Parcelable recyclerViewState = recyclerView.getLayoutManager().onSaveInstanceState();
to restore saved instance:
recyclerView.getLayoutManager().onRestoreInstanceState(recyclerViewState);