Hi i tried to inflate my home_items.xml in my application however it doesnt work it just gives me the fragment_home.xml ONLY im wondering how can i fix this? (I can send any part of my code.)
HomeAdapter.java:
package com.example.soulforge.adapter;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.soulforge.R;
import com.example.soulforge.model.HomeModel;
import java.util.List;
import java.util.Random;
import de.hdodenhof.circleimageview.CircleImageView;
public class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.HomeHolder>{
private List<HomeModel> list;
Context context;
public HomeAdapter(List<HomeModel> list, Context context) {
this.list = list;
this.context = context;
}
#NonNull
#Override
public HomeHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.home_items, parent, false);
return new HomeHolder(view);
}
#Override
public void onBindViewHolder(#NonNull HomeHolder holder, int position) {
holder.userNameTv.setText(list.get(position).getUserName());
holder.timeTv.setText(""+list.get(position).getTimestamp());
int count = list.get(position).getLikeCount();
if(count ==0){
holder.likeCountTv.setVisibility(View.INVISIBLE);
}else if (count == 1){
holder.likeCountTv.setText(count + " like");
}else{
holder.likeCountTv.setText(count + " likes");
}
holder.descriptionTv.setText(list.get(position).getDescription());
Random random = new Random();
int color = Color.argb(255, random.nextInt(256), random.nextInt(256), random.nextInt(256));
Glide.with(context.getApplicationContext())
.load(list.get(position).getProfileImage())
.placeholder(R.drawable.ic_person)
.timeout(6500)
.into(holder.profileImage);
Glide.with(context.getApplicationContext())
.load(list.get(position).getImageUrl())
.placeholder(new ColorDrawable(color))
.timeout(7000)
.into(holder.imageView);
}
#Override
public int getItemCount() {
return list.size();
}
static class HomeHolder extends RecyclerView.ViewHolder{
private CircleImageView profileImage;
private TextView userNameTv, timeTv, likeCountTv, descriptionTv;
private ImageView imageView;
private ImageButton likeBtn, commentBtn, shareBtn;
public HomeHolder(#NonNull View itemView) {
super(itemView);
profileImage = itemView.findViewById(R.id.profileImage);
imageView = itemView.findViewById(R.id.imageView);
userNameTv = itemView.findViewById(R.id.nameTv);
timeTv = itemView.findViewById(R.id.timeTv);
likeCountTv = itemView.findViewById(R.id.likeCountTv);
likeBtn = itemView.findViewById(R.id.likeBtn);
commentBtn = itemView.findViewById(R.id.commentBtn);
shareBtn = itemView.findViewById(R.id.shareBtn);
descriptionTv = itemView.findViewById(R.id.descTv);
}
}
}
Home.java:
package com.example.soulforge.fragments;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.soulforge.R;
import com.example.soulforge.adapter.HomeAdapter;
import com.example.soulforge.model.HomeModel;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class Home extends Fragment {
private RecyclerView recyclerView;
HomeAdapter adapter;
private List<HomeModel> list;
private FirebaseUser user;
public Home() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
init(view);
list = new ArrayList<>();
adapter = new HomeAdapter(list, getContext());
recyclerView.setAdapter(adapter);
loadDataFromFirestore();
}
private void init(View view) {
Toolbar toolbar = view.findViewById(R.id.toolbar);
if (getActivity() != null)
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
FirebaseAuth auth = FirebaseAuth.getInstance();
user = auth.getCurrentUser();
}
public void loadDataFromFirestore() {
CollectionReference reference = FirebaseFirestore.getInstance().collection("Users")
.document(user.getUid())
.collection("Post Images");
reference.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value, #Nullable FirebaseFirestoreException error) {
if (error != null) {
Log.e("Error: ", error.getMessage());
return;
}
if (value == null)
return;
for (QueryDocumentSnapshot snapshot : value) {
if (!snapshot.exists())
return;
HomeModel model = snapshot.toObject(HomeModel.class);
list.add(new HomeModel(
model.getUserName(),
model.getProfileImage(),
model.getImageUrl(),
model.getUid(),
model.getComments(),
model.getDescription(),
model.getId(),
model.getTimestamp(),
model.getLikeCount()
));
}
adapter.notifyDataSetChanged();
}
});
}
}
Any idea how to fix this? I tried to use inflate however it failed to work as shown it is missing the home items xml enter image description here.
Before you say i have cleared and rebuild and all the FAQ ways to fix this
You're updating wrong list instance
Create one method inside adapter
public updateList(List<HomeModel> list) {
this.list = list;
notifyDataSetChanged()
}
And call it like :
reference.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value, #Nullable FirebaseFirestoreException error) {
...
adapter.updateList(new HomeModel(
model.getUserName(),
model.getProfileImage(),
model.getImageUrl(),
model.getUid(),
model.getComments(),
model.getDescription(),
model.getId(),
model.getTimestamp(),
model.getLikeCount()
));
}
}
});
Related
I am working on a chat app with firebase and I want to fitch the user information to the recyclerview...my code is correct by when I set the adapter to the recycler view its show an error.
Here is my code:
package com.abdelatif.chatapp;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.ViewHolder;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import com.squareup.picasso.Picasso;
public class ChatFragment extends Fragment {
private FirebaseFirestore firebaseFirestore;
LinearLayoutManager linearLayoutManager;
private FirebaseAuth firebaseAuth;
ImageView mimageviewofuser;
FirestoreRecyclerAdapter<FireBaseModel, NoteViewHolder> chatAdapter = null;
RecyclerView mrecyclerview;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.chatfragment,container,false);
firebaseAuth=FirebaseAuth.getInstance();
firebaseFirestore= FirebaseFirestore.getInstance();
mrecyclerview=v.findViewById(R.id.recyclerView);
// Query query=firebaseFirestore.collection("Users");
Query query=firebaseFirestore.collection("Users").whereNotEqualTo("uid",firebaseAuth.getUid());
FirestoreRecyclerOptions<FireBaseModel> allusername=new FirestoreRecyclerOptions.Builder<FireBaseModel>().setQuery(query,FireBaseModel.class).build();
chatAdapter=new FirestoreRecyclerAdapter<FireBaseModel, NoteViewHolder>(allusername) {
#Override
protected void onBindViewHolder(#NonNull NoteViewHolder noteViewHolder, int i, #NonNull FireBaseModel firebasemodel) {
noteViewHolder.particularusername.setText(firebasemodel.getName());
String uri=firebasemodel.getImage();
Picasso.get().load(uri).into(mimageviewofuser);
if(firebasemodel.getStatus().equals("Online"))
{
noteViewHolder.statusofuser.setText(firebasemodel.getStatus());
noteViewHolder.statusofuser.setTextColor(Color.GREEN);
}
else
{
noteViewHolder.statusofuser.setText(firebasemodel.getStatus());
}
noteViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "contactClicked", Toast.LENGTH_SHORT).show();
}
});
}
#NonNull
#Override
public NoteViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view=LayoutInflater.from(parent.getContext()).inflate(R.layout.chat_view_layout,parent,false);
return new NoteViewHolder(view);
}
};
mrecyclerview.setHasFixedSize(true);
linearLayoutManager=new LinearLayoutManager(getContext());
linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
mrecyclerview.setLayoutManager(linearLayoutManager);
mrecyclerview.setAdapter(chatAdapter);
chatAdapter.startListening();
return v;
}
public class NoteViewHolder extends android.support.v7.widget.RecyclerView.ViewHolder
{
private TextView particularusername;
private TextView statusofuser;
public NoteViewHolder(#NonNull View itemView) {
super(itemView);
particularusername=itemView.findViewById(R.id.nameOfUser);
statusofuser=itemView.findViewById(R.id.statusOfUser);
mimageviewofuser=itemView.findViewById(R.id.imageViewOfUser);
}
}
}
the error is in the line: mrecyclerview.setAdapter(chatAdapter);
and the error is:
'setAdapter(androidx.recyclerview.widget.RecyclerView.Adapter)' in 'androidx.recyclerview.widget.RecyclerView' cannot be applied to '(com.firebase.ui.firestore.FirestoreRecyclerAdapter<com.abdelatif.chatapp.FireBaseModel,com.abdelatif.chatapp.ChatFragment.NoteViewHolder>)'
I hope someone give me a solution...i searched many time but nothing.
Make sure you call chatAdapter.startListening(); before calling mrecyclerview.setAdapter(chatAdapter);
To put this simple, I have a table called Wishlist in Firebase Database which contains 2 different types of objects: attractions and sights.
Then, in my app I want to show in a fragment only those objects from Wishlist table which are sights. How could I achieve this? Right now, the code is as it follows: (obviously, it will crash if I put return null, but how else could I address this issue?)
package com.example.mytravelapp.Fragments;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.mytravelapp.Adapters.WishlistViewHolder;
import com.example.mytravelapp.Models.Sight;
import com.example.mytravelapp.Models.Wishlist;
import com.example.mytravelapp.R;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.firebase.ui.database.SnapshotParser;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
*/
public class WishlistSightsFragment extends Fragment {
private RecyclerView wishlist;
private DatabaseReference query;
private FirebaseRecyclerAdapter adapter;
private FirebaseUser user;
public WishlistSightsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_wishlist_sights, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
wishlist = view.findViewById(R.id.rvWishlistSights);
wishlist.setHasFixedSize(true);
user = FirebaseAuth.getInstance().getCurrentUser();
GridLayoutManager grid = new GridLayoutManager(getContext().getApplicationContext(), 1);
wishlist.setLayoutManager(grid);
fetch();
}
private void fetch(){
query = FirebaseDatabase.getInstance().getReference("wishlist").child(user.getUid());
FirebaseRecyclerOptions<Wishlist> options =
new FirebaseRecyclerOptions.Builder<Wishlist>()
.setQuery(query, new SnapshotParser<Wishlist>() {
#NonNull
#Override
public Wishlist parseSnapshot(#NonNull DataSnapshot snapshot) {
Wishlist attraction = new Wishlist(snapshot.child("idWishlist").getValue().toString(),
snapshot.child("idAttraction").getValue().toString(),
snapshot.child("name").getValue().toString(),
snapshot.child("description").getValue().toString(),
snapshot.child("image").getValue().toString(),
snapshot.child("type").getValue().toString());
if(attraction.getType().equals("sight")){
return attraction;
}
return null;
}
})
.build();
adapter = new FirebaseRecyclerAdapter<Wishlist, WishlistViewHolder>(options) {
#Override
public WishlistViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.wishlist_design, parent, false);
return new WishlistViewHolder(view);
}
#Override
protected void onBindViewHolder(final WishlistViewHolder holder, final int position, final Wishlist model) {
holder.setDetails(getActivity(), model.getName(), model.getDescription(), model.getIdAttraction(), model.getImage());
}
};
wishlist.setAdapter(adapter);
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
}
I think this query is more useful for you.
query = FirebaseDatabase.getInstance().getReference("wishlist").child(user.getUid()).orderByChild("type").equalTo("sight");
FirebaseRecyclerOptions<Wishlist> options =
new FirebaseRecyclerOptions.Builder<Wishlist>()
.setQuery(query, Wishlist.class)
.build();
You can get the list of wish who have type sight.
I'm a beginner to java and android. I'm sure this is a basic question.
I get an error when trying to import a class defined in a file adjacent to the current file. The code is available at https://github.com/morenoh149/HarryLearnsAndroid/blob/master/HttpDemo/app/src/main/java/com/harrymoreno/httpdemo/MainActivity.java#L44
// MainActivity.java
package com.harrymoreno.httpdemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import com.harrymoreno.httpdemo.GitHubRepoAdapter;
public class MainActivity extends AppCompatActivity {
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.pagination_list);
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
GithubClient client = retrofit.create(GithubClient.class);
Call<List<GithubRepo>> call = client.reposForUser("morenoh149");
call.enqueue(new Callback<List<GithubRepo>>() {
#Override
public void onResponse(Call<List<GithubRepo>> call, Response<List<GithubRepo>> response) {
List<GithubRepo> repos = response.body();
// error error: cannot find symbol class GithubRepoAdapter
listView.setAdapter(new GithubRepoAdapter(MainActivity.this, repos));
}
#Override
public void onFailure(Call<List<GithubRepo>> call, Throwable t) {
Toast.makeText(MainActivity.this, "error :(", Toast.LENGTH_SHORT).show();
}
});
}
}
and
// GitHubRepoAdapter.java
package com.harrymoreno.httpdemo;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
public class GitHubRepoAdapter extends ArrayAdapter<GithubRepo> {
private Context context;
private List<GithubRepo> values;
public GitHubRepoAdapter(Context context, List<GithubRepo> values) {
super(context, R.layout.list_item_pagination, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.list_item_pagination, parent, false);
}
TextView textView = (TextView) row.findViewById(R.id.list_item_pagination_text);
GithubRepo item = values.get(position);
String message = item.getName();
textView.setText(message);
return row;
}
}
You have spelling mistake on that error line.
It should be GitHubRepoAdapter, not GithubRepoAdapter.
I have list of Categories of Subjects in my firestore database and i want it to be displayed in my app ( which i thought can be done by recyclerView).But my RecyclerView is not populating any data.You can see my code below:
Question_list.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import com.google.firebase.firestore.DocumentChange;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nullable;
public class Question_list extends AppCompatActivity {
private static final String TAG ="Firelog" ;
private RecyclerView mMainList;
private FirebaseFirestore mFirestore;
private CategoryAdapter categoryAdapter;
private List<Categories> list_category;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question_list);
mMainList = (RecyclerView)findViewById(R.id.main_list_id);
//mMainList.setHasFixedSize(true);
mMainList.setLayoutManager(new LinearLayoutManager(this));
mMainList.setAdapter(categoryAdapter);
mFirestore = FirebaseFirestore.getInstance();
categoryAdapter = new CategoryAdapter(list_category);
list_category = new ArrayList<>();
mFirestore.collection("Questions").addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot queryDocumentSnapshots, #Nullable FirebaseFirestoreException e) {
if(e!=null){
Log.d(TAG, "Error: "+ e.getMessage());
}
for(DocumentChange doc: queryDocumentSnapshots.getDocumentChanges()){
if(doc.getType() == DocumentChange.Type.MODIFIED){
//String document = doc.getDocument().getString("Category");
Categories categories = doc.getDocument().toObject(Categories.class);
list_category.add(categories);
Log.d(TAG, "Category: "+ categories);
categoryAdapter.notifyDataSetChanged();
}
}
}
});
}
}
CategoryAdapter.java
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.TextView;
import java.util.List;
public class CategoryAdapter extends
RecyclerView.Adapter<CategoryAdapter.ViewHolder> {
public List<Categories> list_categorie;
public CategoryAdapter(List<Categories> list_categorie){
this.list_categorie = list_categorie;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.category_list,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.mCategoryText.setText(list_categorie.get(position).getCategory());
}
#Override
public int getItemCount() {
return list_categorie.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
View mview;
public TextView mCategoryText;
public ViewHolder(View itemView) {
super(itemView);
mview = itemView;
mCategoryText = (TextView)mview.findViewById(R.id.category_text_id);
}
}
}
Categories.java
public class Categories {
String category;
public Categories(){}
public Categories(String category) {
this.category = category;
}
public String getCategory() {
return category;
}
}
Above are my all java classes. I haven't uploaded my XML file as i think the problem is in the java class.
categoryAdapter = new CategoryAdapter(list_category);
list_category = new ArrayList<>();
list_category should be initialized before passing it to the adapter
list_category = new ArrayList<>();
categoryAdapter = new CategoryAdapter(list_category);
This is my RecyclerAdapter code:
package com.example.sander.app;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.CardView;
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.TextView;
import java.util.ArrayList;
/**
* Created by Sander on 6-4-2017.
*/
public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.MyViewHolder> {
private String[] mDataset;
ArrayList<String> ArrayDataset;
public static class MyViewHolder extends RecyclerView.ViewHolder{
public CardView mCardView;
public TextView mTextView;
public MyViewHolder(View v){
super(v);
mCardView = (CardView) v.findViewById(R.id.card_view);
mTextView = (TextView) v.findViewById(R.id.tv_blah);
}
}
public RecycleAdapter(ArrayList<String> names){
ArrayDataset = names;
}
#Override
public RecycleAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_card_view, parent, false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position){
holder.mTextView.setText(ArrayDataset.get(position));
}
#Override
public int getItemCount() { return ArrayDataset.size(); }
}
And this is my Recycler Fragment code:
package com.example.sander.app;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.CardView;
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.FrameLayout;
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 org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Sander on 6-4-2017.
*/
public class RecycleFrame extends Fragment {
ArrayList<String> names = new ArrayList<>();
GoogleMaps maps = new GoogleMaps();
public RecycleFrame() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RequestQueue rq = Volley.newRequestQueue(getActivity().getApplicationContext());
String url= "http://test.dontstealmywag.ga/api/parkgarage.php";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// Do something with the response
try{
JSONObject o = new JSONObject(response);
JSONArray values=o.getJSONArray("parkgarage");
for ( int i=0; i< values.length(); i++) {
JSONObject jsonObject = values.getJSONObject(i);
names.add(jsonObject.getString("parkgarage_name"));
}
} catch (JSONException ex){}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle error
}
});
rq.add(stringRequest);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_recycle, container, false);
RecyclerView VRecyclerView = (RecyclerView) rootView.findViewById(R.id.rv_recycler_view);
VRecyclerView.setHasFixedSize(true);
RecycleAdapter adapter = new RecycleAdapter(names);
VRecyclerView.setAdapter(adapter);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
VRecyclerView.setLayoutManager(llm);
return rootView;
}
}
Now if I'm correct. My data from my API (link can be found in the code), will be added in an ArrayList called "names", but when I run my code my Recyclerview is empty. How do I add my JSON data to the RecyclerView and display it.
(For the record if I try it with String [] {"Example"} it will show a card with "Example")
Thanks in advance