I m working on a project in which i have to add the tabs and the data dynamically from the json.
The following is the code in the activity in which i add the tabs
private void getShopDetails() {
coordinatorLayout.setVisibility(View.GONE);
new ProgressDialog(this);
ProgressDialog.show();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(shopDetailsJsonUrl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
SharedPreferences sharedPreferences = getSharedPreferences("ShopDetailsJson", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("sdresponse", response.toString());
editor.apply();
ProgressDialog.dismiss();
coordinatorLayout.setVisibility(View.VISIBLE);
try {
JSONArray shopDetailsArray = response.getJSONArray("shop_details");
JSONObject shopDetailsObj = shopDetailsArray.getJSONObject(0);
shopName = shopDetailsObj.getString("shop_name");
phone = shopDetailsObj.getString("tel");
shopNum = shopDetailsObj.getString("shop_no");
shopAddress = shopDetailsObj.getString("shop_address");
shopImage = shopDetailsObj.getString("featured_image");
Glide.with(getApplicationContext()).load("http://allmartapp.com/appapi/uploads/" + shopImage).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(backdrop);
colLayout.setTitle(shopName);
address.setText("Address - " + shopAddress);
JSONArray tabsArray = response.getJSONArray("category");
if (tabsArray != null) {
categoryId = new int[tabsArray.length()];
for (int i = 0; i < tabsArray.length(); i++) {
JSONObject tabsObj = tabsArray.getJSONObject(i);
tabLayout.addTab(tabLayout.newTab().setText(tabsObj.getString("category_name")));
categoryId[i] = tabsObj.getInt("category_id");
}
tabLayout.setTabGravity(TabLayout.GRAVITY_CENTER);
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
pager.setAdapter(pagerAdapter);
pager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
pager.setOffscreenPageLimit(tabLayout.getTabCount());
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
pager.setCurrentItem(tab.getPosition());
ShopDetailsTabsFragment.sgetid(categoryId[tab.getPosition()]);
Log.d("CATIID", categoryId[tab.getPosition()] + "");
pager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
ProgressDialog.dismissWithError();
}
});
int socketTimeout = 30000;//30 seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
jsonObjectRequest.setRetryPolicy(policy);
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
}
Following is the code of fragment
public class ShopDetailsTabsFragment extends Fragment {
RecyclerView recyclerView;
boolean isViewShown = true;
CategoryListItemsAdapter shopListRvAdapters;
private String shopDetailsJsonUrl = "http://allmartapp.com/appapi/json/get_shop_details_by_shop_id/";
private String baseshopDetailsJsonUrl = "http://allmartapp.com/appapi/json/get_shop_details_by_shop_id/";
ArrayList<CategoryItemsListModel> arrayList = new ArrayList<>();
static int catid = 0;
int shopId;
Boolean isdataloaded = false;
ProgressBar progressBar;
private boolean fragmentResume = false;
private boolean fragmentVisible = true;
private boolean fragmentOnCreated = false;
public ShopDetailsTabsFragment() {
// 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_shop_details_tabs, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.rv);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));
progressBar = (ProgressBar) v.findViewById(R.id.progressBarTabs);
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("SHOPID", Context.MODE_PRIVATE);
shopId = sharedPreferences.getInt("shopid", 0);
if (!fragmentResume && fragmentVisible) { //only when first time fragment is created
makeJsonRequest();
}
shopListRvAdapters = new CategoryListItemsAdapter(arrayList, getActivity());
recyclerView.setAdapter(shopListRvAdapters);
return v;
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && isResumed()) { // only at fragment screen is resumed
fragmentResume = true;
fragmentVisible = false;
fragmentOnCreated = true;
makeJsonRequest();
} else if (isVisibleToUser) { // only at fragment onCreated
fragmentResume = false;
fragmentVisible = true;
fragmentOnCreated = true;
} else if (!isVisibleToUser && fragmentOnCreated) {// only when you go out of fragment screen
fragmentVisible = false;
fragmentResume = false;
}
// if (getView() != null) {
// isViewShown = true;
// makeJsonRequest();
//
//
// // fetchdata() contains logic to show data when page is selected mostly asynctask to fill the data
// } else {
// isViewShown = false;
// }
}
public static void sgetid(int cat) {
catid = cat;
}
private void getShopCat() {
recyclerView.setAdapter(null);
shopDetailsJsonUrl += shopId;
arrayList.clear();
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(shopDetailsJsonUrl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
isdataloaded = true;
Log.d("JSON", response.toString());
try {
JSONArray categoryArray = response.getJSONArray("category");
if (arrayList != null) {
if (arrayList.size() > 0)
arrayList.clear();
}
for (int i = 0; i < categoryArray.length(); i++) {
JSONObject catObj = categoryArray.getJSONObject(i);
int category_id = catObj.getInt("category_id");
if (category_id == catid) {
JSONArray productArray = catObj.getJSONArray("product");
for (int j = 0; j < productArray.length(); j++) {
JSONObject productObj = productArray.getJSONObject(j);
String name = productObj.getString("product_name");
String image = "http://allmartapp.com/appapi/uploads/" + productObj.getString("image_name");
int id = productObj.getInt("product_id");
int price = productObj.getInt("price");
arrayList.add(new CategoryItemsListModel(id, image, name, price));
}
shopListRvAdapters = new CategoryListItemsAdapter(arrayList, getActivity());
recyclerView.setAdapter(shopListRvAdapters);
shopListRvAdapters.notifyDataSetChanged();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
int socketTimeout = 30000;//30 seconds - change to what you want
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
jsonObjectRequest.setRetryPolicy(policy);
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
shopDetailsJsonUrl = baseshopDetailsJsonUrl;
}
void makeJsonRequest() {
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("ShopDetailsJson", Context.MODE_PRIVATE);
String response = sharedPreferences.getString("sdresponse", null);
try {
JSONArray jsonArray = new JSONObject(response).getJSONArray("category");
Log.d("TBASARRAY", jsonArray + "");
progressBar.setVisibility(View.GONE);
if (arrayList != null) {
if (arrayList.size() > 0)
arrayList.clear();
}
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject catObj = jsonArray.getJSONObject(i);
int category_id = catObj.getInt("category_id");
if (category_id == catid) {
JSONArray productArray = catObj.getJSONArray("product");
for (int j = 0; j < productArray.length(); j++) {
JSONObject productObj = productArray.getJSONObject(j);
String name = productObj.getString("product_name");
String image = "http://allmartapp.com/appapi/uploads/" + productObj.getString("image_name");
int id = productObj.getInt("product_id");
int price = productObj.getInt("price");
arrayList.add(new CategoryItemsListModel(id, image, name, price));
}
shopListRvAdapters = new CategoryListItemsAdapter(arrayList, getActivity());
recyclerView.setAdapter(shopListRvAdapters);
shopListRvAdapters.notifyDataSetChanged();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
recyclerView.addOnItemTouchListener(new CategoryListActivity.RecyclerTouchListener(getActivity(), recyclerView, new CategoryListActivity.OnClickListener() {
#Override
public void onClick(View v, int position) {
int id = arrayList.get(position).getId();
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("CATITEMID", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("catitemid", id);
editor.apply();
startActivity(new Intent(getActivity(), ItemDetailView.class));
}
#Override
public void onLongClick(View v, int position) {
}
}));
// shopDetailsJsonUrl = baseshopDetailsJsonUrl;
}
My problem is that the function makeJsonRequest() is only called when i swipe the tabs. Actually the onCreateview method is not called unless i swipe the tabs.
And also, when i press back and come back to that activity, the data of that tab that was left when pressing back appears at the first tab.
Any help/ guidance will be appreciated.
I would suggest you looking at theViewPager's setOffscreenPageLimit(int) method.
It controls how many tabs left/right must be preinitialised before showing them.
As for 'back' problem. Probably the first fragment is 'added' to the activity Backstack, and the other ones are 'replaced'. Therefore calling onBackPressed of Activity is just going back in the Backstack.
Related
I tried to build an app that have 5 fragment that displayed using bottom navigation view. I use volley to get the data from database. i have a problem with calling the data. at fragment A. i call the web service and got some data and then display it using recyclerview. But if i move to another fragment ( lets say fragment B) and went back to the fragment A. the data is lost and it just show the standard ui like search widget,spinner widget. All i want to ask is :
where should i put the code to call web service for all my fragment. On the activity that handle the fragment or just on the fragment?
why volley doesn't call data again when i back to the fragment?
this is the code of my mainactivity that contain bottom navigation view with 5 fragments:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(isNetworkStatusAvialable (getApplicationContext())) {
bottomNavigationView=(BottomNavigationView)findViewById(R.id.main_nav);
frameLayout=(FrameLayout) findViewById(R.id.main_frame);
herbal= new herbal();
crude = new crude();
database=new database();
analysis=new analysis();
compound=new compound();
setFragment(herbal);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId())
{
case R.id.nav_herbal:
setFragment(herbal);
return true;
case R.id.nav_crude:
setFragment(crude);
return true;
case R.id.nav_database:
setFragment(database);
return true;
case R.id.nav_analysis:
setFragment(analysis);
return true;
case R.id.nav_compound:
setFragment(compound);
return true;
default:
return false;
}
}
});
} else {
Toast.makeText(getApplicationContext(), "internet is not avialable", Toast.LENGTH_SHORT).show();
}
}
private boolean isNetworkStatusAvialable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null)
{
NetworkInfo netInfos = connectivityManager.getActiveNetworkInfo();
if(netInfos != null)
if(netInfos.isConnected())
return true;
}
return false;
}
private void setFragment(Fragment fragment) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_frame,fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
this is the example in my fragment which calling web service and then display it using recycler view:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_herbal, container, false);
herbalModels = new ArrayList<>();
kampoModels = new ArrayList<>();
searchHerbal = (EditText) rootView.findViewById(R.id.search_herbal);
searchHerbal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
searchHerb();
}
});
loadData = (ProgressBar) rootView.findViewById(R.id.loadRecyclerView);
RequestQueue queue = MySingleton.getInstance(this.getActivity().getApplicationContext()).getRequestQueue();
sortData(rootView);
get20DataJamu();
get20DataKampo();
StartRecyclerViewJamu(rootView);
return rootView;
}
private void searchHerb() {
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
searchHerbs searchHerbs = new searchHerbs();
ft.replace(R.id.main_frame, searchHerbs);
ft.commit();
}
private void StartRecyclerViewKampo(View rootView) {
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview_herbal);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
// use a linear layout manager
mRecyclerView.setLayoutManager(mLayoutManager);
kampoAdapter = new kampoAdapter(mRecyclerView, getActivity(), kampoModels);
mRecyclerView.setAdapter(kampoAdapter);
kampoAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
kampoModels.add(null);
kampoAdapter.notifyItemInserted(kampoModels.size() - 1);
handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
kampoModels.remove(kampoModels.size() - 1);
kampoAdapter.notifyItemRemoved(kampoModels.size());
//add items one by one
int start = kampoModels.size();
int end = start + 20;
loadMoreKampo(start, end);
}
}, 5000);
}
});
}
private void loadMoreKampo(final int start, final int end) {
String url = "https://jsonplaceholder.typicode.com/photos";
JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.d(TAG, "Onresponse" + jsonArray.toString());
for (int i = start; i < end; i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Log.d(TAG,"jsonobject"+jsonObject);
kampoModels.add(
new kampoModel(
jsonObject.getString("title"),
"Khasiat",
jsonObject.getString("albumId"),
jsonObject.getString("id"),
jsonObject.getString("thumbnailUrl")
)
);
kampoAdapter.notifyItemInserted(kampoModels.size());
} catch (JSONException e) {
}
}
kampoAdapter.setLoaded();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d(TAG, "Onerror" + volleyError.toString());
}
});
MySingleton.getInstance(getActivity()).addToRequestQueue(request);
}
private void get20DataKampo() {
String url = "https://jsonplaceholder.typicode.com/photos";
JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.d(TAG, "Onresponsekampo" + jsonArray.toString());
Log.d(TAG, "lengthresponse" + jsonArray.length());
for (int i = 0; i < 20; i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Log.d(TAG,"jsonobject"+jsonObject);
kampoModels.add(
new kampoModel(
jsonObject.getString("title"),
"Khasiat",
jsonObject.getString("albumId"),
jsonObject.getString("id"),
jsonObject.getString("thumbnailUrl")
)
);
} catch (JSONException e) {
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d(TAG, "Onerrorkampo" + volleyError.toString());
}
});
MySingleton.getInstance(getActivity()).addToRequestQueue(request);
}
private void StartRecyclerViewJamu(final View rootView) {
mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerview_herbal);
mRecyclerView.setVisibility(View.GONE);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(getActivity());
// use a linear layout manager
mRecyclerView.setLayoutManager(mLayoutManager);
// create an Object for Adapter
mAdapter = new herbalAdapter(mRecyclerView, getActivity(), herbalModels);
mRecyclerView.setAdapter(mAdapter);
loadData.setVisibility(View.GONE);
mRecyclerView.setVisibility(View.VISIBLE);
mAdapter.notifyDataSetChanged();
mAdapter.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
//add null , so the adapter will check view_type and show progress bar at bottom
herbalModels.add(null);
mAdapter.notifyItemInserted(herbalModels.size() - 1);
handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// remove progress item
herbalModels.remove(herbalModels.size() - 1);
mAdapter.notifyItemRemoved(herbalModels.size());
//add items one by one
int start = herbalModels.size();
int end = start + 20;
loadMoreJamu(start, end);
}
}, 5000);
}
});
}
private void get20DataJamu() {
String url = "https://jsonplaceholder.typicode.com/posts";
JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.d(TAG, "Onresponse" + jsonArray.toString());
Log.d(TAG, "lengthonresponse" + jsonArray.length());
for (int i = 0; i < 20; i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Log.d(TAG,"jsonobject"+jsonObject);
herbalModels.add(
new herbalModel(
jsonObject.getString("title"),
"Khasiat",
jsonObject.getString("userId"),
jsonObject.getString("id"),
jsonObject.getString("body")
)
);
} catch (JSONException e) {
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d(TAG, "Onerror" + volleyError.toString());
}
});
MySingleton.getInstance(getActivity()).addToRequestQueue(request);
}
private void loadMoreJamu(final int start, final int end) {
String url = "https://jsonplaceholder.typicode.com/posts";
JsonArrayRequest request = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
Log.d(TAG, "Onresponse" + jsonArray.toString());
for (int i = start; i < end; i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// Log.d(TAG,"jsonobject"+jsonObject);
herbalModels.add(
new herbalModel(
jsonObject.getString("title"),
"Khasiat",
jsonObject.getString("userId"),
jsonObject.getString("id"),
jsonObject.getString("body")
)
);
mAdapter.notifyItemInserted(herbalModels.size());
} catch (JSONException e) {
}
}
mAdapter.setLoaded();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d(TAG, "Onerror" + volleyError.toString());
}
});
MySingleton.getInstance(getActivity()).addToRequestQueue(request);
}
private void sortData(final View rootView) {
final Spinner spinner = (Spinner) rootView.findViewById(R.id.filter_herbal);
// Create an ArrayAdapter using the string array and a default spinner layout
List<categoriesHerbal> itemList = new ArrayList<categoriesHerbal>();
itemList.add(
new categoriesHerbal(
"1",
"Jamu"
)
);
itemList.add(
new categoriesHerbal(
"2",
"Kampo"
)
);
ArrayAdapter<categoriesHerbal> spinnerAdapter = new ArrayAdapter<categoriesHerbal>(getActivity(), android.R.layout.simple_spinner_item, itemList);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Specify the layout to use when the list of choices appears
// Apply the adapter to the spinner
spinner.setAdapter(spinnerAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
categoriesHerbal selectedValue = (categoriesHerbal) parent.getItemAtPosition(position);
String categories = (String) selectedValue.getCategories();
String idCategories = (String) selectedValue.getIdCategories();
StartRecyclerViewJamu(rootView);
} else {
categoriesHerbal selectedValue = (categoriesHerbal) parent.getItemAtPosition(position);
String categories = (String) selectedValue.getCategories();
String idCategories = (String) selectedValue.getIdCategories();
StartRecyclerViewKampo(rootView);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
move your data code in separate class and call it wherever needed.
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId())
{
case R.id.nav_herbal:
setFragment(herbal);
return true;
case R.id.nav_crude:
setFragment(crude);
return true;
case R.id.nav_database:
setFragment(database);
return true;
case R.id.nav_analysis:
setFragment(analysis);
return true;
case R.id.nav_compound:
setFragment(compound);
return true;
/*default:
return false;*/ //no need for this one
}
return true; /*you forget'it*/
}
I am trying to implement Ranking for city, country and Worldwide in my App while fetching data using Volley as JSON response and loading it in seperate ArrayList. My problem is that it loads data in arrayList but pagerAdapter.notifyDataSetChanged() does not reflect the new data until you manual rotate mobile orientation and onCreate() or onResume() is called automatically. Bellow is the code for RatingActivity.java. and BlankFragment.java to load cards(Recyclers).
RatingActivity.java
public class RatingActivity extends AppCompatActivity {
String user,aun, aps;
int lst=0;
public static ArrayList<String> emailst1, ranklst1, namelst1, ratinglst1;
public static ArrayList<String> emailst2, ranklst2, namelst2, ratinglst2;
public static ArrayList<String> emailst3, ranklst3, namelst3, ratinglst3;
public static PagerAdapter pagerAdapter;
TextView txtmyrank, txtmyname, txtmyrating;
public static int ran[]={0,0,0};
public static int tabpost;
public String[] usdtl={"","","",""};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rating);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
javalib jl = new javalib();
txtmyrank=(TextView)findViewById(R.id.txtmyrank);
txtmyname=(TextView)findViewById(R.id.txtmyname);
txtmyrating=(TextView)findViewById(R.id.txtmyrating);
aun = jl.HelloJNI();
aps = jl.HiJNI();
aps=aps.substring(0,aps.length()-1);
DBHelper db = new DBHelper(this);
//Log.e("Called","yeh");
SessionM session = new SessionM(this);
// get user data from session
HashMap<String, String> user;
user = session.getUserDetails();
String Usremail = user.get(SessionM.KEY_EMAIL);
usdtl = db.getUserDetail(Usremail);
String loc = usdtl[1];
emailst1 = new ArrayList<String>();
ranklst1 = new ArrayList<String>();
namelst1 = new ArrayList<String>();
ratinglst1 = new ArrayList<String>();
emailst2 = new ArrayList<String>();
ranklst2 = new ArrayList<String>();
namelst2 = new ArrayList<String>();
ratinglst2 = new ArrayList<String>();
emailst3 = new ArrayList<String>();
ranklst3 = new ArrayList<String>();
namelst3 = new ArrayList<String>();
ratinglst3 = new ArrayList<String>();
String[] address={"",""};
address[0]=loc.substring(0,loc.indexOf(','));
address[1]=loc.substring(loc.indexOf(',')+1,loc.length());
txtmyname.setText(usdtl[2]);
txtmyrating.setText(usdtl[3]);
//////////////////////////// update rank///////////////////////////////////////////////////////////////
String url = "http://abcd.net/getRank.php?uname=" + aun + "&password=" + aps + "&usrname=" + usdtl[0] +"&location1="+address[0]+"&location2="+address[1]+"&app=0";
Log.e("Url", url);
RequestQueue requestQueue = Volley.newRequestQueue(RatingActivity.this);
JsonArrayRequest jar4 = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
Boolean isUpdate = response.getJSONObject(0).has("rank");
if (isUpdate == true) {
int lng = 0, il = 0;
lng = response.length();
while (il < lng) {
Log.e("Rank response", response.toString());
ran[il]=Integer.parseInt(response.getJSONObject(il).getString("rank"));
il++;
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
// Adding request to request queue
requestQueue.add(jar4);
url = "http://abcd.net/ctranking.php?uname=" + aun + "&password=" + aps + "&usrname=" + usdtl[0] +"&location="+address[0]+"&cpage=1&app=0";
requestQueue = Volley.newRequestQueue(RatingActivity.this);
JsonArrayRequest jar1 = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
Boolean isUpdate = response.getJSONObject(0).has("username");
Boolean isId = response.getJSONObject(0).has("randno");
if (isUpdate == true) {
if (isId == true) {
int lng = 0, il = 0;
lng = response.length();
ranklst1 = new ArrayList<String>();
namelst1 = new ArrayList<String>();
ratinglst1 = new ArrayList<String>();
while (il < lng) {
ranklst1.add((il+1)+"");
emailst1.add(response.getJSONObject(il).getString("username"));
namelst1.add(response.getJSONObject(il).getString("name"));
ratinglst1.add(response.getJSONObject(il).getString("randno"));
il++;
}
lst++;
if(lst==3)
setList();
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
// Adding request to request queue
requestQueue.add(jar1);
url = "http://abcd.net/cntranking.php?uname=" + aun + "&password=" + aps + "&usrname=" + usdtl[0] +"&location="+address[1]+"&cpage=1&app=0";
RequestQueue requestQueue2 = Volley.newRequestQueue(RatingActivity.this);
JsonArrayRequest jar2 = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
Boolean isUpdate = response.getJSONObject(0).has("username");
Boolean isId = response.getJSONObject(0).has("randno");
if (isUpdate == true) {
if (isId == true) {
int lng = 0, il = 0;
lng = response.length();
ranklst2 = new ArrayList<String>();
namelst2 = new ArrayList<String>();
ratinglst2 = new ArrayList<String>();
while (il < lng) {
ranklst2.add((il+1)+"");
emailst2.add(response.getJSONObject(il).getString("username"));
namelst2.add(response.getJSONObject(il).getString("name"));
ratinglst2.add(response.getJSONObject(il).getString("randno"));
il++;
}
lst++;
if(lst==3)
setList();
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
// Adding request to request queue
requestQueue2.add(jar2);
url = "http://abcd.net/wwranking.php?uname=" + aun + "&password=" + aps + "&usrname=" + usdtl[0] +"&cpage=1&app=0";
RequestQueue requestQueue3 = Volley.newRequestQueue(RatingActivity.this);
JsonArrayRequest jar3 = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
Boolean isUpdate = response.getJSONObject(0).has("username");
Boolean isId = response.getJSONObject(0).has("randno");
if (isUpdate == true) {
if (isId == true) {
int lng = 0, il = 0;
lng = response.length();
ranklst3 = new ArrayList<String>();
namelst3 = new ArrayList<String>();
ratinglst3 = new ArrayList<String>();
while (il < lng) {
ranklst3.add((il+1)+"");
emailst3.add(response.getJSONObject(il).getString("username"));
namelst3.add(response.getJSONObject(il).getString("name"));
ratinglst3.add(response.getJSONObject(il).getString("randno"));
il++;
}
lst++;
if(lst==3)
setList();
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
// Adding request to request queue
requestQueue3.add(jar3);
/////////////////////////////////////////////////////////////////////////////////////////////////////
}
public void setList(){
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
pagerAdapter =
new PagerAdapter(getSupportFragmentManager(), RatingActivity.this);
viewPager.setAdapter(pagerAdapter);
// Give the TabLayout the ViewPager
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
// Iterate over all tabs and set the custom view
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(pagerAdapter.getTabView(i));
}
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
switch(position){
case 0:
ran[0]=emailst1.indexOf(usdtl[0])+1;
break;
case 1:
ran[1]=emailst2.indexOf(usdtl[0])+1;
break;
case 2:
ran[2]=emailst3.indexOf(usdtl[0])+1;
break;
}
txtmyrank.setText(ran[position]+"");
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
class PagerAdapter extends FragmentPagerAdapter {
String tabTitles[] = new String[] { "શહેર", "દેશ", "વૈશ્વિક" };
Context context;
public PagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return tabTitles.length;
}
#Override
public Fragment getItem(int position) {
Bundle extra = new Bundle();
switch (position) {
case 0:
tabpost=1;
break;
case 1:
tabpost=2;
break;
case 2:
tabpost=3;
break;
}
extra.putString("position", tabpost+"");
BlankFragment bf = new BlankFragment();
bf.setArguments(extra);
return bf;
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
public View getTabView(int position) {
View tab = LayoutInflater.from(RatingActivity.this).inflate(R.layout.custom_tab, null);
TextView tv = (TextView) tab.findViewById(R.id.custom_text);
tv.setText(tabTitles[position]);
return tab;
}
}
}
Following is the code for BlankFragment.java
public class BlankFragment extends Fragment {
int tabpost;
Boolean userScrolled=false;
ArrayList<String> alstname, alstrank, alstrating;
public BlankFragment(){
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tabpost=Integer.parseInt(getArguments().getString("position"));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
final RecyclerView rv = (RecyclerView) rootView.findViewById(R.id.rv_recycler_view);
rv.setHasFixedSize(true);
switch (tabpost) {
case 1:
alstname = RatingActivity.namelst1;
alstrank = RatingActivity.ranklst1;
alstrating = RatingActivity.ratinglst1;
break;
case 2:
alstname = RatingActivity.namelst2;
alstrank = RatingActivity.ranklst2;
alstrating = RatingActivity.ratinglst2;
break;
case 3:
alstname = RatingActivity.namelst3;
alstrank = RatingActivity.ranklst3;
alstrating = RatingActivity.ratinglst3;
break;
}
MyAdapter adapter = new MyAdapter(alstname, alstrank, alstrating);
rv.setAdapter(adapter);
final LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
userScrolled = true;
}
}
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
Log.e("dx, dy", dx+" "+dy);
int visibleItemCount = llm.getChildCount();
int totalItemCount = llm.getItemCount();
int pastVisiblesItems = llm.findFirstVisibleItemPosition();
if (userScrolled
&& (visibleItemCount + pastVisiblesItems) == totalItemCount) {
userScrolled = false;
///////////////// updating rank list////////////////////////////////////
switch (tabpost) {
case 1:
Log.e("Updating","Recycler View1"+tabpost);
updatelist(1, totalItemCount);
break;
case 2:
Log.e("Updating","Recycler View2"+tabpost);
updatelist(2, totalItemCount);
break;
case 3:
Log.e("Updating","Recycler View3"+tabpost);
updatelist(3, totalItemCount);
break;
}
/////////////////////////////////////////////////////////////////////////
}
}
});
rv.setLayoutManager(llm);
return rootView;
}
void updatelist(int post, int item){
javalib jl = new javalib();
String aun = jl.HelloJNI();
String aps = jl.HiJNI();
aps=aps.substring(0,aps.length()-1);
DBHelper db = new DBHelper(getContext());
//Log.e("Called","yeh");
SessionM session = new SessionM(getContext());
// get user data from session
HashMap<String, String> user;
user = session.getUserDetails();
String Usremail = user.get(SessionM.KEY_EMAIL);
String[] usdtl = db.getUserDetail(Usremail);
String loc = usdtl[1];
String[] address={"",""};
address[0]=loc.substring(0,loc.indexOf(','));
address[1]=loc.substring(loc.indexOf(',')+1,loc.length());
int page1;
if(item==0)
page1=1;
else
page1=(item-1)/3 + 2;
String url = "http://abcd.net/ctranking.php?uname=" + aun + "&password=" + aps + "&usrname=" + usdtl[0] +"&location="+address[0]+"&cpage="+page1+"&app=0";
Log.e("url", url);
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
JsonArrayRequest jar1 = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
Boolean isUpdate = response.getJSONObject(0).has("username");
Boolean isId = response.getJSONObject(0).has("randno");
if (isUpdate == true) {
if (isId == true) {
int lng = 0, il = 0;
lng = response.length();
while (il < lng) {
RatingActivity.ranklst1.add((RatingActivity.ranklst1.size()+1)+"");
RatingActivity.emailst1.add(response.getJSONObject(il).getString("username"));
RatingActivity.namelst1.add(response.getJSONObject(il).getString("name"));
RatingActivity.ratinglst1.add(response.getJSONObject(il).getString("randno"));
il++;
}
RatingActivity.pagerAdapter.notifyDataSetChanged();
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
// Adding request to request queue
url = "http://abcd.net/cntranking.php?uname=" + aun + "&password=" + aps + "&usrname=" + usdtl[0] +"&location="+address[1]+"&cpage="+page1+"&app=0";
Log.e("url", url);
RequestQueue requestQueue2 = Volley.newRequestQueue(getContext());
JsonArrayRequest jar2 = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
Boolean isUpdate = response.getJSONObject(0).has("username");
Boolean isId = response.getJSONObject(0).has("randno");
if (isUpdate == true) {
if (isId == true) {
int lng = 0, il = 0;
lng = response.length();
/*RatingActivity.ranklst2 = new ArrayList<String>();
RatingActivity.namelst2 = new ArrayList<String>();
RatingActivity.ratinglst2 = new ArrayList<String>();*/
while (il < lng) {
RatingActivity.ranklst2.add((RatingActivity.ranklst2.size()+1)+"");
RatingActivity.emailst2.add(response.getJSONObject(il).getString("username"));
RatingActivity.namelst2.add(response.getJSONObject(il).getString("name"));
RatingActivity.ratinglst2.add(response.getJSONObject(il).getString("randno"));
il++;
}
RatingActivity.pagerAdapter.notifyDataSetChanged();
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
url = "http://abcd.net/wwranking.php?uname=" + aun + "&password=" + aps + "&usrname=" + usdtl[0] +"&cpage="+page1+"&app=0";
Log.e("url", url);
RequestQueue requestQueue3 = Volley.newRequestQueue(getContext());
JsonArrayRequest jar3 = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
Boolean isUpdate = response.getJSONObject(0).has("username");
Boolean isId = response.getJSONObject(0).has("randno");
if (isUpdate == true) {
if (isId == true) {
int lng = 0, il = 0;
lng = response.length();
while (il < lng) {
RatingActivity.ranklst3.add((RatingActivity.ranklst3.size()+1)+"");
RatingActivity.emailst3.add(response.getJSONObject(il).getString("username"));
RatingActivity.namelst3.add(response.getJSONObject(il).getString("name"));
RatingActivity.ratinglst3.add(response.getJSONObject(il).getString("randno"));
il++;
}
RatingActivity.pagerAdapter.notifyDataSetChanged();
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
switch (post) {
case 1: requestQueue.add(jar1);
break;
// Adding request to request queue
case 2:
requestQueue2.add(jar2);
break;
// Adding request to request queue
case 3: requestQueue3.add(jar3);
break;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
}
}
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);
How can i pass the position of item using intent to start a new activity?
I want to start a new activity called single which displays the rating of the movie correspondingly..pls help
I have been trying this for the past two days.
Here is the code:
public class NowPlaying extends Fragment {
private static final String TAG = NowPlaying.class.getSimpleName();
// Movies json url
private static final String url = "http://private-8149-themoviedb.apiary-mock.com/3/movie/now_playing?api_key=";
private ProgressDialog pDialog;
private List<NowPlayingInfo> bottom = new ArrayList<NowPlayingInfo>() ;
NowPlayingAdapter adapter;
RecyclerView recyclerView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_main, container, false);
ActionBar toolbar = ((AppCompatActivity) getActivity()).getSupportActionBar();
toolbar.setTitle("Now playing");
recyclerView = (RecyclerView) v.findViewById(R.id.cardList);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(linearLayoutManager);
adapter = new NowPlayingAdapter(getActivity(), bottom);
recyclerView.setAdapter(adapter);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...");
pDialog.show();
adapter.SetOnItemClickListener(new NowPlayingAdapter.OnItemClickListener() {
#Override
public void onItemClick(View v, int position) {
// do something with position
Intent i = new Intent(v.getContext(), Single.class);
//pass the position of the item to single class
v.getContext().startActivity(i);
}
});
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
hidePDialog();
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
NowPlayingInfo trailer = new NowPlayingInfo();
trailer.setTitle(jsonObject.getString("original_title"));
String iss = "http://image.tmdb.org/t/p/w500" + jsonObject.getString("poster_path") ;
trailer.setImage(iss);
bottom.add(trailer);
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
AppController.getInstance().addToRequestQueue(jsonObjectRequest);
return v;
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
adapter.SetOnItemClickListener(new NowPlayingAdapter.OnItemClickListener() {
#Override
public void onItemClick(View v, int position) {
NowPlayingInfo _nowPlaying = bottom.get(position);
// do something with position
Intent i = new Intent(v.getContext(), Single.class);
//pass the position of the item to single class
i.putExtra("ISS", _nowPlaying.getImage()); //you can put your current playing info.
i.putExtra("POSITION", position); //you can put your position to next activity.
v.getContext().startActivity(i);
}
});
Add this in your SingleInfo Class.
String _rating = "";
public String get_rating() {
return _rating;
}
public void set_rating(String _rating) {
this._rating = _rating;
}
Add this in your Single class -
int _currentPos = 0 ; //Global variable .
_currentPos = getIntent().getIntExtra("position", 0);// paste this in onCreate()
Add this code in onResponse of Single Class -
try {
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
SingleInfo s = new SingleInfo();
s.set_rating(jsonObject.getString("rating"));
single.add(s);
}
//changed by Shoeb
SingleInfo _singleInfo = single.get(_currentPos); //position from previous activity
textView.setText(_singleInfo.get_rating());
//end changes
} catch (JSONException e) {
e.printStackTrace();
}
Add an extra to your intent
i.putExtra("position",position);
And on the other activity:
getIntent().getIntExtra("position", 0);