Palang Palang - 6 months ago 189
JSON Question

How to show JSON data in fragment on Android

I want insert 3

fragment
in
MainActivity
, and when swipe in
fragments
load data from that
fragment
!

For show website posts, i use Json and i write below codes, when running application not show me any post in
fragments
just show me this message in
logCat
:

05-31 15:40:22.303 18219-18219/com.razemovafaghiat.tellfa.android D/LGMtpDatabaseJNI: register_android_mtp_LGMtpDatabase
05-31 15:40:25.612 18219-18304/com.razemovafaghiat.tellfa.android W/System.err: at com.razemovafaghiat.tellfa.android.AccessLayer.freeDataInfo$getInfo.doInBackground(freeDataInfo.java:75)
05-31 15:40:25.612 18219-18304/com.razemovafaghiat.tellfa.android W/System.err: at com.razemovafaghiat.tellfa.android.AccessLayer.freeDataInfo$getInfo.doInBackground(freeDataInfo.java:38)


Fragment codes:

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 = getActivity();

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

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

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

@Override
public void onResume() {
super.onResume();
EventBus.getDefault().register(this);
}

@Override
public void onPause() {
EventBus.getDefault().unregister(this);
super.onPause();
}
}


Adapter codes:

public class free_recycler_adapter extends RecyclerView.Adapter<free_recycler_adapter.ViewHolder> {
private static String[] mDataset;
private List<DataModel> mDateSet;
private Context context;

// Provide a suitable constructor (depends on the kind of dataset)
public free_recycler_adapter(Context context, List<DataModel> dataSet) {
this.context = context;
this.mDateSet = dataSet;
}

// Create new views (invoked by the layout manager)
@Override
public free_recycler_adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// create a new view
View view = LayoutInflater.from(context).inflate(R.layout.free_card_layout, parent, false);

// create ViewHolder
return new ViewHolder(view);
}

// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {

// - get data from your itemsData at this position
// - replace the contents of the view with that itemsData

viewHolder.free_titleText.setText(Html.fromHtml(mDateSet.get(position).getTitle()));
Glide.with(context)
.load(mDateSet.get(position).getImage())
.placeholder(R.drawable.ic_content_info_cat)
.crossFade()
.into(viewHolder.free_avatarImage);
viewHolder.free_descText.setText(Html.fromHtml(mDateSet.get(position).getDescription()));

}

// Return the size of your dataset (invoked by the layout manager)
@Override
public int getItemCount() {
return mDateSet.size();
}

public void remove(int position) {
mDateSet.remove(position);
notifyItemRemoved(position);
}

public void clear() {
mDateSet.clear();
notifyDataSetChanged();
}

public void add(List<DataModel> models) {
mDateSet.addAll(models);
notifyDataSetChanged();
}

public void update(List<DataModel> models) {
mDateSet.clear();
mDateSet.addAll(models);
notifyDataSetChanged();
}

// inner class to hold a reference to each item of RecyclerView
public static class ViewHolder extends RecyclerView.ViewHolder {

public TextView free_titleText, free_descText;
public ImageView free_avatarImage;

public ViewHolder(View itemLayoutView) {
super(itemLayoutView);

free_titleText = (TextView) itemLayoutView.findViewById(R.id.pdf_card_title);
free_descText = (TextView) itemLayoutView.findViewById(R.id.pdf_card_content);
free_avatarImage = (ImageView) itemLayoutView.findViewById(R.id.pdf_card_image);

itemLayoutView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), ContentPage.class);
v.getContext().startActivity(intent);
}
});
}
}
}


AsyncTask codes (freeDataInfo) :

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");
String title = postObject.getString("title");
String description = postObject.getString("content");
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", "---------------------------------");

//Use the title and id as per your requirement
infoModels.add(new DataModel(id, title, description, image, category, date));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
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();
}
}
}
}


For show data i use
RecyclerView
!


How can i fix this problem and show website datas in fragment?

Answer

You must check the Context variable. in Fragments you have to define and set context variable in onCreateView method in Fragment itself instead of caller Activity.

context=getActivity(); in onCreateView method.