I am building an app in which I have a view with multiple tabs. Each tab contains a RecyclerView
which gets populated from data in MySQL
. So there is the Activity
with the ViewPager
and then each tab has its own Fragment
. So I use the Interface
to pass data from Fragment
to Activity
in order to be able to search for. The thing is that if I do not scroll over the tabs the recycler List
is null so I cannot search. My question is would it be better if I search directly in the database or is there any other way to do this?
My App looks like this:
The code for passing data is:
Interface:
public interface CoffeeCommunicator {
void sendCoffeeListData(String name, String image, String price);
}
Fragment:
@Override
protected List<ProductList> doInBackground(String... params) {
try {
url = new URL(params[0]);
urlConnection =(HttpURLConnection) url.openConnection();
urlConnection.connect();
urlConnection.setConnectTimeout(5000);
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
jsonResult = StringGenerator.inputStreamToString(in, getActivity());
customList = new ArrayList<>();
jsonResponse = new JSONObject(jsonResult.toString());
jsonMainNode = jsonResponse.optJSONArray(AppConstant.COFFEE_JSON_ARRAY);
for (int i = 0; i < jsonMainNode.length(); i++) {
jsonChildNode = jsonMainNode.getJSONObject(i);
name = jsonChildNode.optString("name");
price = jsonChildNode.optString("price");
image = jsonChildNode.optString("image");
customList.add(new ProductList(image, name, price));
coffeeCommunicator.sendCoffeeListData(name, image, price);
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return customList;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
coffeeCommunicator = (CoffeeCommunicator)activity;
}
Activity:
@Override
public void sendCoffeeListData(String name, String image, String price) {
coffeesList.add(new ProductList(image, name, price));
}
So then i have coffeeList
available to search for.
Any ideas would be helpfull.
I can give code sample but you know your code better. Here's a sample:
In Activity:
populateList();
coffeeFragment = CoffeeFragment.newInstance();
coffeeFragment.setList(coffeesList);
void populateList() {
jsonResponse = new JSONObject(jsonResult.toString());
jsonMainNode = jsonResponse.optJSONArray(AppConstant.COFFEE_JSON_ARRAY);
for (int i = 0; i < jsonMainNode.length(); i++) {
jsonChildNode = jsonMainNode.getJSONObject(i);
name = jsonChildNode.optString("name");
price = jsonChildNode.optString("price");
image = jsonChildNode.optString("image");
coffeesList.add(new ProductList(image, name, price));
}
}
Fragment:
public void setList(final List<ProductList> arrayList) {
{
customList = arrayList;
}
Note:
Basically you fill data onto coffeesList
in Activity. And then pass the List onto the Fragment. I pass a List object by calling a method setList
in the Fragment because it is easier.
I hope that is clear enough. Is there a problem with this approach?