application blank after move to another fragment using bottom navigation view - android

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*/
}

Related

How Do We Set id For Data That Showed With Volley Json Array Request

I have some problem about setting and getting id from data that showed with volley JSon array request.
I've tried to do this, but it fail.
ChildTidur.java
public class ChildTidur extends AppCompatActivity implements TidurAdapter.ContactsAdapterListener {
private static final String TAG = ChildTidur.class.getSimpleName();
private RecyclerView recyclerView;
private List<Story> storyList;
private TidurAdapter mAdapter;
private SearchView searchView;
private TextView noFavtsTV;
private AppPreferences appPreferences;
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 2000;
public static final int READ_TIMEOUT = 2000;
final String KEY_SAVED_RADIO_BUTTON_INDEX = "SAVED_RADIO_BUTTON_INDEX";
// url to fetch contacts json
private static final String URL = "https://api.kafeinkode.com/childtidur.json";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.child_tidur);
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
SwipeRefreshLayout pullToRefresh = findViewById(R.id.pullToRefresh);
pullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
finish();
startActivity(getIntent());
}
});
//toolbar logo and desc
Toolbar topToolBar = (Toolbar) findViewById(R.id.toolbarTidur);
setSupportActionBar(topToolBar); //munculkan menu ke toolbar
getSupportActionBar().setDisplayHomeAsUpEnabled(true); //this line shows back button
recyclerView = findViewById(R.id.recycler_view);
noFavtsTV = findViewById(R.id.no_favt_text);
storyList = new ArrayList<>();
mAdapter = new TidurAdapter(this, storyList, this, appPreferences);
// white background notification bar
whiteNotificationBar(recyclerView);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.addItemDecoration(new TidurDekor(this, DividerItemDecoration.VERTICAL, 36));
recyclerView.setAdapter(mAdapter);
//Make call to AsyncTask
new AsyncLogin().execute();
//Get radio button value
LoadPreferences();
} //OnCreate
private void showNoFavtText(boolean show) {
noFavtsTV.setVisibility(show ? View.VISIBLE : View.GONE); //jika data yang ditampilkan tidak ada, maka show noFavsTv
recyclerView.setVisibility(show ? View.GONE : View.VISIBLE); //jika data yang ditampilkan tidak ada, maka don't show rV
}
private void LoadPreferences(){
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View contentView = inflater.inflate(R.layout.activity_settings, null,false);
RadioGroup radioGroup = (RadioGroup)contentView.findViewById(R.id.radioSex);
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
int savedRadioIndex = sharedPreferences.getInt(KEY_SAVED_RADIO_BUTTON_INDEX, 0);
RadioButton savedCheckedRadioButton = (RadioButton)radioGroup.getChildAt(savedRadioIndex);
savedCheckedRadioButton.setChecked(true);
RadioGroup genderGroup = (RadioGroup) contentView.findViewById(R.id.radioSex);
RadioButton male = (RadioButton) contentView.findViewById(R.id.theme1);
RadioButton female = (RadioButton) contentView.findViewById(R.id.theme2);
if (genderGroup.getCheckedRadioButtonId() == -1) {
Toolbar tb = (Toolbar) findViewById(R.id.toolbarTidur);
tb.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
}
else {
if (male.isChecked()) { // one of the radio buttons is checked
Toolbar tb1 = (Toolbar) findViewById(R.id.toolbarTidur);
tb1.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
}
else if (female.isChecked()) {
Toolbar tb2 = (Toolbar) findViewById(R.id.toolbarTidur);
tb2.setBackgroundColor(getResources().getColor(R.color.colorAccent));
}
}
}
private class AsyncLogin extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(ChildTidur.this);
HttpURLConnection conn;
java.net.URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
showNoFavtText(false);
pdLoading.setMessage("\tMencoba terhubung ke internet...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your json file resides
// Even you can make call to php file which returns json data
url = new URL("https://api.kafeinkode.com/childtidur.json");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("GET");
// setDoOutput to true as we recieve data from json file
conn.setDoOutput(true);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return("koneksi gagal");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
/**
* fetches json by making http calls
*/
protected void onPostExecute(String result) {
JsonArrayRequest request = new JsonArrayRequest(URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
pdLoading.dismiss();
Log.d(TAG, response.toString());
if (response.length() > 0) {
// Parsing json
List<Story> items = new Gson().fromJson(response.toString(), new TypeToken<List<Story>>() {
}.getType());
// adding contacts to contacts list
storyList.clear();
storyList.addAll(items);
// refreshing recycler view
mAdapter.notifyDataSetChanged();
for (int i=0; i<storyList.size(); i++) {
Story story = new Story();
story.setIdStory(String.valueOf(i));
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pdLoading.dismiss();
// error in getting json
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), "Tidak bisa menampilkan data. Periksa kembali sambungan internet Anda", Toast.LENGTH_LONG).show();
AlertDialog alertDialog = new AlertDialog.Builder(ChildTidur.this).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Data Tidak bisa ditampilkan. Periksa kembali sambungan internet Anda");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
showNoFavtText(true);
}
});
TidurSearch.getInstance().addToRequestQueue(request);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search_tidur, menu);
getMenuInflater().inflate(R.menu.menu_main, menu);
// Associate searchable_tidur configuration with the SearchView
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView = (SearchView) menu.findItem(R.id.action_search2).getActionView();
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
searchView.setMaxWidth(Integer.MAX_VALUE);
// listening to search query text change
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// filter recycler view when query submitted
mAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String query) {
// filter recycler view when text is changed
mAdapter.getFilter().filter(query);
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_search2) {
return true;
}
//Menu
if (id == R.id.action_settings) {
startActivity(new Intent(this, SettingsActivity.class));
return true;
}
else
if (id == R.id.about_us) {
startActivity(new Intent(this, AboutUs.class));
return true;
}
else
if (id == R.id.favlist) {
startActivity(new Intent(this, ShowFavouriteList.class));
return true;
}
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
// close search view on back button pressed
if (!searchView.isIconified()) {
searchView.setIconified(true);
return;
}
super.onBackPressed();
}
private void whiteNotificationBar(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int flags = view.getSystemUiVisibility();
flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
view.setSystemUiVisibility(flags);
getWindow().setStatusBarColor(Color.WHITE);
}
}
#Override
public void onContactSelected(Story story) {
Toast.makeText(getApplicationContext(), "Selected: " + story.getName(), Toast.LENGTH_LONG).show();
}
}
TidurAdapter.java
public void onClick(View view) {
// Another problem lays here when I get id of data
Story story = storyList.get(getLayoutPosition());
int ambilId = Integer.parseInt(story.getIdStory());
if ( 0 == ambilId ) {
Intent myIntent = new Intent(view.getContext(), DoaMauTidur.class);
view.getContext().startActivity(myIntent);
}
else if ( 1 == getAdapterPosition() )
{
Intent myIntent = new Intent(view.getContext(), DoaBangunt.class);
view.getContext().startActivity(myIntent);
}
else if ( 2 == getAdapterPosition() )
{
Intent myIntent = new Intent(view.getContext(), DoaJimak.class);
view.getContext().startActivity(myIntent);
}
}
This is a full code:
Story.java
public Story(){}
String name;
String nomor;
private String idStory;
private int isLiked;
public String getName() {
return name;
}
public String getNomor() { return nomor; }
public void setIdStory(String isStory) {
this.idStory = isStory;
}
public String getIdStory() {
return idStory;
}
public void setIsLiked(int isLiked) {
this.isLiked = isLiked;
}
public int getIsLiked() {
return isLiked;
}
}
ChildTidur.java
/**
* fetches json by making http calls
*/
protected void onPostExecute(String result) {
JsonArrayRequest request = new JsonArrayRequest(URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
pdLoading.dismiss();
Log.d(TAG, response.toString());
if (response.length() > 0) {
// Parsing json
List<Story> items = new Gson().fromJson(response.toString(), new TypeToken<List<Story>>() {
}.getType());
// adding contacts to contacts list
storyList.clear();
storyList.addAll(items);
// refreshing recycler view
mAdapter.notifyDataSetChanged();
for (int i=0; i<storyList.size(); i++) {
Story story = new Story();
story.setIdStory(String.valueOf(i));
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
pdLoading.dismiss();
// error in getting json
Log.e(TAG, "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), "Tidak bisa menampilkan data. Periksa kembali sambungan internet Anda", Toast.LENGTH_LONG).show();
AlertDialog alertDialog = new AlertDialog.Builder(ChildTidur.this).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Data Tidak bisa ditampilkan. Periksa kembali sambungan internet Anda");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
showNoFavtText(true);
}
});
TidurSearch.getInstance().addToRequestQueue(request);
}
}
TidurAdapter.java
public class TidurAdapter extends RecyclerView.Adapter<TidurAdapter.TidurViewHolder> implements Filterable {
private Context context;
private List<Story> storyList;
private List<Story> storyListFiltered;
private ContactsAdapterListener listener;
private int changedItemPosition;
public boolean isLiked;
private AppPreferences appPreferences;
Boolean checked = false;
public TidurAdapter(Context context, List<Story> storyList, ContactsAdapterListener listener, AppPreferences appPreferences) {
this.context = context;
this.listener = listener;
this.storyList = storyList;
this.storyListFiltered = storyList;
this.appPreferences = appPreferences;
}
#Override
public TidurViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.child_row_item_tidur, parent, false);
return new TidurViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull TidurViewHolder holder, int position) {
final Story story = storyListFiltered.get(position);
holder.name.setText(story.getName());
holder.nomor.setText(story.getNomor());
holder.setViewData(storyList.get(position), holder.getAdapterPosition());
}
#Override
public int getItemCount() {
return storyListFiltered.size();
}
public interface ContactsAdapterListener {
void onContactSelected(Story story);
}
//ViewHolder
public class TidurViewHolder extends RecyclerView.ViewHolder {
public TextView name;
public TextView nomor;
public ImageView mFavorite;
private CheckBox likeCheckBox;
final String KEY_SAVED_RADIO_BUTTON_INDEX = "SAVED_RADIO_BUTTON_INDEX";
public TidurViewHolder(View view) {
super(view);
name = view.findViewById(R.id.name);
nomor = view.findViewById(R.id.nomor);
likeCheckBox = itemView.findViewById(R.id.like_button_cb);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// get id of data
Story story = storyList.get(getLayoutPosition());
int ambilId = Integer.parseInt(story.getIdStory());
if ( 0 == ambilId ) {
Intent myIntent = new Intent(view.getContext(), DoaMauTidur.class);
view.getContext().startActivity(myIntent);
}
else if ( 1 == getAdapterPosition() )
{
Intent myIntent = new Intent(view.getContext(), DoaBangunt.class);
view.getContext().startActivity(myIntent);
}
else if ( 2 == getAdapterPosition() )
{
Intent myIntent = new Intent(view.getContext(), DoaJimak.class);
view.getContext().startActivity(myIntent);
}
}
});
//Get radio button value
LayoutInflater inflater = (LayoutInflater) view.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View cV = inflater.inflate(R.layout.activity_settings, null,false);
RadioGroup radioGroup = (RadioGroup)cV.findViewById(R.id.radioSex);
SharedPreferences sharedPreferences = view.getContext().getSharedPreferences("MY_SHARED_PREF", Activity.MODE_PRIVATE);
int savedRadioIndex = sharedPreferences.getInt(KEY_SAVED_RADIO_BUTTON_INDEX, 0);
RadioButton savedCheckedRadioButton = (RadioButton)radioGroup.getChildAt(savedRadioIndex);
savedCheckedRadioButton.setChecked(true);
RadioGroup genderGroup = (RadioGroup) cV.findViewById(R.id.radioSex);
RadioButton male = (RadioButton) cV.findViewById(R.id.theme1);
RadioButton female = (RadioButton) cV.findViewById(R.id.theme2);
if (genderGroup.getCheckedRadioButtonId() == -1) {
nomor.setBackgroundColor(view.getResources().getColor(R.color.colorPrimaryDark));
} else {
if (male.isChecked()) { // one of the radio buttons is checked
nomor.setBackgroundDrawable(ContextCompat.getDrawable(view.getContext(), R.drawable.rounded_drawable));
}
else if (female.isChecked()) {
nomor.setBackgroundDrawable(ContextCompat.getDrawable(view.getContext(), R.drawable.rounded_drawable_red));
}
}
} //TidurViewHolder(View view)
public void setViewData(final Story story, final int adapterPosition) {
if (story.getIsLiked() == 1) {
likeCheckBox.setChecked(true);
}
else {
likeCheckBox.setChecked(false);
}
likeCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
changedItemPosition = adapterPosition;
if (buttonView.isPressed()) {
if (isChecked) {
isLiked = true;
updateLikes();
appPreferences.saveFavouriteCard(story);
Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
}
else {
isLiked = false;
updateLikes();
appPreferences.deleteCard(story.getIdStory());
Toast.makeText(context, "Removed", Toast.LENGTH_SHORT).show();
}
}
}
});
} //setviewdata
public void updateLikes() {
if (isLiked && storyList.get(changedItemPosition).getIsLiked() == 0) { //jika dilakukan like (pada posisi hati kosong) di halaman home
storyList.get(changedItemPosition).setIsLiked(1); //maka jadikan hati berwarna merah di halaman favourite list
notifyItemChanged(changedItemPosition, ACTION_LIKE_IMAGE_CLICKED);
}
else if (!isLiked && storyList.get(changedItemPosition).getIsLiked() == 1) { //jika like dicabut (pada posisi hati yang sedang merah) di halaman home
storyList.get(changedItemPosition).setIsLiked(0); //maka cabut juga warna merah di halaman favourite list
notifyItemChanged(changedItemPosition, ACTION_LIKE_IMAGE_CLICKED);
}
} //updateLikes
}//Class TidurViewHolder
}
The error result is, it is showing null... Which mean no ID that can be obtained.
In your for loop you are not setting id of your List, but your new Story.
Instead of:
for (int i=0; i<storyList.size(); i++) {
Story story = new Story();
story.setIdStory(String.valueOf(i));
}
Use this:
for (int i=0; i<storyList.size(); i++) {
storyList.get(i).setIdStory(String.valueOf(i));
}
Also because your index i=0 starts from zero, you should change for loop index i to start from 1 like this:
for (int i=1; i<=storyList.size(); i++) {
storyList.get(i).setIdStory(String.valueOf(i));
}
Check this main activity:
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
private ArrayList<Story> storyList;
// url to fetch contacts json
private static final String URL = "https://api.kafeinkode.com/childtidur.json";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
storyList = new ArrayList<>();
//Fetch JSON data
fetchData();
}
private void fetchData(){
JsonArrayRequest request = new JsonArrayRequest(URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// Parsing json
List<Story> items = new Gson().fromJson(response.toString(), new TypeToken<List<Story>>() {}.getType());
// adding contacts to contacts list
storyList.clear();
storyList.addAll(items);
for (int i=0; i<storyList.size(); i++) {
storyList.get(i).setIdStory(String.valueOf(i + 1));
}
Log.d("StoryLid: ", storyList.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error in getting json
Log.e(TAG, "Error: " + error.getMessage());
}
});
VolleyService.getInstance(this).getRequestQueue().add(request);
}
}
As a result you have response:

Can't swipe in SwipeRefresh layout when there is no data

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();
}

RecyclerView in ViewPager not refreshing from BlankFragment

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;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
}
}

Fragment Oncreateview() not called unless we swipe the tabs

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.

Pass position of the item of recycler view to open up a new acitivity

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);

Categories

Resources