I am making Expandable RecyclerView. The problem is I have Data in ArrayList but Adapter is not getting set.
I have tried by setting adapter after arrayListNotiTypes.add(new NotiTypes("About SMS", addNotiToParticularNotiType(jaSms, ""))); this line, but same error occurs. I have made this type of Expandable RecyclerView for different module. There it is working fine.
Below is what I have tried..
Notification_Activity.java
public class Notification_Activity extends AppCompatActivity {
// Widgets
private ProgressDialog progressDialog;
private RecyclerView recyclerView_Noti;
// Variables
private String url = "notification.php";
private ArrayList<NotiTypes> arrayListNotiTypes;
private ArrayList<ActualNotis> arrayListActualNotis;
// Others
private AdapterNotification adapterNoti;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification);
find_view_by_id();
init();
if (Commom_Methods.isNetworkAvailable(this)) {
fetchData();
} else {
Toast.makeText(this, "Please, Coonect to internet!!", Toast.LENGTH_SHORT).show();
}
// Setting Adapter for Notification
adapterNoti = new AdapterNotification(Notification_Activity.this, arrayListNotiTypes);
recyclerView_Noti.setAdapter(adapterNoti);
recyclerView_Noti.setLayoutManager(new LinearLayoutManager(Notification_Activity.this));
}
private void find_view_by_id() {
recyclerView_Noti = (RecyclerView) findViewById(R.id.recycle_noti);
}
private void init() {
arrayListNotiTypes = new ArrayList<>();
}
private void fetchData() {
StringRequest stringReq = new StringRequest(Request.Method.POST, Constants.base_url + url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("onResponse: ", response);
progressDialog.dismiss();
if (response != null) {
try {
JSONObject jo = new JSONObject(response);
if (jo.has("success")) {
JSONObject joNoti = jo.getJSONObject("notification");
/*JSONArray jaStu = joNoti.getJSONArray("noti_student");
arrayListNotiTypes.add(new NotiTypes("About Student", addNotiToParticularNotiType(jaStu, "")));*/
JSONArray jaBatch = joNoti.getJSONArray("noti_batch");
arrayListNotiTypes.add(new NotiTypes("About Batch", addNotiToParticularNotiType(jaBatch, "")));
JSONArray jaInst = joNoti.getJSONArray("noti_institute");
arrayListNotiTypes.add(new NotiTypes("About Institute", addNotiToParticularNotiType(jaInst, "attach")));
JSONArray jaFee = joNoti.getJSONArray("noti_fee");
arrayListNotiTypes.add(new NotiTypes("About Fees", addNotiToParticularNotiType(jaFee, "attach")));
JSONArray jaSms = joNoti.getJSONArray("noti_sms");
arrayListNotiTypes.add(new NotiTypes("About SMS", addNotiToParticularNotiType(jaSms, "")));
} else {
Toast.makeText(getApplicationContext(), jo.getString("error_msg"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "Server error! Don't get Data from server. Try again later.", Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(), "Error:" + error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", Preferences.readString(getApplicationContext(), Preferences.KEY_SL_ID, ""));
params.put("tution_center_sl", Preferences.readString(getApplicationContext(), Preferences.KEY_TUTION_CENTER_SL, ""));
params.put("batch_sl", Preferences.readString(getApplicationContext(), Preferences.KEY_BATCH_SL, ""));
params.put("batch_grup_sl", Preferences.readString(getApplicationContext(), Preferences.KEY_BATCH_GRUP_SL, ""));
params.put("co_sl", Preferences.readString(getApplicationContext(), Preferences.KEY_CO_SL, ""));
params.put("drange_sl", Preferences.readString(getApplicationContext(), Preferences.KEY_DRANGE_SL, ""));
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("X-Apikey", Preferences.readString(getApplicationContext(), Preferences.KEY_USER_XAPIKEY, ""));
return headers;
}
};
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(stringReq);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
private ArrayList<ActualNotis> addNotiToParticularNotiType(JSONArray jsonArray, String attachments) throws JSONException {
arrayListActualNotis = new ArrayList<>();
if (jsonArray.length() > 0) {
for (int j = 0; j < jsonArray.length(); j++) {
JSONObject joInner = jsonArray.getJSONObject(j);
String notiTitle = joInner.getString("title");
String notiDesc = joInner.getString("decription");
String attach = "";
if (!attachments.equals(""))
attach = joInner.getString("attach");
arrayListActualNotis.add(new ActualNotis(notiTitle, notiDesc, attach));
}
} else {
arrayListActualNotis.add(new ActualNotis("No Notifications!!", "", ""));
}
return arrayListActualNotis;
}
}
AdapterNotification.java
public class AdapterNotification extends ExpandableRecyclerViewAdapter<AdapterNotification.NotiTypesViewHolder, AdapterNotification.ActualNotisViewHolder> {
private Activity mActivity;
public AdapterNotification(Activity activity, List<? extends ExpandableGroup> groups) {
super(groups);
this.mActivity = activity;
}
#Override
public NotiTypesViewHolder onCreateGroupViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = (LayoutInflater) mActivity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.noti_type_group_view_holder, parent, false);
return new NotiTypesViewHolder(view);
}
#Override
public ActualNotisViewHolder onCreateChildViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = (LayoutInflater) mActivity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.actual_notis_child_view_holder, parent, false);
return new ActualNotisViewHolder(view);
}
#Override
public void onBindGroupViewHolder(NotiTypesViewHolder holder, int flatPosition, ExpandableGroup group) {
holder.setGroupName(group);
}
#Override
public void onBindChildViewHolder(ActualNotisViewHolder holder, int flatPosition, ExpandableGroup group, int childIndex) {
final ActualNotis notis = ((NotiTypes) group).getItems().get(childIndex);
holder.onBind(notis, group);
}
public class NotiTypesViewHolder extends GroupViewHolder {
private TextView txt_noti_type;
public NotiTypesViewHolder(View itemView) {
super(itemView);
txt_noti_type = (TextView) itemView.findViewById(R.id.txt_noti_type);
}
#Override
public void expand() {
txt_noti_type.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.up_arrow, 0);
Log.e("Adapter", "Expand");
}
#Override
public void collapse() {
txt_noti_type.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.down_arrow, 0);
Log.e("Adapter", "collapse");
}
public void setGroupName(ExpandableGroup group) {
txt_noti_type.setText(group.getTitle());
}
}
public class ActualNotisViewHolder extends ChildViewHolder {
private TextView txt_noti, txt_noti_desc;
public ActualNotisViewHolder(View itemView) {
super(itemView);
txt_noti = (TextView) itemView.findViewById(R.id.txt_noti);
txt_noti_desc = (TextView) itemView.findViewById(R.id.txt_noti_desc);
}
public void onBind(ActualNotis actualNotis, ExpandableGroup group) {
switch (actualNotis.getmNotiTitle()) {
case "noti_student":
txt_noti.setText(actualNotis.getmNotiTitle());
txt_noti_desc.setText(actualNotis.getmNotiDesc());
break;
case "noti_batch":
txt_noti.setText(actualNotis.getmNotiTitle());
txt_noti_desc.setText(actualNotis.getmNotiDesc());
break;
case "noti_institute":
txt_noti.setText(actualNotis.getmNotiTitle());
txt_noti_desc.setText(actualNotis.getmNotiDesc());
break;
case "noti_fee":
txt_noti.setText(actualNotis.getmNotiTitle());
txt_noti_desc.setText(actualNotis.getmNotiDesc());
break;
case "noti_sms":
txt_noti.setText(actualNotis.getmNotiTitle());
txt_noti_desc.setText(actualNotis.getmNotiDesc());
break;
default:
break;
}
}
}
}
JSON Response From Server
{
"notification": {
"noti_batch": [
{
"title": "testtest",
"decription": "testtest"
}
],
"noti_institute": [
{
"title": "test",
"decription": "testtest",
"attach": ""
}
],
"noti_fee": [
{
"title": "test",
"decription": "test",
"attach": ""
}
],
"noti_sms": [
{
"title": "2016-11-03 00:00:00",
"decription": ""
}
]
},
"success": true
}
Thanks in advance!
setAdapter after getting data from the server i.e. inside onResponse() Or you have to notify adapter after changing data in List
Related
private void loadFrieghtData() {
progressLoader.startProgress(Frieght_Details.this);
RequestQueue queue = Volley.newRequestQueue(Frieght_Details.this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, UrlConstant.FRIEGHT_DETAILS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String status = jsonObject.optString("status");
if (status.equals("1")){
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int i =0 ; i< jsonArray.length(); i++){
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
dialogPOJO leftDashboardPOJO = new dialogPOJO(jsonObject1.optString("id"),
jsonObject1.optString("date"), jsonObject1.optString("credit"),
jsonObject1.optString("confirm_status"));
leftDashboardPOJOSList.add(leftDashboardPOJO);
}
progressLoader.dismissProgress(Frieght_Details.this);
millWiseReportRecyclerView.setAdapter(FrieghtAdapterPOJO);
FrieghtAdapterPOJO.notifyDataSetChanged();
System.out.println("SOMETHING DATA " + response.toString());
}else {
progressLoader.dismissProgress(Frieght_Details.this);
Toast.makeText(Frieght_Details.this, "Something Went Wrong", Toast.LENGTH_SHORT).show();
}
}catch (JSONException e){
progressLoader.dismissProgress(Frieght_Details.this);
System.out.println("paramsparamsparams===" + e.toString());
Toast.makeText(Frieght_Details.this, e.toString(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressLoader.dismissProgress(Frieght_Details.this);
System.out.println("paramsparamsparams===" + error.toString());
Toast.makeText(Frieght_Details.this, error.toString(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
{
/* params.put("user_id", prefManager.getGSTstate());
params.put("godown_id", prefManager.getGodownlocation()); */
params.put("godown_id", "3");
params.put("user_id", "dddd");
params.put("vehicle", "2");
}
System.out.println("paramsparamsparams===" + params.toString());
return params;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(
DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 8,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(stringRequest);
}
This is my Main Method Code
public class FreightAdapter extends RecyclerView.Adapter<FreightAdapter.ViewHolder> {
private List<dialogPOJO> list_data;
private Frieght_Details context;
private PrefManager prefManager;
public FreightAdapter(List<dialogPOJO> list_data, Frieght_Details context) {
this.list_data = list_data;
this.context = context;
prefManager = new PrefManager(context);
}
#Override
public FreightAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.frieght_wiseadapterlayout,parent,false);
return new FreightAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(FreightAdapter.ViewHolder holder, int position) {
final dialogPOJO lenaDenaPOJO = list_data.get(position);
if (position %2 == 1){
holder.linearLayout_data.setBackgroundColor(context.getResources().getColor(R.color.white));
}else {
holder.linearLayout_data.setBackgroundColor(context.getResources().getColor(R.color.colorGrey));
}
String countString = lenaDenaPOJO.getCount();
holder.ordernumber.setText( countString );
holder.ordernumber1.setText( lenaDenaPOJO.getKey());
String truck_id = lenaDenaPOJO.getReports();
String vehicle_status = lenaDenaPOJO.getVehicleStatus();
System.out.println("VEHICLE_VALE " + vehicle_status + " " + truck_id + " " + countString);
holder.frieght.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
context.callDialogMethod(countString);
}
});
holder.actionOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
context.CallOkStatus(vehicle_status, countString, truck_id);
}
});
}
#Override
public int getItemCount() {
return list_data.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView ordernumber, ordernumber1, frieght, actionOK;
private Button view_Reports;
private LinearLayout linearLayout_data;
public ViewHolder(View itemView) {
super(itemView);
ordernumber = itemView.findViewById(R.id.pro_name);
ordernumber1 = itemView.findViewById(R.id.frieght);
frieght = itemView.findViewById(R.id.total_qty);
actionOK = itemView.findViewById(R.id.actionOK);
linearLayout_data = itemView.findViewById(R.id.linearLayout_data);
}
}
}
Here are logs
I/System.out: SOMETHING DATA
{"status":1,"data":[{"id":2876,"credit":1500,"confirm_status":1,"date":"01-01-2021"},{"id":2919,"credit":1900,"confirm_status":1,"date":"02-01-2021"},{"id":2933,"credit":2050,"confirm_status":1,"date":"04-01-2021"},{"id":2964,"credit":3500,"confirm_status":1,"date":"05-01-2021"},{"id":3004,"credit":2450,"confirm_status":1,"date":"06-01-2021"}
And This is my Adapter Code I can't understand What is wrong in this.
Please Help me in this case
I have added image for more details,
When I call Activity First Time it works Perfectly But If call onResume method then There is no data added on Recycler view I can't understand what get wrong in my code
I am trying to display posts from a server in listView. So I used recycle-view to achieve that. Everything is working fine except that ll items are displaying twice.
I counted the total fetched items from server, and the count is 5, but adapter.getItemCount is showing 10.
After searching hours on the internet, I tried following :
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
and
homeFragmentAdapter.setHasStableIds(true);
Below is my fragment...
package com.example.projectName;
import static android.content.Context.MODE_PRIVATE;
import static android.webkit.ConsoleMessage.MessageLevel.LOG;
import static com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade;
public class HomeFollowersFragment extends Fragment implements InfiniteScrollListener.OnLoadMoreListener, RecyclerViewItemListener {
private static final String TAG = "HomeFollowersFragment";
private static final String URL = "https://api.androidhive.info/json/movies_2017.json";
private RecyclerView recyclerView;
private ProgressBar postLoader;
FFmpeg ffmpeg;
// private List<Movie> movieList;
// private HomeAdapter mAdapter;
private List<PostList> postListGlobal = new ArrayList<>();
List<VerticalDataModal> verticalDataModals;
List<HorizontalDataModal> horizontalDataModals;
private SwipeRefreshLayout swipeMore;
private InfiniteScrollListener infiniteScrollListener;
private HomeFragmentAdapter homeFragmentAdapter;
SharedPreferences sharedPreferences;
private Boolean isLoggedIn = false;
private String email = "";
private String token = "";
private String userId = "";
private Dialog customLoader;
SkeletonScreen skeletonScreen;
private int pastVisiblesItems, visibleItemCount, totalItemCount;
private boolean loading = false;
private EndlessScrollListener scrollListener;
SharedPreferences sp;
SharedPreferences.Editor Ed;
public HomeFollowersFragment() {
//super();
}
/**
* #return A new instance of fragment HomeFollowersFragment.
*/
public static HomeFollowersFragment newInstance() {
return new HomeFollowersFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
// ((AppCompatActivity) getActivity()).getSupportActionBar().show();
try{
sharedPreferences = getActivity().getSharedPreferences("Login", MODE_PRIVATE);
email = sharedPreferences.getString("email", null);
token = sharedPreferences.getString("token", null);
isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false);
userId = sharedPreferences.getString("id", null);
}catch (Exception e){
e.printStackTrace();
Log.d("StackError", "StackError: "+e);
}
sp = getActivity().getSharedPreferences("Posts", MODE_PRIVATE);
if(!isLoggedIn || token == null || userId == null){
Intent intent = new Intent(getActivity(), RegisterActivity.class);
intent.putExtra("loginFrom", "profile");
startActivity(intent);
}
recyclerView = view.findViewById(R.id.recycler_view);
postLoader = view.findViewById(R.id.post_loader);
swipeMore = view.findViewById(R.id.swipe_layout);
homeFragmentAdapter = new HomeFragmentAdapter(postListGlobal, this, "home");
if(sp.contains("postListGlobal"))
skeletonScreen = Skeleton.bind(recyclerView)
.adapter(homeFragmentAdapter)
.shimmer(true)
.angle(20)
.frozen(false)
.duration(1200)
.count(10)
.load(R.layout.item_skelton_home_page)
.show(); //default count is 10
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2);
StaggeredGridLayoutManager sLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(sLayoutManager);
homeFragmentAdapter.setHasStableIds(true);
recyclerView.setAdapter(homeFragmentAdapter);
recyclerView.setNestedScrollingEnabled(false);
customLoader = new Dialog(getActivity(), R.style.crystal_range_seek_bar);
customLoader.setCancelable(false);
View loaderView = getLayoutInflater().inflate(R.layout.custom_loading_layout, null);
customLoader.getWindow().getAttributes().windowAnimations = R.style.crystal_range_seek_bar;
customLoader.getWindow().setBackgroundDrawableResource(R.color.translucent_black);
ImageView imageLoader = loaderView.findViewById(R.id.logo_loader);
Glide.with(this).load(R.drawable.logo_loader).into(imageLoader);
customLoader.setContentView(loaderView);
if(homeFragmentAdapter.getItemCount() == 0 && !loading){
// server fetchdata
Log.d(TAG, "no item available..");
postLoader.setVisibility(View.VISIBLE);
loading = true;
fetchStoreItems();
}else{
postLoader.setVisibility(View.GONE);
}
swipeMore.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
Log.d(TAG, "on refresh...");
fetchStoreItems();
}
});
return view;
}
#Override
public void onItemClicked(int position) {
Log.d(TAG, "click position: "+position);
Toast.makeText(getActivity(),postListGlobal.get(position).getTitle(),Toast.LENGTH_SHORT).show();
// Toast.makeText(getActivity(),""+position, Toast.LENGTH_SHORT).show();
}
public int getLastVisibleItem(int[] lastVisibleItemPositions) {
int maxSize = 0;
for (int i = 0; i < lastVisibleItemPositions.length; i++) {
if (i == 0) {
maxSize = lastVisibleItemPositions[i];
}
else if (lastVisibleItemPositions[i] > maxSize) {
maxSize = lastVisibleItemPositions[i];
}
}
return maxSize;
}
#Override
public void onLoadMore() {
homeFragmentAdapter.addNullData();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
homeFragmentAdapter.removeNull();
Toast.makeText(getContext(), "load more here...", Toast.LENGTH_LONG).show();
// fetchStoreItems();
swipeMore.setRefreshing(false);
}
}, 2000);
}
private void fetchStoreItems() {
RequestQueue queue = Volley.newRequestQueue(getActivity());
Log.d(TAG, "Post Data Followers: "+Constant.FETCH_POSTS_API);
CacheRequest cacheRequest = new CacheRequest(0, Constant.FETCH_POSTS_API, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
try {
final String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
if (response == null) {
Toast.makeText(getActivity(), "Couldn't fetch the store items! Pleas try again.", Toast.LENGTH_LONG).show();
loading = false;
return;
}
JSONObject postObj = new JSONObject(jsonString);
System.out.println("post full data... : " + postObj);
if (postObj.getBoolean("Status")) {
try {
postLoader.setVisibility(View.GONE);
JSONArray arrayResponse = postObj.optJSONArray("Data");
int dataArrLength = arrayResponse.length();
if(dataArrLength == 0){
Toast.makeText(getActivity(), "No posts available at this time, you can create yout own post by clicking on mic button", Toast.LENGTH_SHORT).show();
}
postListGlobal.clear();
Log.d(TAG, "Total Posts count: "+dataArrLength);
for(int i=0; i<dataArrLength; i++) {
try {
JSONObject dataListObj = arrayResponse.optJSONObject(i);
System.out.println("post full data... : " + dataListObj);
JSONObject postDetailObj = dataListObj.optJSONObject("post_detail");
JSONObject followDtatusObj = dataListObj.optJSONObject("follow_status");
JSONArray postFilesArr = dataListObj.optJSONArray("post_files");
JSONObject userDatasObj = postDetailObj.optJSONObject("user");
String userId = userDatasObj.optString("id");
String userName = userDatasObj.optString("email");
String userImage = userDatasObj.optString("email");
boolean followStatus = followDtatusObj.optBoolean("follow");
String postId = postDetailObj.optString("id");
String postTitle = postDetailObj.optString("post_title");
String postDescription = postDetailObj.optString("post_description");
String postCoverUrl = postDetailObj.optString("post_coverurl", "1");
String postViewType = postDetailObj.optString("view_type", "1");
String postAllowComment = postDetailObj.optString("allow_comments", "1");
String postAllowDownload = postDetailObj.optString("allow_download", "1");
String postTotalPost = postDetailObj.optString("total_post", "1");
String postPostSection = postDetailObj.optString("post_section", "image");
String postActiveStatus = postDetailObj.optString("is_active", "1");
String postTotalViews = postDetailObj.optString("total_watched","0");
String postTotalShare = postDetailObj.optString("total_share","0");
String postTotalDownload = postDetailObj.optString("total_download","0");
String postTotalReaction = postDetailObj.optString("total_reaction","0");
String postTotalLike = postDetailObj.optString("total_like","0");
String postTotalSmile = postDetailObj.optString("smile_reaction","0");
String postTotalLaugh = postDetailObj.optString("laugh_reaction","0");
String postTotalSad = postDetailObj.optString("sad_reaction","0");
String postTotalLove = postDetailObj.optString("love_reaction","0");
String postTotalShock = postDetailObj.optString("shock_reaction","0");
int totalPostFiles = Integer.parseInt(postTotalPost);
int postArrLength = postFilesArr.length();
String postImageUrl = null;
String postMusicUrl = null;
String commonUrl = "http://serverName.com/";
if(postArrLength >= 1){
JSONObject dataFilesListObj = postFilesArr.optJSONObject(0);
// System.out.println("post files full data... : " + dataFilesListObj);
String postFileId = dataFilesListObj.optString("id");
postImageUrl = dataFilesListObj.optString("image_file_path");
postMusicUrl = dataFilesListObj.optString("music_file_path");
System.out.println("post files full data... : " + dataFilesListObj);
}
System.out.println("post files full data... : " + commonUrl+postMusicUrl);
System.out.println("post files full data... : " + commonUrl+postImageUrl);
PostList postList = new PostList();
postList.setId(postId);
postList.setTitle(postTitle);
postList.setTotalPost(""+dataArrLength);
postList.setTotalView(postTotalViews);
postList.setTotalReaction(postTotalReaction);
postList.setMusicPath(commonUrl+postMusicUrl);
postList.setImagePath(commonUrl+postImageUrl);
if(postImageUrl == null){
postList.setImagePath("https://amazonBucket.s3.location.amazonaws.com/images/pic1.jpg");
}
postList.setUserId(userId);
postList.setUserName(userName);
postList.setPostDataObject(arrayResponse);
postListGlobal.add(postList);
Log.d(TAG, "Total Posts: "+dataListObj);
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG, "Post Data Error1: "+e);
Toast.makeText(getActivity(), "File now found", Toast.LENGTH_LONG).show();
loading = false;
}
}
} catch (Exception e){
e.printStackTrace();
Log.d(TAG, "Post Data Error2: "+e);
Toast.makeText(getActivity(), R.string.server_error, Toast.LENGTH_LONG).show();
loading = false;
}
}else{
try {
Toast.makeText(getActivity(), new JSONObject(jsonString).getString("Message"), Toast.LENGTH_LONG).show();
} catch (JSONException ex) {
ex.printStackTrace();
Log.d(TAG, "Post Data Error3: "+ex);
Toast.makeText(getActivity(), R.string.server_error, Toast.LENGTH_SHORT).show();
}
loading = false;
}
// refreshing recycler view
homeFragmentAdapter.removeNull();
homeFragmentAdapter.addData(postListGlobal);
homeFragmentAdapter.notifyDataSetChanged();
// save in local memory
// saveArrayList(postListGlobal, "postListGlobal");
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG, "Post Data Error4: "+e);
}
loading = true;
homeFragmentAdapter.notifyDataSetChanged();
swipeMore.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "onErrorResponse: "+ error, Toast.LENGTH_SHORT).show();
swipeMore.setRefreshing(false);
loading = true;
homeFragmentAdapter.notifyDataSetChanged();
postLoader.setVisibility(View.VISIBLE);
loading = false;
Log.d(TAG, "Post Data Error5: "+error);
}
}){
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
String finalToken = "Bearer "+token;
params.put("Authorization", finalToken);
params.put("Content-Type", "application/json");
return params;
}
};
// Add the request to the RequestQueue.
queue.add(cacheRequest);
}
private class CacheRequest extends Request<NetworkResponse> {
private final Response.Listener<NetworkResponse> mListener;
private final Response.ErrorListener mErrorListener;
public CacheRequest(int method, String url, Response.Listener<NetworkResponse> listener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.mListener = listener;
this.mErrorListener = errorListener;
}
#Override
protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) {
Cache.Entry cacheEntry = HttpHeaderParser.parseCacheHeaders(response);
if (cacheEntry == null) {
cacheEntry = new Cache.Entry();
}
final long cacheHitButRefreshed = 3 * 60 * 1000; // in 3 minutes cache will be hit, but also refreshed on background
final long cacheExpired = 24 * 60 * 60 * 1000; // in 24 hours this cache entry expires completely
long now = System.currentTimeMillis();
final long softExpire = now + cacheHitButRefreshed;
final long ttl = now + cacheExpired;
cacheEntry.data = response.data;
cacheEntry.softTtl = softExpire;
cacheEntry.ttl = ttl;
String headerValue;
headerValue = response.headers.get("Date");
if (headerValue != null) {
cacheEntry.serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue);
}
headerValue = response.headers.get("Last-Modified");
if (headerValue != null) {
cacheEntry.lastModified = HttpHeaderParser.parseDateAsEpoch(headerValue);
}
cacheEntry.responseHeaders = response.headers;
return Response.success(response, cacheEntry);
}
#Override
protected void deliverResponse(NetworkResponse response) {
mListener.onResponse(response);
}
#Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
Log.d(TAG, "Post Data volleyError: "+volleyError);
return super.parseNetworkError(volleyError);
}
#Override
public void deliverError(VolleyError error) {
mErrorListener.onErrorResponse(error);
}
}
}
and Adapter Class
package com.example.ProjectName;
public class HomeFragmentAdapter extends RecyclerView.Adapter <HomeFragmentAdapter.HomeViewHolder>{
// private ArrayList<Integer> dataList;
private List<PostList> postListGlobal;
int VIEW_TYPE_LOADING;
int VIEW_TYPE_ITEM;
Context context;
private RecyclerViewItemListener callback;
FFmpeg ffmpeg;
String callingPage;
public HomeFragmentAdapter(List<PostList> postListGlobal, RecyclerViewItemListener callback, String callingPage) {
this.postListGlobal = postListGlobal;
this.callback = callback;
this.callingPage = callingPage;
// setHasStableIds(true);
}
#NonNull
#Override
public HomeFragmentAdapter.HomeViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View root = null;
context = parent.getContext();
root = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_home_tile_list, parent, false);
return new DataViewHolder(root);
}
#Override
public void onBindViewHolder(#NonNull HomeFragmentAdapter.HomeViewHolder holder, int position) {
if (holder instanceof DataViewHolder) {
final PostList postList = postListGlobal.get(position);
holder.postTitle.setText(postList.getTitle());
holder.postWatch.setText(postList.getTotalView());
holder.postReaction.setText(postList.getTotalReaction());
String imageUrl = postList.getImagePath();
// String imageUrl = Constant.SERVER_URL+"/"+postList.getImagePath();
String musicUrl = postList.getMusicPath();
// String musicUrl = Constant.SERVER_URL+"/"+postList.getMusicPath();
Log.d(TAG, "Post url: "+imageUrl+" -- "+musicUrl);
// int totalMusicTime = getDurationVal(musicUrl, "second");
holder.postTime.setText(postList.getTotalPost());
holder.thumbnail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
callback.onItemClicked(position);
Log.d("homeView", "screenName : "+callingPage);
if(callingPage.equals("home")){
Log.d("homeView", "screenName : "+position);
Intent intent = new Intent(context, MainViewActivity.class);
intent.putExtra("loginFrom", "homeView");
intent.putExtra("postDataObj", postList.getPostDataObject().toString());
intent.putExtra("postPosition", ""+position);
intent.putExtra("tabId", "1");
context.startActivity(intent);
}
}
});
Drawable mDefaultBackground = context.getResources().getDrawable(R.drawable.influencers);
CircularProgressDrawable circularProgressDrawable = new CircularProgressDrawable(context);
circularProgressDrawable.setStrokeWidth(5f);
Glide.with(context)
.load(imageUrl)
.listener(new RequestListener<Drawable>() {
#Override
public boolean onLoadFailed(#Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
// progressBar.setVisibility(View.GONE);
return false;
}
#Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
// progressBar.setVisibility(View.GONE);
return false;
}
})
.error(mDefaultBackground)
.into(holder.thumbnail);
}else{
//Do whatever you want. Or nothing !!
}
}
#Override
public int getItemCount() {
return postListGlobal.size();
}
class DataViewHolder extends HomeViewHolder {
public DataViewHolder(View itemView) {
super(itemView);
}
}
class ProgressViewHolder extends HomeViewHolder {
public ProgressViewHolder(View itemView) {
super(itemView);
}
}
class HomeViewHolder extends RecyclerView.ViewHolder {
public TextView postTitle, postTime, postWatch, postReaction;
public ImageView thumbnail;
public HomeViewHolder(View itemView) {
super(itemView);
postTitle = itemView.findViewById(R.id.post_title);
postTime = itemView.findViewById(R.id.total_time);
postWatch = itemView.findViewById(R.id.total_watch);
postReaction = itemView.findViewById(R.id.total_reaction);
thumbnail = itemView.findViewById(R.id.thumbnail);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
public void addNullData() {
}
public void removeNull() {
notifyItemRemoved(postListGlobal.size());
}
public void addData(List<PostList> postLists) {
postListGlobal.addAll(postLists);
notifyDataSetChanged();
}
}
After trying everything, I was still not able to resolve the issue. Any help/suggestions are welcome. Let me know If I left out any needed code--if so I can update it here.
`postListGlobal.add(postList);` below this line add ` homeFragmentAdapter.notifyDataSetChanged();` and remove ` homeFragmentAdapter.removeNull(); homeFragmentAdapter.addData(postListGlobal);homeFragmentAdapter.notifyDataSetChanged();` this code.Because in this case list added twice without notifying datasetchange check with your code by removing this.
postListGlobal.clear(); just clear tha arraylist before add .
postListGlobal.clear() before adding new list to the adapter.
And then notifyDataSetChanged() to let adapter know of the changes.
Recycle view load list and reached at top by mList.add(0,actor) but i want to reverse the list.
also i chnaged my code like this,
mLayoutManager.setReverseLayout(true);
mList.add(0,actor);
Here is my recycleview info, This is my recyclview api code InfoJson() here:
public class GatekeeperInfoActivity extends BaseActivity implements View.OnClickListener , MyComplaintListner {
private RecyclerView mRecyclerView;
private GateInfoAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private List<GateInfoPojo> mList;
Context ctx;
String visitor_id,id,cid;
M_Shared_Pref m_shared_pref;
ImageView back_button, img;
private MyDialog dialog;
TextView complaint,subject,msg,from_name_txt;
ImageView attach;
String from_id,from_name,from_mobile;
String id_rwa,new_id;
public static final int DISMISS_TIMEOUT = 2000;
LinearLayout ll_no_data;
int limit =0;
int limit_refresh;
static int nums;
private appconfig.EndlessRecyclerOnScrollListener scrollListener;
LinearLayoutManager linearLayoutManager;
public int overallXScrol = 0;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rwa_view_info);
ctx = GatekeeperInfoActivity.this;
dialog = new MyDialog(this);
m_shared_pref = new M_Shared_Pref(GatekeeperInfoActivity.this);
visitor_id = m_shared_pref.getPrefranceStringValue(App_Info.Visitor_ID);
id = m_shared_pref.getPrefranceStringValue(App_Info.Flat_User_Id);
cid = m_shared_pref.getPrefranceStringValue(App_Info.Flat_User_Id_cid);
Bundle bundle = this.getIntent().getExtras();
from_id = bundle.getString("id");
from_name = bundle.getString("name");
from_mobile = bundle.getString("mobile");
id_rwa = getIntent().getStringExtra("id_rwa");
if (from_id != null && !from_id.isEmpty() && !from_id.equals("null"))
{ new_id = from_id; }
else{ new_id = id_rwa; }
System.out.println("check:check"+from_id+":"+id_rwa);
///// using this new_id
mList = new ArrayList<GateInfoPojo>();
mRecyclerView = findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new GateInfoAdapter(mList, ctx);
ll_no_data = findViewById(R.id.ll_no_data);
mAdapter.setMyClickListener(this);
/* button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
limit_refresh = nums+limit;
limit = limit_refresh;
if(nums>=20){
// item_progress_bar.setVisibility(View.VISIBLE);
InfoJson();
}
}
});*/
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (!recyclerView.canScrollVertically(-1)) {
// Toast.makeText(GatekeeperInfoActivity.this, "Last", Toast.LENGTH_LONG).show();
limit_refresh = nums+limit;
limit = limit_refresh;
if(nums>=20){
// item_progress_bar.setVisibility(View.VISIBLE);
InfoJson();
}
}
}
});
img = findViewById(R.id.pic);
from_name_txt = findViewById(R.id.from_name_txt);
attach = findViewById(R.id.attach);
msg = findViewById(R.id.msg);
complaint = findViewById(R.id.complaint);
subject = findViewById(R.id.subject);
back_button = findViewById(R.id.back_button);
back_button.setOnClickListener(this);
attach.setOnClickListener(this);
if(NetWorkCheck.checkConnection(GatekeeperInfoActivity.this)){
mList.clear();
InfoJson();
}
else{
TastyToast.makeText(getApplicationContext(), "Internet connection is disable", TastyToast.LENGTH_LONG, TastyToast.WARNING);
}
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.back_button:
finish();
break;
case R.id.attach:
if(msg.getText().toString().length()>0){
submitReply(msg.getText().toString(),new_id);
}
else{
TastyToast.makeText(getApplicationContext(), "Enter Message", TastyToast.LENGTH_LONG, TastyToast.INFO);
}
break;
}
}
public void InfoJson() {
dialog.ShowProgressDialog();
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.Base_Url+"AllChatWithUser.php?", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
dialog.CancelProgressDialog();
JSONObject obj = new JSONObject(response);
String error = obj.getString("error");
nums = obj.getInt("nums");
System.out.println("limit_limit_num"+nums);
if(nums>=1) {
if (error.equals("true")) {
from_name_txt.setText("GateKeeper : " + obj.getString("names"));
JSONArray tower = obj.getJSONArray("Flat");
for (int i = 0; i < tower.length(); i++) {
JSONObject jsonnew = tower.getJSONObject(i);
GateInfoPojo actor = new GateInfoPojo();
String id = jsonnew.getString("id");
String Reply_From = jsonnew.getString("reply_from");
String message = jsonnew.getString("message");
String reply_date = jsonnew.getString("send_time");
String usertype = jsonnew.getString("usertype");
actor.setId(id);
actor.setReply_from(Reply_From);
actor.setMessage(message);
actor.setSend_time(reply_date);
actor.setUsertype(usertype);
if(limit==0){
mList.add(actor);
}
else{
mList.add(0,actor);
}
mAdapter.notifyDataSetChanged();
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.getLayoutManager().scrollToPosition(nums - 1);
}
}
}
else
{
mRecyclerView.setVisibility(View.GONE);
ll_no_data.setVisibility(View.VISIBLE);
// TastyToast.makeText(getApplicationContext(), obj.getString("msg"), TastyToast.LENGTH_LONG, TastyToast.ERROR);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
dialog.CancelProgressDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("empid", new_id);
params.put("fid", id);
params.put("usertype", "FlatUser");
params.put("limit", String.valueOf(limit));
Log.e("params", String.valueOf(params));
return params;
}
};
requestQueue.add(stringRequest);
}
#Override
public void onItemClick(View v, Object bean, String feed, String rating,String comp_spinner) {
String complaint_id = ((GateInfoPojo) bean).getId();
// submitComplaintInfo(complaint_id,feed,rating,comp_spinner);
}
#Override
public void onItemClickActivity(View v, Object bean) {
String complaint_id = ((GateInfoPojo) bean).getId();
}
public void submitReply(final String msg1,final String new_id) {
dialog.ShowProgressDialog();
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.Base_Url+"ChatWithUser.php?", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
dialog.CancelProgressDialog();
JSONObject obj = new JSONObject(response);
String error = obj.getString("error");
if (error.equals("true"))
{
// TastyToast.makeText(getApplicationContext(), obj.getString("msg"), TastyToast.LENGTH_LONG, TastyToast.SUCCESS);
msg.setText("");
InfoJson();
mList.clear();
}
else
{
TastyToast.makeText(getApplicationContext(), obj.getString("msg"), TastyToast.LENGTH_LONG, TastyToast.ERROR);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
dialog.CancelProgressDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("fid", id);
params.put("empid", new_id);
params.put("usertype", "FlatUser");
params.put("message", msg1);
Log.e("params", String.valueOf(params));
return params;
}
};
requestQueue.add(stringRequest);
}
}
But this is not working its add to top but not reverse the api data bottom to top.
Any help would be appreciated.
You can reverse the array list by -
Collections.reverse(mList);
After that setAdapter() or notifyDataSetChanged() according to your requirement.
public void InfoJson() {
dialog.ShowProgressDialog();
RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.Base_Url+"AllChatWithUser.php?", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
dialog.CancelProgressDialog();
JSONObject obj = new JSONObject(response);
String error = obj.getString("error");
nums = obj.getInt("nums");
System.out.println("limit_limit_num"+nums);
if(nums>=1) {
if (error.equals("true")) {
from_name_txt.setText("GateKeeper : " + obj.getString("names"));
JSONArray tower = obj.getJSONArray("Flat");
for (int i = 0; i < tower.length(); i++) {
JSONObject jsonnew = tower.getJSONObject(i);
GateInfoPojo actor = new GateInfoPojo();
String id = jsonnew.getString("id");
String Reply_From = jsonnew.getString("reply_from");
String message = jsonnew.getString("message");
String reply_date = jsonnew.getString("send_time");
String usertype = jsonnew.getString("usertype");
actor.setId(id);
actor.setReply_from(Reply_From);
actor.setMessage(message);
actor.setSend_time(reply_date);
actor.setUsertype(usertype);
if(limit==0){
mList.add(actor);
}
else{
mList.add(0,actor);
}
}
Collections.reverse(mList);
mAdapter.notifyDataSetChanged();
mRecyclerView.setAdapter(mAdapter);
// mRecyclerView.getLayoutManager().scrollToPosition(nums - 1);
}
}
else
{
mRecyclerView.setVisibility(View.GONE);
ll_no_data.setVisibility(View.VISIBLE);
// TastyToast.makeText(getApplicationContext(), obj.getString("msg"), TastyToast.LENGTH_LONG, TastyToast.ERROR);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
dialog.CancelProgressDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("empid", new_id);
params.put("fid", id);
params.put("usertype", "FlatUser");
params.put("limit", String.valueOf(limit));
Log.e("params", String.valueOf(params));
return params;
}
};
requestQueue.add(stringRequest);
}
Try adding the following code, both of them need to be true.
mLayoutManager.setStackFromEnd(true);
mLayoutManager.setReverseLayout(true);
From OnCreate() remove your setadapter as your list doesn't have data yet.
and in your onResponse() reverse your listdata before setting it
Collections.reverse(mList);
mAdapter = new GateInfoAdapter(mList, ctx);
mRecyclerView.setAdapter(mAdapter);
I am using OnScrolListener to add items to a ListView in my app .Scrolling is working fine, but i am facing an error . when I scroll to bottom,data add to list ,but position start from top .Please help me
public class Hotel_list_activity extends AppCompatActivity implements View.OnClickListener {
Global global;
ListView hotel_list;
SharedPreferences mpref;
SharedPreferences.Editor ed;
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
TextView checkIn, checkout, number_of_persons_text, number_of_room_text;
LinearLayout hotel_list_back_image;
boolean isLoading = false;
Bundle translateBundle;
int count, Page_inc = 1;
int next;
#TargetApi(Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hotel_list_activity);
global = (Global) getApplicationContext();
mpref = getSharedPreferences("com.example.brightroots.flight_app", Context.MODE_PRIVATE);
init();
startAnim();
GetHotel();
//initList();
hotel_list.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView arg0, int scrollState) {
// If scroll state is touch scroll then set userScrolled
// true
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
isLoading = true;
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// Now check if userScrolled is true and also check if
// the item is end then update list view and set
// userScrolled to false
if (isLoading
&& firstVisibleItem + visibleItemCount == totalItemCount) {
isLoading = false;
loadMore();
}
}
});
}
private void loadMore() {
Log.e("count_value", count + "");
Log.e("count_Page", Page_inc + "");
Page_inc = 2;
if (Page_inc <= count) {
GetHotel();
Log.e("countttttttt_gg", Page_inc + "");
Page_inc = Page_inc + 1;
Log.e("Page_iceeee", Page_inc + "");
isLoading = false;
} else {
/* Page_inc=1;
GetHotel();*/
}
}
//================================================================================= findviewbyid
private void init() {
hotel_list = (ListView) findViewById(R.id.hotel_list_list_view);
checkIn = (TextView) findViewById(R.id.Enter_date1);
checkout = (TextView) findViewById(R.id.Enter_date2);
number_of_persons_text = (TextView) findViewById(R.id.number_of_persons_text);
number_of_room_text = (TextView) findViewById(R.id.number_of_room_text);
hotel_list_back_image = (LinearLayout) findViewById(R.id.hotel_list_back_image);
number_of_persons_text.setText(mpref.getString("adult", ""));
number_of_room_text.setText(mpref.getString("room", ""));
hotel_list_back_image.setOnClickListener(this);
String date = mpref.getString("checkin", "");
String date_out = mpref.getString("checkout", "");
DateFormat targetFormat = new SimpleDateFormat("MMM dd,yyyy");
DateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd");
Date d = null;
Date dd = null;
try {
d = originalFormat.parse(date);
dd = originalFormat.parse(date_out);
} catch (ParseException e) {
e.printStackTrace();
}
String formattedDate = targetFormat.format(d); // 201208
String formattedDate1 = targetFormat.format(dd); // 201208
Log.e("Change format", formattedDate);
Log.e("Change format", formattedDate1);
checkIn.setText(formattedDate);
checkout.setText(formattedDate1);
}
//========================================================================================hotel name
private void GetHotel() {
String url = "http://api.wego.com/hotels/api/search/show/" + global.getSearch() + "?currency_code=" + mpref.getString("currency_code", "") + "&page=" + Page_inc + "&refresh=true&key=12345&ts_code=123";
Log.e("show", url);
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Log.e("Response_____>>", response);
stopAnim();
JSONObject job = null;
try {
job = new JSONObject(response);
String totalcount = job.getString("total_count");
count = Integer.parseInt(job.getString("count"));
String current_page = job.getString("current_page");
JSONArray jo = job.getJSONArray("hotels");
// Log.e("hhhh", "hhhh");
;
for (int i = 0; i < jo.length(); i++) {
JSONObject obj = jo.getJSONObject(i);
HashMap<String, String> hmap = new HashMap<String, String>();
hmap.put("id", obj.getString("id"));
hmap.put("name", obj.getString("name"));
hmap.put("address", obj.getString("address"));
hmap.put("image", obj.getString("image"));
hmap.put("stars", obj.getString("stars"));
//dataItems.add(String.valueOf(hmap));
list.add(hmap);
}
Log.e("dataItemmmmm", list + "");
global.sethoteldetail(list);
// adapter = new Hotel_List_adapter(Hotel_list_activity.this, list);
hotel_list.setAdapter(new Hotel_List_adapter(Hotel_list_activity.this, list));
} catch (JSONException e1) {
e1.printStackTrace();
stopAnim();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Log.e("Response ERROR_____>>", error.toString());
stopAnim();
//pdia.dismiss();
Toast.makeText(Hotel_list_activity.this, "No Internet Connection", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Custom Adapter
public class Hotel_List_adapter extends BaseAdapter {
Context c;
ArrayList<HashMap<String, String>> list;
LayoutInflater inflater;
public Hotel_List_adapter(Context c, ArrayList<HashMap<String, String>> list) {
this.c=c;
this.list=list;
inflater=LayoutInflater.from(c);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder = new Holder();
if (convertView == null) {
convertView = inflater.inflate(R.layout.custom_hotel_list,null);
holder.name=(TextView)convertView.findViewById(R.id.name);
holder.address =(TextView)convertView.findViewById(R.id.address);
holder.img=(ImageView) convertView.findViewById(R.id.img);
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
holder.name.setText(list.get(position).get("name"));
holder.address.setText(list.get(position).get("address"));
String image_string = list.get(position).get("image");//stars
if (image_string.equalsIgnoreCase("null")){
Log.e("no imG", "NO");
holder.img.setImageResource(R.drawable.no_image);
}
else
{
Glide.with(c).load(image_string).into(holder.img);
}
return convertView;
}
class Holder
{
TextView name, address;
}
}
What do you want? You want to scroll List after update List it reached at Top not at same List State? Is it Right?
Please Check this
private void scrollMyListViewToBottom() {
myListView.post(new Runnable() {
#Override
public void run() {
// Select the last row so it will scroll into view...
myListView.setSelection(myListAdapter.getCount() - 1);
}
});
}
check this Please.
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);