ada.mamad ada.mamad - 5 months ago 24
JSON Question

How to load data in one fragment in Android

I want show 3

fragments
in my
Activity
and load data from
json
in any
fragments
! I want show each json data into one fragment, but in my application show all of data in all fragments!

For example : i want show article data into article fragment, music data into music fragment and more ... . but now show all data (article, music, video) in all
fragment
s!

In my application i use
EventBus
for send data and use one
DataModel
for save json data into this.


Fragment 1 :

public class free_fragment extends Fragment {

private RecyclerView mRecyclerView;
private free_recycler_adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private List<DataModel> dataModels = new ArrayList<DataModel>();

private Context context;

@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {

View view = inflater.inflate(R.layout.fragment_free_layout, container, false);

context = getContext();

if (!EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().register(this);
}

LoadData();

///----- RecyclerView -----
mRecyclerView = (RecyclerView) view.findViewById(R.id.pdf_RecyclerView);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mAdapter = new free_recycler_adapter(context, dataModels);
mRecyclerView.setAdapter(mAdapter);

return view;
}

@Subscribe
public void onEvent(List<DataModel> mainInfoModels) {
/* if (dataModels.size() > 0) {
dataModels.remove(dataModels.size() - 1);
mAdapter.notifyItemRemoved(dataModels.size());
//mAdapter.setLoaded();
}*/

mAdapter.add(mainInfoModels);
mAdapter.notifyDataSetChanged();
}

private void LoadData() {
freeDataInfo dataInfo = new freeDataInfo();
// here getMainDataInfo() should return the server response
dataInfo.getFreeDataInfo(context);
}


Fragment 2 :

public class paid_fragment extends Fragment {

private RecyclerView mRecyclerView;
private paid_recycler_adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private List<DataModel> dataModels = new ArrayList<DataModel>();

private Context context;

@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {

View view = inflater.inflate(R.layout.fragment_paid_layout, container, false);

context = getContext();

if (!EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().register(this);
}

LoadData();

///----- RecyclerView -----
mRecyclerView = (RecyclerView) view.findViewById(R.id.voice_RecyclerView);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
mAdapter = new paid_recycler_adapter(context, dataModels);
mRecyclerView.setAdapter(mAdapter);

return view;
}

@Subscribe
public void onEvent(List<DataModel> mainInfoModels) {
/* if (dataModels.size() > 0) {
dataModels.remove(dataModels.size() - 1);
mAdapter.notifyItemRemoved(dataModels.size());
//mAdapter.setLoaded();
}*/

mAdapter.add(mainInfoModels);
mAdapter.notifyDataSetChanged();
}

private void LoadData() {
paidDataInfo dataInfo = new paidDataInfo();
// here getMainDataInfo() should return the server response
dataInfo.getPaidDataInfo(context);
}


AsyncTask codes for Fragment 1 :

public class freeDataInfo {
private Context mContext ;
private String ServerAddress = freeServer_IP.getFreeIP();

public void getFreeDataInfo(Context context) {
mContext = context;
new getInfo().execute(ServerAddress + "limit=10");
}

private class getInfo extends AsyncTask<String, Void, String> {
EventBus bus = EventBus.getDefault();
private String ou_response;
private List<DataModel> infoModels;

@Override
protected void onPreExecute() {
CustomProcessDialog.createAndShow(mContext);
infoModels = new ArrayList<>();
}

@Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();

//String url = (String) params[0];
Request request = new Request.Builder()
.url(ServerAddress + "limit=10")
.cacheControl(CacheControl.FORCE_NETWORK)
.build();

Response response;
try {
response = client.newCall(request).execute();
ou_response = response.body().string();
response.body().close();
if (ou_response != null) {
try {
JSONObject postObj = new JSONObject(ou_response);
JSONArray postsArray = postObj.optJSONArray("result");
infoModels = new ArrayList<>();

for (int i = 0; i <= infoModels.size(); i++) {
JSONObject postObject = (JSONObject) postsArray.get(i);

int id = postObject.getInt("id");
Log.d("id", String.valueOf(id));
String title = postObject.getString("title");
String description = postObject.getString("description");
String image = postObject.getString("image");
String category = postObject.getString("categoryName");
String date = postObject.getString("publishDate");

Log.d("Data", "Post ID: " + id);
Log.d("Data", "Post title: " + title);
Log.d("Data", "Post image: " + image);
Log.d("Data", "---------------------------------");

//Use the title and id as per your requirement
infoModels.add(new DataModel(id, title, description, category, date, image));
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("error", String.valueOf(e));
}
}
} catch (IOException e) {
e.printStackTrace();
Log.e("error2", String.valueOf(e));
}
return ou_response;
}

@Override
protected void onPostExecute(String result) {
CustomProcessDialog.dissmis();
if (result != null) {
bus.post(infoModels);
} else {
Toast.makeText(mContext, "Empty", Toast.LENGTH_SHORT).show();
}
}
}
}


AsyncTask codes for Fragment 2 :

public class paidDataInfo {
private Context mContext;
private String ServerAddress = paidServer_IP.getPaidIP();

public void getPaidDataInfo(Context context) {
mContext = context;
new getInfo().execute(ServerAddress + "limit=10");
}

private class getInfo extends AsyncTask<String, Void, String> {
EventBus bus = EventBus.getDefault();
private String ou_response;
private List<DataModel> infoModels;

@Override
protected void onPreExecute() {
CustomProcessDialog.createAndShow(mContext);
infoModels = new ArrayList<>();
}

@Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();

//String url = (String) params[0];
Request request = new Request.Builder()
.url(ServerAddress + "limit=10")
.cacheControl(CacheControl.FORCE_NETWORK)
.build();

Response response;
try {
response = client.newCall(request).execute();
ou_response = response.body().string();
response.body().close();
if (ou_response != null) {
try {
JSONObject postObj = new JSONObject(ou_response);
JSONArray postsArray = postObj.optJSONArray("result");
infoModels = new ArrayList<>();

for (int i = 0; i <= infoModels.size(); i++) {
JSONObject postObject = (JSONObject) postsArray.get(i);

int id = postObject.getInt("id");
Log.d("id", String.valueOf(id));
String title = postObject.getString("title");
String description = postObject.getString("description");
String image = postObject.getString("image");
String category = postObject.getString("categoryName");
String date = postObject.getString("publishDate");

Log.d("Data", "Post ID: " + id);
Log.d("Data", "Post title: " + title);
Log.d("Data", "Post image: " + image);
Log.d("Data", "---------------------------------");

//Use the title and id as per your requirement
infoModels.add(new DataModel(id, title, description, category, date, image));
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("error", String.valueOf(e));
}
}
} catch (IOException e) {
e.printStackTrace();
Log.e("error2", String.valueOf(e));
}
return ou_response;
}

@Override
protected void onPostExecute(String result) {
CustomProcessDialog.dissmis();
if (result != null) {
bus.post(infoModels);
} else {
Toast.makeText(mContext, "Empty", Toast.LENGTH_SHORT).show();
}
}
}
}


How can i fix this problem ?

Answer

this is because you are using event bus in a wrong way. all of your callback functions for fetching json data has same signature, so event bus will deliver data to all of them every time you receive data from server.

one way to correct it is to create separate models for your Fragments like this:

class FreeDataModel extends DataModel {}

and

class PaidDataModel extends DataModel {}

and in your AsyncTasks instead of having a List<DataModel> you should use List<FreeDataModel> and List<PaidDataModel> and also change your callback functions signature in your Fragments (onEvent function of each Fragment) and then your problem will be solved.

Comments