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.
Related
I want to display what my array list value is. So, I want to loop with the size of array list as the limit. But after I add some value through a function, and want to get the size of it, it always 0. I still newbie in android programming. I had search in google, but still confused and not understand what the problem is. Thanks for you guys help
I had tried to set through global variable, but it's not work
Here is my activity file
package bobby.irawan.aticket;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
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.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
public class DetailPromoActivity extends AppCompatActivity {
private ListView listView;
private TextView nama_detail_promo_tv;
private String nama_detail_promo;
private DetailPromoAdapter adapter;
private int counter_header=0, counter_promo = 0;
private View layout_kupon;
private int id_link_promo;
private RequestQueue requestQueue;
private String url = "192.168.11.134:8000";
private TextView header_promo, kupon_promo, notif_promo;
private ArrayList<DetailPromo> detailPromos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail_promo);
View view = findViewById(R.id.layout_kupon);
header_promo = view.findViewById(R.id.header_promo_tv);
kupon_promo = view.findViewById(R.id.kode_promo_tv);
id_link_promo = (int) getIntent().getSerializableExtra("id_promo");
nama_detail_promo = (String) getIntent().getSerializableExtra("nama_promo");
String nama_ota = (String) getIntent().getSerializableExtra("nama_ota");
listView = findViewById(R.id.lv_detpro);
layout_kupon = findViewById(R.id.layout_kupon);
header_promo = layout_kupon.findViewById(R.id.header_promo_tv);
kupon_promo = layout_kupon.findViewById(R.id.kode_promo_tv);
notif_promo = layout_kupon.findViewById(R.id.notif_promo_tv);
requestQueue = Volley.newRequestQueue(this);
nama_detail_promo_tv = findViewById(R.id.nama_detail_promo);
nama_detail_promo_tv.setText(nama_detail_promo);
setDetailPromotoClass(id_link_promo);
adapter = new DetailPromoAdapter(detailPromos,this);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("Promo "+nama_ota);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
//Set kupon
System.out.println("Size detpro "+counter_header+" "+counter_promo);
if(counter_header == 0 && counter_promo == 0){
notif_promo.setVisibility(View.VISIBLE);
header_promo.setVisibility(View.GONE);
kupon_promo.setVisibility(View.GONE);
System.out.println("Masuk sini");
}
else if(counter_header == 0){
header_promo.setText("PROMO PESAWAT");
}
else{
kupon_promo.setText("Tidak perlu");
}
}
class DetailPromoAdapter extends BaseAdapter {
private List<DetailPromo> detailPromo;
private Context context;
public DetailPromoAdapter(List<DetailPromo> detailPromo, Context context) {
this.detailPromo = detailPromo;
this.context = context;
}
#Override
public int getCount() {
System.out.println("Detail promo size"+detailPromo.size());
return detailPromo.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = getLayoutInflater().inflate(R.layout.detail_promo_adapter, parent, false);
TextView nama_detail_promo = convertView.findViewById(R.id.isi_detail_promo);
if(detailPromo.get(position).getDetpro_role().equals("detail_promo")){
nama_detail_promo.setText(detailPromo.get(position).getDetpro_list());
}
return convertView;
}
}
public void setDetailPromotoClass(int id_linkpro){
detailPromos = new ArrayList<DetailPromo>();
String url_promo = "http://"+url+"/detail_promo/"+id_linkpro;
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url_promo, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("data");
for(int i=0; i<jsonArray.length(); i++){
JSONObject data_promo = jsonArray.getJSONObject(i);
int id_detpro = data_promo.getInt("id");
int id_promo = data_promo.getInt("promo_id");
int id_linkpro = data_promo.getInt("linkpro_id");
String detpro_list = data_promo.getString("detpro_list");
String detpro_role = data_promo.getString("detpro_role");
detailPromos.add(new DetailPromo(id_detpro,id_promo,id_linkpro,detpro_list,detpro_role));
System.out.println("Data promo yang diklik "+id_promo+" "+id_linkpro+" "+detpro_list+" "+detpro_role);
adapter.notifyDataSetChanged();
if(detpro_role.equals("header_promo")){
header_promo.setText(detailPromos.get(i).detpro_list);
System.out.println("Ada header");
counter_header++;
}
if(detpro_role.equals("kode_promo")){
System.out.println("Ada kupon");
kupon_promo.setText(detailPromos.get(i).detpro_list);
counter_promo++;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
requestQueue.add(request);
}
}
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
I checked all the previous questions regarding this issue, but none of them are helpful to me.
I am trying to open new activity in my listview onItemClickListener but it is not opening the new activity. In the android monitor, it shows
"D/ViewRootImpl: ViewPostImeInputStage ACTION_DOWN".
The onItemClickListener is not responding when I click that item of my listview... Is it possible to open?
The activity is successfully running, but I am unable to listen for list click events.
How to correct this?
Here is my class :
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
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.banyan.simtaa_erp.R;
import com.example.banyan.simtaa_erp.activity.Activity_Add_Enquiry;
import com.example.banyan.simtaa_erp.activity.Activity_Enquiry_Description;
import com.example.banyan.simtaa_erp.adapter.Adapter_Enquiry_List;
import com.example.banyan.simtaa_erp.global.App_Config;
import com.example.banyan.simtaa_erp.global.Session_Manager;
import com.sdsmdg.tastytoast.TastyToast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import dmax.dialog.SpotsDialog;
import static com.willy.ratingbar.BaseRatingBar.TAG;
public class Fragment_Enquiry_List extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
public Fragment_Enquiry_List() {
}
private FloatingActionButton fab_enquiry;
String str_user_name, str_user_id,str_select_task_id;
private ProgressDialog pDialog;
private SpotsDialog dialog_load_more;
public static RequestQueue queue;
Session_Manager session;
private SwipeRefreshLayout enquiry_list_swipe_refresh_layout;
private ListView enquiry_listView;
public static final String TAG_ID= "id";
public static final String TAG_CUSTOMER_ID = "cus_id";
public static final String TAG_IMAGE_ENQUIRY = "image";
public static final String TAG_DESCRIPTION = "description";
public static final String TAG_DATE_ENQUIRY = "date";
public static final String TAG_PROJECT_STATUS = "project_status";
public static final String TAG_CREATED_USERID = "created_userid";
public static final String TAG_CREATED_USERROLE = "created_userrole";
public static final String TAG_CREATED_DATETIME = "created_datetime";
public static final String TAG_CUSTOMER_DETAILS = "customer_details";
int int_starting_item_no = 0, int_last_item_no = 0, int_load_more_count = 100;
public Adapter_Enquiry_List Adapter;
static ArrayList<HashMap<String, String>> enquiry_list;
HashMap<String, String> params = new HashMap<String, String>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_enquiry_list, container, false);
session = new Session_Manager(getActivity());
session.checkLogin();
HashMap<String, String> user = session.getUserDetails();
str_user_id = user.get(Session_Manager.KEY_USER_ID);
str_user_name = user.get(Session_Manager.KEY_USER_NAME);
System.out.println("USER ID from Session ::::" + str_user_id);
System.out.println("USER NAME from Session ::::" + str_user_name);
enquiry_listView = (ListView) rootView.findViewById(R.id.list_enquiry_list);
fab_enquiry = (FloatingActionButton) rootView.findViewById(R.id.fab_enquiry);
enquiry_list_swipe_refresh_layout = (SwipeRefreshLayout) rootView.findViewById(R.id.enquiry_list_swipe_refresh_layout);
enquiry_list_swipe_refresh_layout.setOnRefreshListener(this);
enquiry_list = new ArrayList<HashMap<String, String>>()
enquiry_list_swipe_refresh_layout.post(new Runnable() {
#Override
public void run() {
try {
enquiry_list_swipe_refresh_layout.setRefreshing(true);
queue = Volley.newRequestQueue(getActivity().getApplicationContext());
Activity_Get_Enquiry_List(int_starting_item_no, int_load_more_count);
} catch (Exception e) {
}
}
});
enquiry_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
System.out.println("Event Trigered by Item" );
String str_enquiry_id = enquiry_list.get(position).get(TAG_ID);
String str_customer_id = enquiry_list.get(position).get(TAG_CUSTOMER_ID);
String str_image_enquiry = enquiry_list.get(position).get(TAG_IMAGE_ENQUIRY);
String str_description_enquiry = enquiry_list.get(position).get(TAG_DESCRIPTION);
String str_date_enquiry = enquiry_list.get(position).get(TAG_DATE_ENQUIRY);
String str_project_status = enquiry_list.get(position).get(TAG_PROJECT_STATUS);
String str_created_userid = enquiry_list.get(position).get(TAG_CREATED_USERID);
String str_created_userrole = enquiry_list.get(position).get(TAG_CREATED_USERROLE);
String str_created_datetime = enquiry_list.get(position).get(TAG_CREATED_DATETIME);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("enquiry_id", str_enquiry_id);
editor.putString("customer_id", str_customer_id);
editor.putString("image_enquiry", str_image_enquiry);
editor.putString("description_enquiry", str_description_enquiry);
editor.putString("date_enquiry", str_date_enquiry);
editor.putString("project_status", str_project_status);
editor.putString("created_userid", str_created_userid);
editor.putString("created_role", str_created_userrole);
editor.putString("created_datetime", str_created_datetime);
editor.commit();
Intent i = new Intent(getContext(),Activity_Enquiry_Description.class);
startActivity(i);
}
});
enquiry_listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int pos, long id) {
// TODO Auto-generated method stub
str_select_task_id = enquiry_list.get(pos).get(TAG_ID);
Delete_Task_alert();
return true;
}
});
return rootView;
}
private void Activity_Get_Enquiry_List(final int int_starting_item_no, final int int_load_more_count) {
StringRequest request = new StringRequest(Request.Method.POST, App_Config.url_list_enquiry, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG_CUSTOMER_DETAILS, response.toString());
Log.d("TAG_ENQUIRY_LIST", response.toString());
try {
JSONObject obj = new JSONObject(response);
System.out.println("REG 00" + obj);
int success = obj.getInt("success");
System.out.println("REG" + success);
if (success == 1) {
JSONArray enquiry = obj.getJSONArray("Enquiry");
for (int i = 0; enquiry.length() > i; i++) {
JSONObject obj_one = enquiry.getJSONObject(i);
String str_enquiry_id = obj_one.getString(TAG_ID);
String str_customer_id = obj_one.getString(TAG_CUSTOMER_ID);
String str_image_enquiry = obj_one.getString(TAG_IMAGE_ENQUIRY);
String str_description_enquiry = obj_one.getString(TAG_DESCRIPTION);
String str_date_enquiry = obj_one.getString(TAG_DATE_ENQUIRY);
String str_project_status = obj_one.getString(TAG_PROJECT_STATUS);
String str_created_userid = obj_one.getString(TAG_CREATED_USERID);
String str_created_userrole = obj_one.getString(TAG_CREATED_USERROLE);
String str_created_datetime = obj_one.getString(TAG_CREATED_DATETIME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, str_enquiry_id);
map.put(TAG_CUSTOMER_ID, str_customer_id);
map.put(TAG_IMAGE_ENQUIRY, str_image_enquiry);
map.put(TAG_DESCRIPTION, str_description_enquiry);
map.put(TAG_DATE_ENQUIRY, str_date_enquiry);
map.put(TAG_PROJECT_STATUS, str_project_status);
map.put(TAG_CREATED_USERID, str_created_userid);
map.put(TAG_CREATED_USERROLE, str_created_userrole);
map.put(TAG_CREATED_DATETIME, str_created_datetime);
enquiry_list.add(map);
System.out.println("HASHMAP ARRAY" + enquiry_list);
}
Adapter = new Adapter_Enquiry_List(getActivity(), enquiry_list);
enquiry_listView.setAdapter(Adapter);
enquiry_list_swipe_refresh_layout.setRefreshing(false);
} else {
TastyToast.makeText(getContext(), "OOPS FAILED TO LOAD", TastyToast.LENGTH_LONG, TastyToast.WARNING);
}
LoadMoreButtonVisible();
enquiry_list_swipe_refresh_layout.setRefreshing(false);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
enquiry_list_swipe_refresh_layout.setRefreshing(false);
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("user_id", str_user_id);
params.put("start",""+ int_starting_item_no);
params.put("limit",""+ int_load_more_count);
System.out.println("user_id " + str_user_id);
System.out.println("start " + int_starting_item_no);
System.out.println("limit " + int_load_more_count);
return params;
}
};
queue.add(request);
}
}
If there are clickable UI elements like Button, Imagebutton are present in child view of list/Recyclerview, they can take control of click events. So, Recyclerview would not get chance to click event.
Please set android:focusable="false" for all child clickable view. Then your itemclick will work.
You can also use following property in parent view that prevent child view getting focus.
android:descendantFocusability="blocksDescendants"
You implement wrong method of list item click listener, just replace this
enquiry_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
}
To:
enquiry_listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {}}
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.
im retrieving data in my database from firebase. and shoscription herew up this error can anyone help me? this is my mainactivity.java:
package com.example.infamouslegend.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
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.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
FirebaseDatabase database;
DatabaseReference myRef ;
List<FireModel> list;
RecyclerView recycle;
Button view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
view = (Button) findViewById(R.id.view);
recycle = (RecyclerView) findViewById(R.id.recycle);
database = FirebaseDatabase.getInstance();
myRef = database.getReference("Complaints");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
list = new ArrayList<FireModel>();
for(DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){
FireModel value = dataSnapshot.getValue(FireModel.class);
FireModel fire = new FireModel();
String Description = value.getDescription();
String Date = value.getDate();
String MediaURL = value.getMediaURL();
fire.setDescription(Description);
fire.setDate(Date);
fire.setMediaURL(MediaURL);
list.add(fire);
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w("Hello", "Failed to read value.", error.toException());
Toast.makeText(MainActivity.this, "Failed to read value !" + error.toException(), Toast.LENGTH_SHORT).show();
}
});
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RecyclerAdapter recyclerAdapter = new RecyclerAdapter(list,MainActivity.this);
RecyclerView.LayoutManager recyce = new GridLayoutManager(MainActivity.this,2);
/// RecyclerView.LayoutManager recyce = new LinearLayoutManager(MainActivity.this);
// recycle.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true));
recycle.setLayoutManager(recyce);
recycle.setItemAnimator( new DefaultItemAnimator());
recycle.setAdapter(recyclerAdapter);
}
});
}
}
and this is my firemodel.java:
package com.example.infamouslegend.myapplication;
/**
* Created by Infamous Legend on 10/15/2017.
*/
public class FireModel {
public String Description;
public String Date;
public String MediaURL;
public String getDescription() {
return Description;
}
public void setDescription(String description) {
this.Description = description;
}
public String getDate() {
return Date;
}
public void setDate(String date) {
this.Date = date;
}
public String getMediaURL() {
return MediaURL;
}
public void setMediaURL(String MediaURL) {
this.MediaURL = MediaURL;
}
}
and my recycleradapter.java:
package com.example.infamouslegend.myapplication;
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.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.List;
/**
* Created by Infamous Legend on 10/15/2017.
*/
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.MyHoder>{
List<FireModel> list;
Context context;
public RecyclerAdapter(List<FireModel> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public MyHoder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.card,parent,false);
MyHoder myHoder = new MyHoder(view);
return myHoder;
}
#Override
public void onBindViewHolder(MyHoder holder, int position) {
FireModel mylist = list.get(position);
holder.Description.setText(mylist.getDescription());
holder.Date.setText(mylist.getDate());
//holder.MediaURL.setText(mylist.getMediaURL());
//Picasso.with(context).load(MediaURL.get(position).getMediaURL()).resize(120, 60).into(MyHoder.MediaURL);
}
#Override
public int getItemCount() {
int arr = 0;
try{
if(list.size()==0){
arr = 0;
}
else{
arr=list.size();
}
}catch (Exception e){
}
return arr;
}
class MyHoder extends RecyclerView.ViewHolder{
TextView Description,Date;
//ImageView MediaURL;
public MyHoder(View itemView) {
super(itemView);
Description = (TextView) itemView.findViewById(R.id.vname);
Date= (TextView) itemView.findViewById(R.id.vemail);
//MediaURL= (ImageView) itemView.findViewById(R.id.thumbnail);
}
}
}
Can anyone help me this? Im trying to retrieve data from firebase database to recyclerview with cardview. Thanks in advance
this is my firebase realtime database rule:
{
"rules": {
".read": true,
".write":true
}
}
If you have configured the app to connect with firebase correctly i would redownload the google-service.json and replace with an existing one.
check this solution