How to display items in custom Gridview? - android

I'm trying to create a simple news application,I am able to display data in the listview, But I want to display it in grid format.I am not getting any idea how to achieve that. Please support
Updted Code
package com.journaldev.androidrssfeedtutorial;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.LayoutRes;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public class RSSFeedActivity extends AppCompatActivity {
private ProgressBar pDialog;
ArrayList<HashMap<String, String>> rssItemList = new ArrayList<>();
RSSParser rssParser = new RSSParser();
Toolbar toolbar;
GridView gridView;
List<RSSItem> rssItems = new ArrayList<>();
private static String TAG_TITLE = "title";
private static String TAG_LINK = "link";
private static String TAG_DESCRIPTION = "description";
private static String TAG_PUB_DATE = "pubDate";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rss_feed);
String rss_link = getIntent().getStringExtra("rssLink");
new LoadRSSFeedItems().execute(rss_link);
/* ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent in = new Intent(getApplicationContext(),
MainActivity.class);
String page_url = ((TextView)
view.findViewById(R.id.page_url)).getText().toString().trim();
in.putExtra("url", page_url);
startActivity(in);
}
});*/
}
public class LoadRSSFeedItems extends AsyncTask<String, String,
String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressBar(RSSFeedActivity.this, null,
android.R.attr.progressBarStyleLarge);
RelativeLayout relativeLayout = findViewById(R.id.relativeLayout);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
lp.addRule(RelativeLayout.CENTER_IN_PARENT);
pDialog.setLayoutParams(lp);
pDialog.setVisibility(View.VISIBLE);
relativeLayout.addView(pDialog);
}
#Override
protected String doInBackground(String... args) {
// rss link url
String rss_url = args[0];
// list of rss items
rssItems = rssParser.getRSSFeedItems(rss_url);
// looping through each item
for (RSSItem item : rssItems) {
// creating new HashMap
if (item.link.toString().equals(""))
break;
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
String givenDateString = item.pubdate.trim();
SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy
HH:mm:ss Z");
try {
Date mDate = sdf.parse(givenDateString);
SimpleDateFormat sdf2 = new SimpleDateFormat("EEEE, dd MMMM
yyyy - hh:mm a", Locale.US);
item.pubdate = sdf2.format(mDate);
} catch (ParseException e) {
e.printStackTrace();
}
map.put(TAG_TITLE, item.title);
map.put(TAG_LINK, item.link);
map.put(TAG_DESCRIPTION, item.description);
map.put(TAG_PUB_DATE, item.pubdate); // If you want parse the
date
// adding HashList to ArrayList
rssItemList.add(map);
}
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/* ListAdapter adapter = new SimpleAdapter( //Old code
RSSFeedActivity.this,
rssItemList, R.layout.rss_item_list_row,
new String[]{TAG_LINK, TAG_TITLE,
TAG_DESCRIPTION,TAG_PUB_DATE},
new int[]{R.id.page_url, R.id.title,
R.id.description, R.id.pub_date});
// updating listview
setListAdapter(adapter);*/
RecyclerView recyclerView = (RecyclerView)
findViewById(R.id.recyclerView);
// set a GridLayoutManager with default vertical orientation
and 2 number of columns
GridLayoutManager gridLayoutManager = new
GridLayoutManager(getApplicationContext(), 2);
recyclerView.setLayoutManager(gridLayoutManager); // set
LayoutManager to RecyclerView
// call the constructor of CustomAdapter to send the
reference and data to Adapter
CustomAdapter customAdapter = new
CustomAdapter(RSSFeedActivity.this, rssItemList, new String[]
{TAG_LINK, TAG_TITLE, TAG_DESCRIPTION,TAG_PUB_DATE});
recyclerView.setAdapter(customAdapter);
}
});
return null;
}
protected void onPostExecute(String args) {
pDialog.setVisibility(View.GONE);
}
}
}
Custom Adapter class:
public class CustomAdapter extends
RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
ArrayList rssItemList;
Context context;
public CustomAdapter(Context context, ArrayList rssItemList,String[]
from) {
this.context = context;
this.rssItemList = rssItemList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int
viewType) {
// infalte the item Layout
View v =
LayoutInflater.from(parent.getContext()).inflate(R.layout.gridview_row,
parent, false);
// set the view's size, margins, paddings and layout parameters
MyViewHolder vh = new MyViewHolder(v); // pass the view to View
Holder
return vh;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position)
{
holder.name.setText(rssItemList.get(position)); //Showing error
holder.image.setText(rssItemList.get(position)); //Showing error
}
#Override
public int getItemCount() {
return rssItemList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
// init the item view's
TextView name;
TextView image;
public MyViewHolder(View itemView) {
super(itemView);
// get the reference of item view's
name = (TextView)
itemView.findViewById(R.id.android_gridview_text1);
image = (TextView)
itemView.findViewById(R.id.android_gridview_text2);
}
}
}
No i am facing one problem.Not able to pass data to custom adapter.Pls help me to solve this issue.

Related

How to Show JSON Data in Fragment Android Recyclerview Volley?

Please help with the following problems, the problem is that the data does not want to appear in the fragment home, even though the internet condition is on
My HomeFragment code:
package untag.adproj.lestari.lestari.Home;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import untag.adproj.lestari.lestari.R;
public class HomeFragment extends Fragment {
private String URL="http://pembuatanprogram.000webhostapp.com";
private RecyclerAdapter recyclerAdapter;
private RecyclerView recyclerView;
private ArrayList<Data> listdata;
private GridLayoutManager gridLayoutManager;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
gridLayoutManager = new GridLayoutManager(getActivity(), 2);
gridLayoutManager.setOrientation(GridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(gridLayoutManager);
listdata = new ArrayList<Data>();
AmbilData();
recyclerAdapter = new RecyclerAdapter(getActivity(),listdata);
recyclerView.setAdapter(recyclerAdapter);
recyclerAdapter.notifyDataSetChanged();
return view;
}
private void AmbilData() {
JsonArrayRequest aarRequest = new JsonArrayRequest(URL + "/produk.php" ,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length()>0){
for (int i =0 ; i<response.length();i++){
try {
JSONObject data = response.getJSONObject(i);
Data item = new Data();
item.setId(data.getString("id"));
item.setJudul(data.getString("judul"));
item.setHarga(data.getString("harga"));
item.setThubnail(data.getString(URL+"/img/"+data.getString("gambar")));
listdata.add(item);
recyclerAdapter.notifyDataSetChanged();
} catch (JSONException e) {
}
}
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
};
Volley.newRequestQueue(getActivity()).add(aarRequest);
}
}
My RecyclerAdapter code:
package untag.adproj.lestari.lestari.Home;
import android.app.Activity;
import android.content.Context;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import untag.adproj.lestari.lestari.R;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private ArrayList<Data> listdata;
private Activity activity;
private Context context;
public RecyclerAdapter(Activity activity, ArrayList<Data> listdata) {
this.listdata = listdata;
this.activity = activity;
}
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.fragment_home_list, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
//holder.mImage.setImageResource(listdata.get(position).getThubnail());
holder.id.setText(listdata.get(position).getId());
holder.judul.setText(listdata.get(position).getJudul());
holder.harga.setText(listdata.get(position).getHarga());
final ViewHolder x=holder;
Glide.with(activity)
.load(listdata.get(position).getThubnail())
.into(holder.thumbnail);
holder.id.setVisibility(View.GONE);
}
#Override
public int getItemCount() {
return listdata.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private CardView cv;
private TextView id,judul,harga;
private ImageView thumbnail;
public ViewHolder(View v) {
super(v);
cv=(CardView)v.findViewById(R.id.card_view);
id=(TextView)v.findViewById(R.id.id);
judul=(TextView)v.findViewById(R.id.judul);
harga=(TextView)v.findViewById(R.id.harga);
thumbnail=(ImageView)v.findViewById(R.id.thumbnail);
}
}
}
My Data code:
package untag.adproj.lestari.lestari.Home;
public class Data {
private String id;
private String judul;
private String harga;
private String thubnail;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getJudul() {
return judul;
}
public void setJudul(String judul) {
this.judul = judul;
}
public String getHarga() {
return harga;
}
public void setHarga(String harga) {
this.harga = harga;
}
public String getThubnail() {
return thubnail;
}
public void setThubnail(String thubnail) {
this.thubnail = thubnail;
}
}
My code refresh comes from Youtube
but in the tutorial it does not use fragment, please anyone help me
You have a wrong point, that is not update the list of recycler view, the list you add value in code listdata.add(item); belong to your fragment
Please add below method in your adapter
public void addData(List<Data> data) {
listdata.addAll(data);
notifyDataSetChanged();
}
And edit AmbilData function as below
private void AmbilData() {
JsonArrayRequest aarRequest = new JsonArrayRequest(URL + "/produk.php" ,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length()>0){
for (int i =0 ; i<response.length();i++){
try {
JSONObject data = response.getJSONObject(i);
Data item = new Data();
item.setId(data.getString("id"));
item.setJudul(data.getString("judul"));
item.setHarga(data.getString("harga"));
item.setThubnail(data.getString(URL+"/img/"+data.getString("gambar")));
listdata.add(item);
} catch (JSONException e) {
}
}
recyclerAdapter.addData(listdata);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
};
Volley.newRequestQueue(getActivity()).add(aarRequest);
}
package untag.adproj.lestari.lestari.Home;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import untag.adproj.lestari.lestari.R;
public class HomeFragment extends Fragment {
private String URL="http://pembuatanprogram.000webhostapp.com";
private RecyclerAdapter recyclerAdapter;
private RecyclerView recyclerView;
private ArrayList<Data> listdata;
private ArrayList<Data> tempList;
private GridLayoutManager gridLayoutManager;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
gridLayoutManager = new GridLayoutManager(getActivity(), 2);
gridLayoutManager.setOrientation(GridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(gridLayoutManager);
tempList = new ArrayList<Data>();
listdata = new ArrayList<Data>();
AmbilData();
recyclerAdapter = new RecyclerAdapter(getActivity(),listdata);
recyclerView.setAdapter(recyclerAdapter);
recyclerAdapter.notifyDataSetChanged();
return view;
}
private void AmbilData() {
JsonArrayRequest aarRequest = new JsonArrayRequest(URL + "/produk.php" ,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length()>0){
for (int i =0 ; i<response.length();i++){
try {
JSONObject data = response.getJSONObject(i);
Data item = new Data();
item.setId(data.getString("id"));
item.setJudul(data.getString("judul"));
item.setHarga(data.getString("harga"));
item.setThubnail(data.getString(URL+"/img/"+data.getString("gambar")));
tempList.add(item);
recyclerAdapter.notifyDataSetChanged();
} catch (JSONException e) {
}
}
listdata.clear();
listdata.addAll(tempList);
recyclerAdapter.notifyDataSetChanged();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
};
Volley.newRequestQueue(getActivity()).add(aarRequest);
}
}
Use temp list then addAll() method then call notifyDataSetChanged() method.
If you want to notify your adapter from a loop then you should go for notifyItemInserted() otherwise keep the notifyDataSetChanged() outside of the loop.
Like this;
for (int i =0 ; i<response.length();i++){
try {
JSONObject data = response.getJSONObject(i);
Data item = new Data();
item.setId(data.getString("id"));
item.setJudul(data.getString("judul"));
item.setHarga(data.getString("harga"));
item.setThubnail(data.getString(URL+"/img/"+data.getString("gambar")));
listdata.add(item);
recyclerAdapter.notifyItemInserted(listdata.size()-1); //To update the recyclerview one by one from a loop.
} catch (JSONException e) {
}
}
// OR
for (int i =0 ; i<response.length();i++){
try {
JSONObject data = response.getJSONObject(i);
Data item = new Data();
item.setId(data.getString("id"));
item.setJudul(data.getString("judul"));
item.setHarga(data.getString("harga"));
item.setThubnail(data.getString(URL+"/img/"+data.getString("gambar")));
listdata.add(item);
} catch (JSONException e) {
}
}
recyclerAdapter.notifyDataSetChanged(); //To update the whole recyclerview in one shot

Unable to make CustomAdapter work in a Loop using Fragments

I'm trying to fill make the data show in my Listview, however when i click on the fragment there is nothing on the list.
I've tried move the setAdapter inside the loop but it did not work.
I'm running out of ideas about how to make it work
Has anybody tried to fill an custom adapter with fragments before???
This is my Custom Adapter
import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
/**
* Created by calvi on 22/05/2018.
*/
public class MyListAdapter extends ArrayAdapter<User> {
List<User> userList;
Context context;
int resource;
public MyListAdapter(#NonNull Context context, #LayoutRes int resource, List<User> userList) {
super(context, resource, userList);
this.context = context;
this.resource = resource;
this.userList = userList;
}
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
//And for this we need a layoutinflater
LayoutInflater layoutInflater = LayoutInflater.from(context);
Log.d("listando", "Antes do inflater");
//getting the view
View view = layoutInflater.inflate(resource, null, false);
Log.d("listando", "Depois do inflater");
//getting the view elements of the list from the view
TextView textViewName = view.findViewById(R.id.list_row);
Log.d("listando", "Depois de pegar o textview");
//getting the hero of the specified position
User user = userList.get(position);
Log.d("listando", "Depois de pegar o get pisition");
//adding values to the list item
textViewName.setText(user.getName());
Log.d("listando", "Depois de setar o name");
//finally returning the view
return view;
}
}
And this is my Fragment which are taking data from firebase and populating it on the adapter
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.GenericTypeIndicator;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class UserMessageListFragment extends Fragment {
private ProgressDialog progressDialog;
private final String TAG = "UsersMessageLis";
private ArrayList<String> arrayList = new ArrayList<>();
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
private int totalUsers = 0;
private ListView listView;
private TextView noUsersText;
private List<User> userList = new ArrayList<>();
public static UserMessageListFragment newInstance() {
return new UserMessageListFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_user_message_list, container, false);
listView = view.findViewById(R.id.usersListListView);
noUsersText = view.findViewById(R.id.noUsersText);
final DatabaseReference refMessages = FirebaseDatabase.getInstance().getReference();
final DatabaseReference ref= FirebaseDatabase.getInstance().getReference().child("usuarios");
refMessages.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if(dataSnapshot.getKey().contains(UserDetails.username+ "_")) {
final String[] userChatWithId = dataSnapshot.getKey().split(UserDetails.username+"_");
ref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if(dataSnapshot.getKey().equals(userChatWithId[1])) {
GenericTypeIndicator<Map<String, String>> genericTypeIndicator = new GenericTypeIndicator<Map<String, String>>() {};
Map<String, String> map = dataSnapshot.getValue(genericTypeIndicator);
String name = map.get("name").toString();
String username = map.get("username").toString();
String status = map.get("status").toString();
String city = map.get("city").toString();
Log.d("listando", name);
Log.d("listando", username);
Log.d("listando", status);
Log.d("listando", city);
User newUser = new User(username, status, city, name);
Log.d("Listando", newUser.toString());
userList.add(newUser);
//// usersList.setAdapter(new ArrayAdapter<>(getContext(), R.layout.my_list, arrayList));
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
MyListAdapter adapter = new MyListAdapter(getContext(), R.layout.my_list, userList);
//attaching adapter to the listview
listView.setAdapter(adapter);
// listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
// #Override
// public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// UserDetails.chatWithId = arrayList.get(position);
// startActivity(new Intent(getContext(), Chat.class));
// }
// });
return view;
}
// public void doOnSuccess(String response) {
//
// try {
// JSONObject object = new JSONObject(response);
// Iterator iterator = object.keys();
// String key = "";
//
// while(iterator.hasNext()) {
// key = iterator.next().toString();
//
// if(! key.equals(UserDetails.username)) {
// arrayList.add(key);
// }
// totalUsers++;
// }
//
// } catch (JSONException e) {
// e.printStackTrace();
// }
//
// checkIfThereIsAnUser(totalUsers);
// }
// public void checkIfThereIsAnUser(int totalUsers) {
//
//
// if(totalUsers <=1){
// noUsersText.setVisibility(View.VISIBLE);
// usersList.setVisibility(View.GONE);
// }
// else{
// noUsersText.setVisibility(View.GONE);
// usersList.setVisibility(View.VISIBLE);
// usersList.setAdapter(new ArrayAdapter<>(getContext(), R.layout.my_list, arrayList));
// }
// progressDialog.dismiss();
// }
}
What i have noticed is that the logs inside the adapter are not showing
When you create adapter
MyListAdapter adapter = new MyListAdapter(getContext(), R.layout.my_list, userList);
the userList is empty. So when you add an item to userList, you have to adapter.notifyDataSetChange() to update your adapter
Try refMessages.addChildEventListener(getActivity(),new ChildEventListener() {......}
Do this in every listeners if they are in fragments.
In case of an Activity you don't need to do this.

ReyclerView. Police Data Json - No adapter attached, skipping layout

Good afternoon guys, I am trying to fetch some data from the police data website.
Unfortunately, the application doesn't show any data saying "E/RecyclerView: No adapter attached; skipping layout".
I have attached the LatestCrimesActivity, adapter and the ListItem class.
Thank you for your help.
This is LatestCrimesActivity:
package com.example.cosmin.crimerate.Latest_crimes_api;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.cosmin.crimerate.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class LatestCrimesActivity extends AppCompatActivity {
private static final String URL_DATA = "https://data.police.uk/api/crimes-street/all-crime?poly=52.268,0.543:52.794,0.238:52.130,0.478&date=2017-01";
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<ListItem> listItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_latest_crimes);
recyclerView = (RecyclerView) findViewById(R.id.recyclerViewlatest);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems=new ArrayList<>();
loadRecyclerViewData();
}
private void loadRecyclerViewData() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading data...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET,
URL_DATA,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray array = jsonObject.getJSONArray("");
for (int i=0; i<array.length();i++){
JSONObject o = array.getJSONObject(i);
ListItem item = new ListItem(
o.getString("category"),
o.getString("location_type"),
o.getString("street"),
o.getString("status")
);
listItems.add(item);
}
adapter = new MyAdapter(listItems, getApplicationContext());
recyclerView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Adapter:
package com.example.cosmin.crimerate.Latest_crimes_api;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.TextView;
import com.example.cosmin.crimerate.R;
import java.util.List;
/**
* Created by Cosmin on 25/11/2017.
*/
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<ListItem> listItems;
private Context context;
public MyAdapter(List<ListItem> listItems, LatestCrimesActivity latestCrimesActivity) {
this.listItems = listItems;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
ListItem listItem = listItems.get(position);
holder.textViewCat.setText(listItem.getCategory());
holder.textViewLoc.setText(listItem.getLocation());
holder.textViewStreet.setText(listItem.getStreet());
holder.textViewStatus.setText(listItem.getStatus());
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView textViewCat;
public TextView textViewLoc;
public TextView textViewStreet;
public TextView textViewStatus;
public ViewHolder(View itemView) {
super(itemView);
textViewCat = (TextView) itemView.findViewById(R.id.textViewCat);
textViewLoc = (TextView) itemView.findViewById(R.id.textViewLoc);
textViewStreet = (TextView) itemView.findViewById(R.id.textViewStreet);
textViewStatus = (TextView) itemView.findViewById(R.id.textViewStatus);
}
}
}
This is ListItem class:
package com.example.cosmin.crimerate.Latest_crimes_api;
/**
* Created by Cosmin on 25/11/2017.
*/
public class ListItem {
private String category;
private String location;
private String street;
private String status;
public ListItem (String category, String location, String street, String status){
this.category=category;
this.location=location;
this.street=street;
this.status=status;
}
public String getCategory (){
return category;
}
public String getLocation (){
return location;
}
public String getStreet (){
return street;
}
public String getStatus (){
return status;
}
}
Just try to change some lines. First set adapter before your api call.
recyclerView = (RecyclerView) findViewById(R.id.recyclerViewlatest);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems=new ArrayList<>();
adapter = new MyAdapter(listItems, getApplicationContext());
recyclerView.setAdapter(adapter);
Then when you received the answer, fill listItems, then call notifyDataSetChange() method of your adapter object.

LinkedHashMap error in SimpleAdapter

I've an error in my simpleAdapter on 'map' and can't resolve it. I've created a LinkedHashMap through a json file.
See screenshot below. I assume it's correct. This screenshot is only for seeing the content of the array.
See my code below:
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.LinkedHashMap;
public class BlogFragment extends Fragment {
View myView;
ArrayList<String> lists = new ArrayList<>();
ListView lv = (ListView) myView.findViewById(R.id.listView);
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.blog_layout, container, false);
new AsyncTaskParseJson().execute();
return myView;
}
public class AsyncTaskParseJson extends AsyncTask<LinkedHashMap, LinkedHashMap, LinkedHashMap> {
String url = "myUrl"; // Link to json file
JSONArray dataJsonArr = null;
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(getActivity(), "", "Loading blog ...");
}
#Override
protected LinkedHashMap<Integer, ArrayList<String>> doInBackground(LinkedHashMap... params) {
LinkedHashMap<Integer, ArrayList<String>> map = new LinkedHashMap<>();
try {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
dataJsonArr = json.getJSONArray("blog");
for (int i = dataJsonArr.length()-1; i >= 0 ; i--) {
JSONObject c = dataJsonArr.getJSONObject(i);
String afb = c.getString("afbeelding");
String tt = c.getString("titel");
String inh = c.getString("inhoud");
lists = new ArrayList<>();
lists.add(tt);
lists.add(afb);
lists.add(inh);
map.put(i,lists);
}
} catch (JSONException e) {
e.printStackTrace();
}
return map;
}
#Override
protected void onPostExecute(LinkedHashMap map) {
dialog.dismiss();
String[] from = new String[]{"6", "5", "4", "3", "2", "1"};
int[] to = new int[]{R.id.textView, R.id.textView2, R.id.textView3};
//Map<String, ArrayList<String>> map1 = new LinkedHashMap<>(map);
SimpleAdapter simpleAdapter;
simpleAdapter = new SimpleAdapter(getActivity(), map, R.layout.blog_layout, from, to); // <<< **I get an error on 'map'**
lv.setAdapter(simpleAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getActivity(), Detail.class);
i.putExtra("string", Long.toString(id));
startActivity(i);
}
});
}}}
I already tried to convert LinkedHashMap to Map but it didn't resolve the issue.
Can someone help me, please?
Thank you!

Custom ListView with Asynctask not working in Fragment

My Fragment is not showing custom listview data. Asynctask is working properly but after sometime application is crashing with null pointer exception.
My fragment class code :
package com.example.y34h1a.androidlime.Fragment;
import android.app.ProgressDialog;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.example.y34h1a.androidlime.R;
import com.example.y34h1a.androidlime.adapter.FeedListAdapter;
import com.example.y34h1a.androidlime.data.FeedItem;
import com.example.y34h1a.androidlime.network.VolleySigleton;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
public class FragmentBoxOffice extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private VolleySigleton volleySigleton;
private ImageLoader imageLoader;
private RequestQueue requestQueue;
private OnFragmentInteractionListener mListener;
private static final String TAG = FragmentBoxOffice.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private ArrayList<FeedItem> feedItems;
private String URL_FEED = "http://androidlime.com/wp-json/posts";
private FeedItem feedItem = new FeedItem();
// TODO: Rename and change types and number of parameters
public static FragmentBoxOffice newInstance(String param1, String param2) {
FragmentBoxOffice fragment = new FragmentBoxOffice();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public FragmentBoxOffice() {
// Required empty public constructor
feedItems = new ArrayList<FeedItem>();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_box_office, container, false);
listView = (ListView) view.findViewById(R.id.fragmentList);
new JSONAsyncTask().execute(URL_FEED);
return view;
}
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(getActivity());
dialog.setMessage("Loading...");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
for(String url : urls){
try {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject titleObj = jsonArray.getJSONObject(i);
String title = titleObj.getString("title");
feedItem.setStatus(title);
Log.i("arif", title);
//DATE
String date = titleObj.getString("date");
feedItem.setTimeStamp(date);
Log.i("arif", date);
//Author Name
JSONObject author = titleObj.getJSONObject("author");
String name = author.getString("name");
feedItem.setName(name);
Log.i("arif", name);
//Author Profile Pic
String profilePic = author.getString("avatar");
feedItem.setProfilePic(profilePic);
Log.i("arif", profilePic);
//Post thumbnail
JSONObject thumnailObj = titleObj.getJSONObject("featured_image");
String thumbnail = thumnailObj.getString("guid");
feedItem.setThumnail(thumbnail);
Log.i("arif", thumbnail);
feedItems.add(feedItem);
}
return true;
//------------------>>
} catch (IOException e) {
Log.e("arif", "Parse Exception");
} catch (JSONException e) {
Log.e("arif", "Parse Exception");
}
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
listAdapter = new FeedListAdapter(getActivity().getApplicationContext(),R.layout.feed_item,feedItems);
listView.setAdapter(listAdapter);
if(result == false)
Log.i("arif","unable to featch data");
}
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
}
My Custom Adapter Class:
package com.example.y34h1a.androidlime.adapter;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.y34h1a.androidlime.R;
import com.example.y34h1a.androidlime.data.FeedItem;
import java.util.ArrayList;
import java.util.List;
public class FeedListAdapter extends ArrayAdapter<FeedItem> {
private LayoutInflater vi;
private List<FeedItem> feedItems;
int Resource;
ViewHolder holder;
public FeedListAdapter(Context context, int resource, ArrayList<FeedItem> feedItems) {
super(context, resource, feedItems);
this.feedItems = feedItems;
Resource = resource;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// convert view = design
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = ((Activity)getContext()).getLayoutInflater().inflate(R.layout.feed_item,null);
holder.name = (TextView) v.findViewById(R.id.name);
holder.status = (TextView) v.findViewById(R.id.txtStatusMsg);
holder.time = (TextView) v.findViewById(R.id.timestamp);
holder.url = (TextView) v.findViewById(R.id.txtUrl);
holder.profilePic = (ImageView) v.findViewById(R.id.profilePic);
holder.thumbnail = (ImageView) v.findViewById(R.id.thumbernail);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
v.setTag(holder);
holder.name.setText(feedItems.get(position).getName());
holder.status.setText(feedItems.get(position).getStatus());
holder.time.setText(feedItems.get(position).getTimeStamp());
holder.url.setText(feedItems.get(position).getUrl());
holder.profilePic.setImageResource(R.drawable.ic_launcher);
holder.profilePic.setImageResource(R.drawable.sample);
return v;
}
static class ViewHolder {
public TextView name;
public TextView status;
public TextView url;
public TextView time;
public ImageView profilePic;
public ImageView thumbnail;
}
}
The line where error showing is :
View v = ((Activity)getContext()).getLayoutInflater().inflate(R.layout.feed_item,null);'
From your code, I think your error is more like ClassCastException, don't know why it's NPE, because
listAdapter = new FeedListAdapter(getActivity().getApplicationContext(),R.layout.feed_item,feedItems);
You pass a ApplicationContext then cast it to a Activity
v = ((Activity)getContext()).getLayoutInflater().inflate(R.layout.feed_item,null);
Try this may works:
in onPostExecute:
if (getActivity() != null) {
listAdapter = new FeedListAdapter(getActivity().getApplicationContext(),R.layout.feed_item,feedItems);
listView.setAdapter(listAdapter);
}
in getView:
v = LayoutInflater.from(parent.getContext()).inflate(R.layout.feed_item, parent, false);
Try:
v = (LayoutInflater.from(getContext()).inflate(R.layout.feed_item, parent, false);

Categories

Resources