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;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
}
}
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*/
}
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 developing the chatbot app. I am using the RecycleView to render the chat of user and bot. I have to show the user listview or text response depend upon his query. All is working until my RecyclerView get's scroll. Whenever my RecyclerView gets scroll it changes the item position. I search a lot and applied every solution but not able to solve my issue.
here is my activity.java
public class HomeActivity extends AppCompatActivity implements AIListener,
View.OnClickListener {
private RecyclerView recyclerView;
private ChatAdapter mAdapter;
LinearLayoutManager layoutManager;
private ArrayList<Message> messageArrayList;
private EditText inputMessage;
private RelativeLayout btnSend;
Boolean flagFab = true;
PaytmPGService service = null;
Map<String, String> paytmparam = new HashMap<>();
PrefManager prefManager;
private AIService aiService;
AIDataService aiDataService;
AIRequest aiRequest;
Gson gson;
String food_dish = " ";
double price = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, 1);
inputMessage = findViewById(R.id.editText_ibm);
btnSend = findViewById(R.id.addBtnibm);
recyclerView = findViewById(R.id.recycler_view_ibm);
messageArrayList = new ArrayList<>();
mAdapter = new ChatAdapter(this,messageArrayList);
prefManager = new PrefManager(this);
GsonBuilder gsonBuilder = new GsonBuilder();
gson = gsonBuilder.create();
layoutManager = new LinearLayoutManager(this);
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.setItemAnimator(new DefaultItemAnimator());
mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onItemRangeInserted(int positionStart, int itemCount) {
super.onItemRangeInserted(positionStart, itemCount);
int msgCount = mAdapter.getItemCount();
int lastVisiblePosition = layoutManager.findLastCompletelyVisibleItemPosition();
if (lastVisiblePosition == -1 ||
(positionStart >= (msgCount - 1) &&
lastVisiblePosition == (positionStart - 1))) {
recyclerView.scrollToPosition(positionStart);
}
}
});
recyclerView.setAdapter(mAdapter);
this.inputMessage.setText("");
final AIConfiguration configuration = new AIConfiguration("cabc4b7b9c20409aa7ffb1b3d5fe1243",
AIConfiguration.SupportedLanguages.English,
AIConfiguration.RecognitionEngine.System);
aiService = AIService.getService(this, configuration);
aiService.setListener(this);
aiDataService = new AIDataService(configuration);
aiRequest = new AIRequest();
btnSend.setOnClickListener(this);
inputMessage.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
ImageView fab_img = findViewById(R.id.fab_img_ibm);
Bitmap img = BitmapFactory.decodeResource(getResources(), R.drawable.ic_send_white_24dp);
Bitmap img1 = BitmapFactory.decodeResource(getResources(), R.drawable.ic_mic_white_24dp);
if (s.toString().trim().length() != 0 && flagFab) {
ImageViewAnimatedChange(HomeActivity.this, fab_img, img);
flagFab = false;
} else if (s.toString().trim().length() == 0) {
ImageViewAnimatedChange(HomeActivity.this, fab_img, img1);
flagFab = true;
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
public void ImageViewAnimatedChange(Context c, final ImageView v, final Bitmap new_image) {
final Animation anim_out = AnimationUtils.loadAnimation(c, R.anim.zoom_out);
final Animation anim_in = AnimationUtils.loadAnimation(c, R.anim.zoom_in);
anim_out.setAnimationListener(new Animation.AnimationListener()
{
#Override public void onAnimationStart(Animation animation) {}
#Override public void onAnimationRepeat(Animation animation) {}
#Override public void onAnimationEnd(Animation animation)
{
v.setImageBitmap(new_image);
anim_in.setAnimationListener(new Animation.AnimationListener() {
#Override public void onAnimationStart(Animation animation) {}
#Override public void onAnimationRepeat(Animation animation) {}
#Override public void onAnimationEnd(Animation animation) {}
});
v.startAnimation(anim_in);
}
});
v.startAnimation(anim_out);
}
#Override
public void onClick(View v) {
final String inputmessage = this.inputMessage.getText().toString().trim();
if(!inputmessage.equals("")){
new AsyncTask<String, Void, AIResponse>(){
private AIError aiError;
#Override
protected AIResponse doInBackground(final String... params) {
final AIRequest request = new AIRequest();
String query = params[0];
if (!TextUtils.isEmpty(query))
request.setQuery(query);
try {
return aiDataService.request(request);
} catch (final AIServiceException e) {
aiError = new AIError(e);
return null;
}
}
#Override
protected void onPostExecute(final AIResponse response) {
if (response != null) {
onResult(response);
} else {
onError(aiError);
}
}
}.execute(inputmessage);
}else {
aiService.startListening();
}
inputMessage.setText("");
}
#Override
public void onResult(AIResponse response) {
int itemNumber = 0;
Log.d("dialogeflow response",response.toString());
try {
JSONObject AIResponse = new JSONObject(gson.toJson(response));
Log.d("json response",AIResponse.toString());
final JSONObject result = AIResponse.getJSONObject("result");
JSONArray contexts = result.getJSONArray("contexts");
final JSONObject fulfillment = result.getJSONObject("fulfillment");
if(contexts.length()>0) {
for(int i = 0;i<contexts.length();i++) {
JSONObject context_items = contexts.getJSONObject(i);
JSONObject paramters = context_items.getJSONObject("parameters");
if (paramters.has("Cuisine")) {
prefManager.setCuisinetype(paramters.getString("Cuisine"));
} else if (paramters.has("Restaurants_name")) {
prefManager.setRestaurant_name(paramters.getString("Restaurants_name"));
}
if (paramters.has("number") && !paramters.getString("number").equals("") && paramters.has("Food_Dishes") && !paramters.getString("Food_Dishes").equals("")) {
itemNumber = Integer.parseInt(paramters.getString("number"));
if (itemNumber <= 2 && price !=0) {
price = 300 + (int) (Math.random() * ((1400 - 300) + 1));
} else {
price = 600 + (int) (Math.random() * ((2200 - 600) + 1));
}
food_dish = paramters.getString("Food_Dishes");
}
}
}
final double finalPrice = price;
final int finalItemNumber = itemNumber;
if(!result.getString("resolvedQuery").matches("payment is done successfully")) {
Message usermsg = new Message();
usermsg.setMessage(result.getString("resolvedQuery"));
usermsg.setId("1");
messageArrayList.add(usermsg);
mAdapter.notifyDataSetChanged();
if (fulfillment.has("speech")) {
Log.d("response of speech", fulfillment.getString("speech"));
if (!fulfillment.getString("speech").equals("") && fulfillment.getString("speech") != null) {
final String speech = fulfillment.getString("speech");
if (fulfillment.getString("speech").matches("Redirecting you to the Pay-Tm site")) {
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
Message outMessage = new Message();
outMessage.setMessage(speech);
outMessage.setId("2");
messageArrayList.add(outMessage);
mAdapter.notifyDataSetChanged();
getpaytm_params((int) price);
}
}, 2000);
} else {
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
Message outMessage = new Message();
if (speech.contains("Your total bill is ₹")) {
Log.d("price", String.valueOf(price));
outMessage.setMessage("Please Confirm your order:- \n" +finalItemNumber +" "+food_dish+" from "+prefManager.getRestaurant_name()+" at Flat No: 20,Galaxy Apartment,Airport Authority Colony,Andheri,Mumbai,Maharashtra 400 047 \n Your total bill is ₹"+price+". \n Do you want to pay by Wallet or by PayTm");
}else{
outMessage.setMessage(speech);
}
outMessage.setId("2");
messageArrayList.add(outMessage);
Log.d("messgae",outMessage.getMessage());
mAdapter.notifyDataSetChanged();
}
}, 2000);
}
} else {
final JSONArray msg = fulfillment.getJSONArray("messages");
for (int i = 0; i < msg.length(); i++) {
if (i == 0) {
Message outMessage = new Message();
JSONObject speechobj = msg.getJSONObject(i);
JSONArray speech = speechobj.getJSONArray("speech");
Log.d("response of speech", speech.getString(0));
outMessage.setMessage(speech.getString(0));
outMessage.setId("2");
messageArrayList.add(outMessage);
} else {
final int itemposition = i;
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
Message outMessage = new Message();
try {
JSONObject speechobj = msg.getJSONObject(itemposition);
JSONArray speech = speechobj.getJSONArray("speech");
Log.d("response of speech", speech.getString(0));
outMessage.setMessage(speech.getString(0));
outMessage.setId("2");
messageArrayList.add(outMessage);
mAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, 5000);
}
}
}
}
}else{
if (!fulfillment.getString("speech").equals("") && fulfillment.getString("speech") != null) {
final String speech = fulfillment.getString("speech");
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
#Override
public void run() {
Message outMessage = new Message();
outMessage.setMessage(speech);
outMessage.setId("2");
messageArrayList.add(outMessage);
mAdapter.notifyDataSetChanged();
}
},2000);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(AIError error) {
}
#Override
public void onAudioLevel(float level) {
}
#Override
public void onListeningStarted() {
btnSend.setBackground(getDrawable(R.drawable.recording_bg));
}
#Override
public void onListeningCanceled() {
btnSend.setBackground(getDrawable(R.drawable.stedy_recording));
}
#Override
public void onListeningFinished() {
btnSend.setBackground(getDrawable(R.drawable.stedy_recording));
}
}`
my ChatAdapter.java class
public class ChatAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private int BOT = 100;
private int BOT_Restaurant_ListView = 101;
private int USER = 102;
private Activity activity;
private PrefManager prefManager;
private int itemposition = -1;
private int menu_itemposition = -1;
private List<Restaurant_List_Model> restaurant_list;
private ArrayList<Message> messageArrayList;
private RestaurantListViewAdapter restaurantListViewAdapter;
private TextToSpeech tts ;
public ChatAdapter(Activity activity, ArrayList<Message> messageArrayList) {
this.activity = activity;
this.messageArrayList = messageArrayList;
tts = new TextToSpeech(activity, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR){
tts.setLanguage(Locale.ENGLISH);
}
}
});
prefManager = new PrefManager(activity.getApplicationContext());
setHasStableIds(true);
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemview;
if(viewType == BOT){
itemview = LayoutInflater.from(parent.getContext()).inflate(R.layout.bot_msg_view,parent,false);
}else if(viewType == BOT_Restaurant_ListView){
itemview = LayoutInflater.from(parent.getContext()).inflate(R.layout.bot_msg_restaurant_listview,parent,false);
}else {
itemview = LayoutInflater.from(parent.getContext()).inflate(R.layout.user_msg_view,parent,false);
}
return new ViewHolder(itemview);
}
#Override
public int getItemViewType(int position) {
Message message = messageArrayList.get(position);
if(message.getId()!=null && message.getId().equals("2")){
if(message.getMessage().contains("restaurants") || message.getMessage().contains("restaurant")) {
return BOT_Restaurant_ListView;
}else {
return BOT;
}
}else{
return USER;
}
}
#Override
public void onBindViewHolder(#NonNull final RecyclerView.ViewHolder holder, int position) {
int pic_int = 1;
String filename = null;
final Message message = messageArrayList.get(position);
message.setMessage(message.getMessage());
if (holder.getItemViewType() == BOT_Restaurant_ListView) {
Log.d("inside bot listview msg", String.valueOf(BOT_Restaurant_ListView ));
Log.d("adapter position", String.valueOf(holder.getAdapterPosition()));
if(itemposition<holder.getAdapterPosition()){
itemposition = holder.getAdapterPosition();
Log.d("itemposition",String.valueOf(itemposition));
String jsonFileContent;
Log.d("cuisine value", prefManager.getCuisinetype());
if (message.getMessage().contains("restaurants")) {
if(!prefManager.getCuisinetype().equals("") && prefManager.getCuisinetype() != null){
Log.d("restauratn has drawn", "greate");
try {
restaurant_list = new ArrayList<>();
restaurantListViewAdapter = new RestaurantListViewAdapter(activity, restaurant_list);
((ViewHolder) holder).retaurant_listView.setVisibility(View.VISIBLE);
((ViewHolder) holder).retaurant_listView.setAdapter(restaurantListViewAdapter);
Log.d("cuisine value", prefManager.getCuisinetype());
if(message.getMessage().contains("Here are restaurants near you")){
String [] restaurant_Array ={
"indian","french","mexican","italian"
};
int randomNumber = (int) Math.floor(Math.random()*restaurant_Array.length);
filename = restaurant_Array[randomNumber];
Log.d("filename",filename);
jsonFileContent = readFile(activity.getResources().getIdentifier(filename, "raw", activity.getPackageName()));
}else {
filename = prefManager.getCuisinetype().toLowerCase() + "_restaurants";
Log.d("filename", filename);
jsonFileContent = readFile(activity.getResources().getIdentifier(filename, "raw", activity.getPackageName()));
}
JSONObject restaurantfile = new JSONObject(jsonFileContent);
JSONArray jsonArray = restaurantfile.getJSONArray("restaurants");
for (int i = 0; i < jsonArray.length(); i++) {
ImageRoundCorner imageRoundCorner = new ImageRoundCorner();
JSONObject restaurantList = jsonArray.getJSONObject(i);
Restaurant_List_Model restaurant_list_obj = new Restaurant_List_Model();
restaurant_list_obj.setName(restaurantList.getString("name"));
restaurant_list_obj.setLocation(restaurantList.getString("location"));
restaurant_list_obj.setImage_of_item(imageRoundCorner.getRoundedCornerBitmap(BitmapFactory.decodeResource(activity.getResources(), activity.getResources().getIdentifier("restaurant_" + pic_int, "drawable", activity.getPackageName()))));
pic_int++;
restaurant_list_obj.setRating(restaurantList.getLong("rating"));
restaurant_list.add(restaurant_list_obj);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null, null);
} else {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null);
}
prefManager.setCuisinetype("");
pic_int = 1;
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
restaurantListViewAdapter.notifyDataSetChanged();
}
}else if(message.getMessage().contains("Here are some famous food items from "+prefManager.getRestaurant_name()+" restaurant")){
try {
Log.d("menu has draw","greate");
restaurant_list = new ArrayList<>();
restaurantListViewAdapter = new RestaurantListViewAdapter(activity, restaurant_list);
((ViewHolder) holder).retaurant_listView.setAdapter(restaurantListViewAdapter);
((ViewHolder) holder).retaurant_listView.setVisibility(View.VISIBLE);
Log.d("restaurant name value", prefManager.getRestaurant_name());
jsonFileContent = readFile(R.raw.restaurant_menu);
JSONObject menu_cuisine = new JSONObject(jsonFileContent);
ImageRoundCorner imageRoundCorner = new ImageRoundCorner();
if (menu_cuisine.has(prefManager.getRestaurant_name())) {
JSONObject restaurant_menu = menu_cuisine.getJSONObject("Dominos");
Log.d("Chili's American menu", restaurant_menu.toString());
JSONArray menu = restaurant_menu.getJSONArray("menu");
for (int j = 0; j < menu.length(); j++) {
JSONObject menu_obj = menu.getJSONObject(j);
Restaurant_List_Model restaurant_list_obj = new Restaurant_List_Model();
restaurant_list_obj.setName(menu_obj.getString("name"));
restaurant_list_obj.setLocation(menu_obj.getString("cuisine_type"));
restaurant_list_obj.setImage_of_item(imageRoundCorner.getRoundedCornerBitmap(BitmapFactory.decodeResource(activity.getResources(), activity.getResources().getIdentifier("menu_" + pic_int, "drawable", activity.getPackageName()))));
//restaurant_list_obj.setImage_of_item(imageRoundCorner.getRoundedCornerBitmap(BitmapFactory.decodeResource(activity.getResources(), activity.getResources().getIdentifier("menu_" + pic_int, "drawable", activity.getPackageName()))));
pic_int++;
restaurant_list_obj.setRating(menu_obj.getLong("rating"));
restaurant_list.add(restaurant_list_obj);
}
restaurantListViewAdapter.notifyDataSetChanged();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null, null);
} else {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null);
}
pic_int = 1;
prefManager.setRestaurant_name("");
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Log.d("user_message",message.getMessage());
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null, null);
}else {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null);
}
pic_int = 1;
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
((ViewHolder) holder).retaurant_listView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
v.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
v.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
v.onTouchEvent(event);
return true;
}
});
}
} if(holder.getItemViewType()==BOT) {
Log.d("adapter position", String.valueOf(holder.getAdapterPosition()));
Log.d("inside bot msg", String.valueOf(BOT));
((ViewHolder) holder).bot_msg.setText(message.getMessage());
if(itemposition<holder.getAdapterPosition()) {
itemposition = holder.getAdapterPosition();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null, null);
} else {
tts.speak(message.getMessage(), TextToSpeech.QUEUE_FLUSH, null);
}
}
}if(holder.getItemViewType() == USER) {
((ViewHolder) holder).user_message.setText(message.getMessage());
}
}
#Override
public void onViewRecycled(#NonNull RecyclerView.ViewHolder holder) {
super.onViewRecycled(holder);
if(holder.isRecyclable()){
Log.d("inside onViewRecycled","great");
// itemposition = holder.getAdapterPosition();
}
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Override
public int getItemCount() {
return messageArrayList.size();
}
private String readFile(int id) throws IOException
{
BufferedReader reader = null;
reader = new BufferedReader(new InputStreamReader(activity.getResources().openRawResource(id)));
String content = "";
String line;
while ((line = reader.readLine()) != null)
{
content = content + line;
}
return content;
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView user_message,bot_msg;
private ListView retaurant_listView;
ViewHolder(View itemView) {
super(itemView);
bot_msg = itemView.findViewById(R.id.bot_message);
user_message = itemView.findViewById(R.id.message);
retaurant_listView = itemView.findViewById(R.id.restaurant_items_list_ibm);
}
}
}
Please help me out with this issue.
In gif, you can see the lower list is swap with the upper list and then return back
I am using RecyclerView with SwipeRefreshLayout in my app. The problem is that when my RecyclerView have data, I can swipe the layout. But when there's no data in RecyclerView, I can't swipe.
Anyone can solve this problem?
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.student_fragment_tutorial_upcoming, container, false);
tvNoData = (TextView) view.findViewById(R.id.tvNoData);
bdn = getArguments();
year = bdn.getString(TutorialStudentFragment.YEARNAME);
Toast.makeText(getContext(), year, Toast.LENGTH_SHORT).show();
networkUtil = new NetworkUtil();
conStatus = networkUtil.getConnectivityStatusString(getContext());
mdbHelper = new DatabaseHelper(getContext());
copyData = new CopyDatabase(getContext());
recyclerTutorial = (RecyclerView) view.findViewById(R.id.recyclerTutorial);
swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipelayoutTutorial);
swipeRefreshLayout.setColorSchemeResources(R.color.blue, R.color.orange, R.color.green);
if (conStatus.equals("wifi") || conStatus.equals("mobile_data")) {
onRefresh();
} else {
//swipeRefreshLayout.setRefreshing(true);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
if (mdbHelper.getAllTutorialInfo(year, tutorialType).size() == 0) {
tvNoData.setText("There is no upcoming tutorial for now");
tvNoData.setVisibility(View.VISIBLE);
} else {
tvNoData.setVisibility(View.INVISIBLE);
loadTutorialCard(mdbHelper.getAllTutorialInfo(year, tutorialType));
}
//swipeRefreshLayout.setRefreshing(false);
}
});
}
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getContext(), 1);
recyclerTutorial.setLayoutManager(mLayoutManager);
recyclerTutorial.addItemDecoration(new GridSpacingItemDecoration(1, dpToPx(10), true));
recyclerTutorial.setItemAnimator(new DefaultItemAnimator());
Animation fadeIn = AnimationUtils.loadAnimation(getContext(), R.anim.fade_in);
Animation fadeOut = AnimationUtils.loadAnimation(getContext(), R.anim.fade_out);
recyclerTutorial.setAnimation(fadeIn);
recyclerTutorial.addOnItemTouchListener(new RecyclerTouchListener(getContext(), recyclerTutorial, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
/* tutorialArrayList = mdbHelper.getAllTutorialInfo(year);
Tutorial tutorial = tutorialArrayList.get(position);
Bundle bdn = new Bundle();*/
Toast.makeText(getContext(), position + " clicked", Toast.LENGTH_SHORT).show();
}
#Override
public void onLongClick(View view, int position) {
}
}));
swipeRefreshLayout.setOnRefreshListener(this);
return view;
}
public void getTutorialData() {
swipeRefreshLayout.setRefreshing(true);
networkUtil = new NetworkUtil();
conStatus = networkUtil.getConnectivityStatusString(getContext());
if (conStatus.equals("wifi") || conStatus.equals("mobile_data")) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, select_tutorial_url,
new Response.Listener<String>() {
ArrayList<Tutorial> tutorialArrayList = new ArrayList<>();
#Override
public void onResponse(String response) {
int count = 0;
if (response.length() > 0) {
while (count < response.length()) {
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(count);
int id = Integer.parseInt(jsonObject.getString("id"));
// String codeStatus =jsonObject.getString("code");
Tutorial tutorial = new Tutorial(id, jsonObject.getString("class_name"), jsonObject.getString("subject"), jsonObject.getString("lesson"), jsonObject.getString("exam_date"), jsonObject.getString("exam_time"), jsonObject.getString("published"));
if (checkTutorialListWithDate(tutorial)) {
tutorialArrayList.add(tutorial);
}
Log.i("Class :", tutorial.getsClass());
Log.i("Subject :", tutorial.getSubject());
Log.i("Lesson :", tutorial.getLesson());
} catch (JSONException e) {
e.printStackTrace();
}
count++;
}
} else {
Toast.makeText(getContext(), String.valueOf(response.length()), Toast.LENGTH_SHORT).show();
}
swipeRefreshLayout.setRefreshing(false);
loadTutorialCard(tutorialArrayList);
if (tutorialArrayList.size() == 0) {
tvNoData.setVisibility(View.VISIBLE);
tvNoData.setText("There is no upcoming tutorial for now");
} else {
tvNoData.setVisibility(View.INVISIBLE);
}
workingWithLocalDatabase(tutorialArrayList, mdbHelper.getAllTutorialInfo(year, tutorialType));
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
swipeRefreshLayout.setRefreshing(false);
NetworkUtil.checkInternetConnection(error, getContext(), swipeRefreshLayout);
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("studentYear", year);
return params;
}
};
Mysingleton.getInstance(getContext()).addToRequestque(stringRequest);
} else {
swipeRefreshLayout.setRefreshing(false);
networkUtil.showNetError(getContext(), swipeRefreshLayout);
}
}
public void onRefresh() {
getTutorialData();
}
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.