com.google.firebase.database.databaseexception:firebase database error: Permission denied - android

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

Related

How to search using an edit text in a recyclerview?

I am looking some help for my application. I've built an app and i've included a chat feature. Within the chat fragment I have 2 additional fragments, one for chats currently open and one for all users which can be messaged. I want to incorroprate a search bar into each of these fragements to allow the user to find a certain user to message. I am
users fragment XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/gold"
tools:context=".ChatFragments.UsersFragment">
<EditText
android:id="#+id/etSearch"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#android:color/white"
android:ems="20"
android:hint="#string/search"
android:layout_weight="0.5"
android:paddingLeft="15dp" />
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_below="#+id/etSearch"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
users fragment java class
package com.alicearmstrong.coffeysloyaltyprojectv1.ChatFragments;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import com.alicearmstrong.coffeysloyaltyprojectv1.Adapter.CustomerAdapter;
import com.alicearmstrong.coffeysloyaltyprojectv1.R;
import com.alicearmstrong.coffeysloyaltyprojectv1.database.Customers;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
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 UsersFragment extends Fragment {
private RecyclerView recyclerView;
private CustomerAdapter customerAdapter;
private List<Customers> customersList;
DatabaseReference databaseReference;
EditText etSearch;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Inflate the layout for this fragment
View view = inflater.inflate( R.layout.fragment_users , container, false);
etSearch = view.findViewById(R.id.etSearch);
recyclerView = view.findViewById( R.id.recycler_view );
recyclerView.setHasFixedSize( true );
recyclerView.setLayoutManager( new LinearLayoutManager( getContext() ) );
customersList = new ArrayList<>( );
readCustomers();
return view;
}
// Method for reading customers
private void readCustomers()
{
final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
databaseReference = FirebaseDatabase.getInstance().getReference().child("Customers");
databaseReference.addValueEventListener( new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot)
{
customersList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren())
{
Customers customers = snapshot.getValue(Customers.class);
if (!customers.getId().equals(firebaseUser.getUid()))
{
customersList.add( customers );
}
}
customerAdapter = new CustomerAdapter( getContext(), customersList );
recyclerView.setAdapter( customerAdapter );
}
#Override
public void onCancelled( #NonNull DatabaseError databaseError) {
}
} );
}
}
customerAdapter.java
package com.alicearmstrong.coffeysloyaltyprojectv1.Adapter;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import com.alicearmstrong.coffeysloyaltyprojectv1.uiOwner.chatOwner.MessageActivityOwner;
import com.alicearmstrong.coffeysloyaltyprojectv1.R;
import com.alicearmstrong.coffeysloyaltyprojectv1.database.Customers;
import java.util.ArrayList;
import java.util.List;
public class CustomerAdapter extends RecyclerView.Adapter<CustomerAdapter.ViewHolder>
{
private Context context;
private List<Customers> customersList;
public CustomerAdapter (Context context, List<Customers> customersList)
{
this.customersList = customersList;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i)
{
// Set layout to user_item for displaying each user
View view = LayoutInflater.from(context).inflate( R.layout.user_item , viewGroup, false);
return new CustomerAdapter.ViewHolder( view );
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i)
{
final Customers customer = customersList.get( i );
// Set title to user's name
viewHolder.customerName.setText( customer.getFirstName() + " " + customer.getSurname() );
// Open Message Activity when user is selected
viewHolder.itemView.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent(context, MessageActivityOwner.class );
intent.putExtra( "userid", customer.getId() );
context.startActivity( intent );
}
} );
}
#Override
public int getItemCount()
{
return customersList.size();
}
/* #Override
public Filter getFilter() {
return exampleFilter;
}
private Filter exampleFilter = new Filter()
{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<Customers> filteredList = new ArrayList<>( );
if (constraint == null || constraint.length() == 0)
{
filteredList.addAll( customersList );
}
else
{
// allows search to be case sensitive
String filteredPattern = constraint.toString().toLowerCase().trim();
for(Customers customers : customersList )
{
}
}
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
}
};*/
public class ViewHolder extends RecyclerView.ViewHolder
{
public TextView customerName;
public ViewHolder(#NonNull View view)
{
super( view );
customerName = view.findViewById( R.id.customerName );
}
}
public void upToDate(List<Customers> newList){
customersList = new ArrayList<>();
customersList.addAll(newList);
notifyDataSetChanged();
}
}
customers database
package com.alicearmstrong.coffeysloyaltyprojectv1.database;
public class Customers
{
String id, firstName,surname, DOB, contactNumber, email, qrCode;
Integer loyaltyScore;
public Customers(String id, String firstName, String surname, String DOB, String contactNumber, String email, String qrCode, Integer loyaltyScore)
{
this.id = id;
this.firstName = firstName;
this.surname = surname;
this.DOB = DOB;
this.contactNumber = contactNumber;
this.email = email;
this.qrCode = qrCode;
this.loyaltyScore = loyaltyScore;
}
public String getId() {
return id;
}
public String getFirstName()
{
return firstName;
}
public String getSurname()
{
return surname;
}
public String getDOB()
{
return DOB;
}
public String getContactNumber()
{
return contactNumber;
}
public String getEmail()
{
return email;
}
public String getQrCode()
{
return qrCode;
}
public Integer getLoyaltyScore()
{
return loyaltyScore;
}
public Customers()
{
}
}
I read in to the addTextChangeListener method just not sure how to implement the method. Any help would be greatly appreciated.
why using textView when searchView is exsist. check this code below but let me see ur Customers java class then i can help u better. at the first set search view then find view by id it then ....
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
String userInput = newText.toLowerCase();
List<Customers> newList = new ArrayList<>();
for (Customers customersList : accounts) {
if (customersList.customerName.toLowerCase().contains(userInput)) {
newList.add(accountList);
}
}
accountAdapter.upToDate(newList);
return true;
}
});
then add upToDate function in ur adapter and call it at the above code.
public void upToDate(List<Customers> newList){
customersList = new ArrayList<>();
customersList.addAll(newList);
notifyDataSetChanged();
}

How to fetch Firebase data into arrays for recyclerview?

This is my HomeActivity
package my.unimas.a50200siswa.studentattendancemonitoringsystem;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
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 HomeActivity extends AppCompatActivity {
String userID;
List<CourseModel> mlist;
TextView btnSignOut, UserName;
RecyclerView courseRecycler;
String CourseCode, CourseName;
/*---- Firebase Database stuff ----*/
FirebaseDatabase mFirebaseDatabase;
FirebaseAuth mAuth;
FirebaseUser user;
FirebaseAuth.AuthStateListener mAuthListener;
DatabaseReference myRef;
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
/*-------Finding View---------*/
Button btnShow = findViewById(R.id.show);
btnSignOut = (TextView) findViewById(R.id.btnsignout_home);
UserName = findViewById(R.id.username);
courseRecycler = findViewById(R.id.recyclerviewcourse);
btnSignOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAuth.signOut();
}
});
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() == null) {
startActivity(new Intent(HomeActivity.this, SignInActivity.class));
}
}
};
/* ----------------- Firebase Elements -----------------*/
mAuth = FirebaseAuth.getInstance();
user = mAuth.getCurrentUser();
userID = user.getUid();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getInstance().getReference();
UserName.setText(user.getDisplayName());
/*------------------------------------------------------------------*/
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.
mlist = new ArrayList<CourseModel>();
for (DataSnapshot dataSnapshot1 : dataSnapshot.child("Users").child(userID).child("Courses").getChildren()) {
CourseModel value = dataSnapshot1.getValue(CourseModel.class);
CourseModel course = new CourseModel();
String userID = value.getUserId();
course.setUserId(userID);
String courseCode = value.getCourseCode();
course.setCourseCode(courseCode);
for (DataSnapshot dataSnapshot2 : dataSnapshot1.child("CourseName").getChildren()) {
CourseModel value2 = dataSnapshot2.getValue(CourseModel.class);
String courseName = value2.getCourseName();
course.setCourseName(courseName);
mlist.add(course);
}
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w("Hello", "Failed to read value.", error.toException());
}
});
RecyclerViewAdapterCourse recyclerAdapter = new RecyclerViewAdapterCourse(mlist, HomeActivity.this);
RecyclerView.LayoutManager recycler = new GridLayoutManager(HomeActivity.this, 2);
/// RecyclerView.LayoutManager recyce = new LinearLayoutManager(MainActivity.this);
// recycle.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true));
courseRecycler.setLayoutManager(recycler);
courseRecycler.setItemAnimator(new DefaultItemAnimator());
courseRecycler.setAdapter(recyclerAdapter);
}
}
This is My RecyclerViewCourse.class
package my.unimas.a50200siswa.studentattendancemonitoringsystem;
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.TextView;
import java.util.List;
class RecyclerViewAdapterCourse extends RecyclerView.Adapter<RecyclerViewAdapterCourse.CourseViewHolder> {
private Context mContext ;
private List<CourseModel> mlist ;
public RecyclerViewAdapterCourse(List<CourseModel> mData, Context mContext) {
this.mContext = mContext;
this.mlist = mData;
}
#Override
public CourseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view =LayoutInflater.from(mContext).inflate(R.layout.item_course,parent,false);
CourseViewHolder courseViewHolder = new CourseViewHolder(view);
return courseViewHolder;
}
#Override
public void onBindViewHolder(CourseViewHolder holder, int position) {
CourseModel courselist = mlist.get(position);
holder.userID.setText(courselist.getUserId());
holder.courseCode.setText(courselist.getCourseCode());
holder.courseName.setText(courselist.getCourseName());
}
#Override
public int getItemCount() {
int arr = 0;
try{
if(mlist.size()==0){
arr = 0;
}
else{
arr=mlist.size();
}
}catch (Exception e){
}
return arr;
}
class CourseViewHolder extends RecyclerView.ViewHolder{
TextView userID,courseCode,courseName;
public CourseViewHolder(View itemView) {
super(itemView);
userID = (TextView) itemView.findViewById(R.id.userid);
courseCode= (TextView) itemView.findViewById(R.id.coursecode);
courseName= (TextView) itemView.findViewById(R.id.coursename);
}
}
}
This is My CourseModel.class
package my.unimas.a50200siswa.studentattendancemonitoringsystem;
public class CourseModel {
public String UserId, CourseCode, CourseName;
public String getUserId() {
return UserId;
}
public String getCourseCode() {
return CourseCode;
}
public String getCourseName() {
return CourseName;
}
public void setUserId(String userid) {
this.UserId = userid;
}
public void setCourseCode(String coursecode) {
this.CourseCode = coursecode;
}
public void setCourseName(String coursename) {
this.CourseCode = coursename;
}
}
I want the array list like:
{"***", "TMI4013", "System Programming"}
{"***", "TMI4033", "LogicProgramming"}
I am not really experienced with firebase data retrieval in array. I tried many answers posted in stack. none worked. in some answers, sometime it shows data after a while and then in the realtime database the data get removed, i don't even understand why.
I did not provide the XML files since I tried with local file and generating array in HomeActivity and it worked perfectly.
mlist = new ArrayList<>();
mlist.add(new CourseModel("012223","TMN4013","System Programming"));
mlist.add(new CourseModel("34566","TMN4013","System Programming"));
RecyclerView myrv = (RecyclerView) findViewById(R.id.recyclerview_id);
RecyclerViewAdapter myAdapter = new RecyclerViewAdapter(this,mlist);
myrv.setLayoutManager(new GridLayoutManager(this,3));
myrv.setAdapter(myAdapter);
Retrieve data from firebase and convert list into array like this
for (DataSnapshot dataSnapshot1 : dataSnapshot.child("Users").child(userID).child("Courses").getChildren()) {
CourseModel value = dataSnapshot1.getValue(CourseModel.class);
CourseModel course = new CourseModel();
String userID = value.getUserId(); course.setUserId(userID);
String courseCode = value.getCourseCode();
course.setCourseCode(courseCode);
for (DataSnapshot dataSnapshot2 : dataSnapshot1.child("CourseName").getChildren()) {
CourseModel value2 = dataSnapshot2.getValue(CourseModel.class);
String courseName = value2.getCourseName();
course.setCourseName(courseName);
mlist.add(course);
}
}
CourseModel[] array = mlist.toArray(new CourseModel[mlist.size()]);
EDIT:
Change your adapter like this
RecyclerViewAdapter myAdapter = new RecyclerViewAdapter(this, array);
Change the constructor of recyclerView to CourseModel array
public RecyclerViewAdapterCourse(CourseModel[] mData, Context mContext) {
this.mContext = mContext;
this.mArray = mData;
}
#Override
public void onBindViewHolder(CourseViewHolder holder, int position) {
CourseModel courselist = marray[position];
holder.userID.setText(courselist.getUserId());
holder.courseCode.setText(courselist.getCourseCode());
holder.courseName.setText(courselist.getCourseName());
}

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.

Loading Data from Firebase into Recycleview using Fragments

Can anyone help me with this firebase recycler view using fragments issue? I am having a problem with retrieving the data from firebase to my recycler view. I am using fragments and the app crashes everytime I run it.
Here's my code:
SubjecList.java
package com.google.myeclassrecordapp.mye_classrecord;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import org.w3c.dom.Text;
public class SubjectsList extends Fragment {
private View view;
private Context c;
private RecyclerView myTimeline;
private FirebaseDatabase databaseReference;
private DatabaseReference mFireDatabasaeRef;
private LinearLayoutManager mananger;
private RecyclerView mRecyclerView;
FirebaseRecyclerAdapter<ScheduleListAdapter, ViewHolder> firebaseRecyclerAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = LayoutInflater.from(container.getContext())
.inflate(R.layout.schedule_model, container, false);
mFireDatabasaeRef = FirebaseDatabase.getInstance().getReference().child("SubjectsList");
c = getContext();
mRecyclerView = (RecyclerView) view.findViewById(R.id.rcsched);
mananger = new LinearLayoutManager(c);
mRecyclerView.setHasFixedSize(true);
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<ScheduleListAdapter, ViewHolder>(
ScheduleListAdapter.class,
R.layout.schedule_model,
ViewHolder.class,
mFireDatabasaeRef
)
{
#Override
protected void populateViewHolder(ViewHolder viewHolder, ScheduleListAdapter model, int position) {
viewHolder.setSubjectCode(model.getSubjectCode());
viewHolder.setSection(model.getSection());
viewHolder.setTime(model.getTime());
viewHolder.setDay(model.getDay());
viewHolder.setRoom(model.getRoom());
}
};
mRecyclerView.setAdapter(firebaseRecyclerAdapter);
firebaseRecyclerAdapter.notifyDataSetChanged();
//mRecyclerView.setLayoutManager(mananger);
return view;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
View mView;
public ViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setSubjectCode(String subjectcode){
TextView txtSubjectCode = (TextView) itemView.findViewById(R.id.txtsubjectcode);
txtSubjectCode.setText(subjectcode);
}
public void setSection(String section){
TextView txtSection = (TextView) itemView.findViewById(R.id.txtsection);
txtSection.setText(section);
}
public void setTime(String time){
TextView txtTime = (TextView) itemView.findViewById(R.id.txttime);
txtTime.setText(time);
}
public void setDay(String day){
TextView txtDay = (TextView) itemView.findViewById(R.id.txtday);
txtDay.setText(day);
}
public void setRoom(String room){
TextView txtRoom = (TextView) itemView.findViewById(R.id.txtroom);
txtRoom.setText(room);
}
}
}
ScheduleListAdapater.java
package com.google.myeclassrecordapp.mye_classrecord;
/**
* Created by Pau-Le on 5/12/17.
*/
public class ScheduleListAdapter {
private String SubjectCode;
private String Section;
private String Time;
private String Day;
private String Room;
public ScheduleListAdapter() {
}
public ScheduleListAdapter(String subjectCode, String section, String time, String day, String room) {
SubjectCode = subjectCode;
Section = section;
Time = time;
Day = day;
Room = room;
}
public String getSubjectCode() {
return SubjectCode;
}
public void setSubjectCode(String subjectCode) {
SubjectCode = subjectCode;
}
public String getSection() {
return Section;
}
public void setSection(String section) {
Section = section;
}
public String getTime() {
return Time;
}
public void setTime(String time) {
Time = time;
}
public String getDay() {
return Day;
}
public void setDay(String day) {
Day = day;
}
public String getRoom() {
return Room;
}
public void setRoom(String room) {
Room = room;
}
}

Android Recycler View caching

I'm using volley to load data using JSON Parsing in to a recycler view. I've used recylcer view before, but somehow, the downloaded data is persistent this time, meaning its still there after the app is closed, maybe stays in cache. I'm not sure, what I'm doing wrong here. Any help is appreciated, thanks.
Edit: The application is storing downloaded data after the app is closed, which doesn't happen when using recycler view.
This is my Activity Class:
package com.example.recyclerview;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
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.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class PostActivity extends AppCompatActivity implements
OnItemClick{
private ArrayList<PostData> posts = new ArrayList<>();
private PostRecycleViewAdapter viewAdapter;
private String listingJsonUrl = "https://jsonplaceholder.typicode.com/posts/";
Toolbar toolbar;
private ProgressDialog progressDialog;
private RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
progressDialog = new ProgressDialog(this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(true);
final RecyclerView.LayoutManager viewLayoutManager = new LinearLayoutManager(getApplicationContext());
viewAdapter = new PostRecycleViewAdapter(posts);
final RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(viewLayoutManager);
recyclerView.setAdapter(viewAdapter);
viewAdapter.setClickListener(this);
new DownloadData().execute(listingJsonUrl);
}
#Override
public void onClick(View view, int position) {
final PostData data = posts.get(position);
String title;
int id;
Intent commentIntent = new Intent(this, CommentsActivity.class);
id = data.getId();
title = data.getTitle();
if(title.length() > 25){
title = title.substring(0,25);
title = title.concat("..");
}
commentIntent.putExtra("title",title) ;
commentIntent.putExtra("id", id);
startActivity(commentIntent);
}
class DownloadData extends AsyncTask<String, String, String>{
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
#Override
protected String doInBackground(String... url) {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url[0], new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
JSONArray jsonArray = new JSONArray(response.toString());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
PostData postData = new PostData(jsonObject.getInt("id"),jsonObject.getString("title"), jsonObject.getString("body"));
posts.add(postData);
viewAdapter.notifyDataSetChanged();
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("JsonError", error.getMessage());
}
});
getRequestQueue().add(jsonArrayRequest);
return null;
}
}
public RequestQueue getRequestQueue()
{
if (requestQueue == null)
{
requestQueue = com.android.volley.toolbox.Volley.newRequestQueue(getApplicationContext());
}
return requestQueue;
}
}
This is my RecyclerView Adapter Class:
package com.example.recyclerview;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class PostRecycleViewAdapter extends RecyclerView.Adapter<PostRecycleViewAdapter.ViewHolder>
{
private List<PostData> postData;
private OnItemClick itemClick;
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView title, body;
public ViewHolder(View view){
super(view);
title = (TextView) view.findViewById(R.id.title);
body = (TextView) view.findViewById(R.id.body);
view.setTag(view);
view.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if(itemClick != null) itemClick.onClick(view, getAdapterPosition());
}
}
public PostRecycleViewAdapter(List<PostData> postData)
{
this.postData = postData;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayout = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_recycler_view,parent,false);
return new ViewHolder(itemLayout);
}
#Override
public void onBindViewHolder(PostRecycleViewAdapter.ViewHolder holder, int position) {
PostData data = postData.get(position);
holder.title.setText(data.getTitle());
holder.body.setText(data.getBody());
}
#Override
public int getItemCount() {
return postData.size();
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);}
public void setClickListener(OnItemClick itemClick) {
this.itemClick = itemClick;
}
}
And this is the data item class:
package com.example.recyclerview;
public class PostData {
private String title, body;
private int id;
public PostData(int id, String title, String body)
{
this.id = id;
this.title = title;
this.body = body;
}
public String getTitle() {
return title;
}
public String getBody() {
return body;
}
public int getId() {
return id;
}
}

Categories

Resources