This is anExpandableRecyclerViewer Code.
I want to add a Search View to filter songs and singers both when the user types a name of a song or singer. I tried using adding search view to recyclerview and expandablelistview but they didn't work. Can someone please give me a way to solve my problem?
My Main Activity
package com.example.expandableview;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.annotation.SuppressLint;
import android.app.SearchManager;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.SearchView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private SearchView search;
private SongAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
ArrayList<Singer>singers = new ArrayList<>();
ArrayList<Song> shakirasong = new ArrayList<>();
shakirasong.add(new Song("Hips Don't Lie"));
shakirasong.add(new Song("Chantaje"));
shakirasong.add(new Song("Locca"));
shakirasong.add(new Song("Whenever Whenever"));
shakirasong.add(new Song("Me Gusta"));
Singer shakira = new Singer("Shakira", shakirasong);
singers.add(shakira);
ArrayList<Song> westlifesong = new ArrayList<>();
westlifesong.add(new Song("My Love"));
westlifesong.add(new Song("I Wanna Grow Old With You"));
westlifesong.add(new Song("I Lay My Love On You"));
westlifesong.add(new Song("Uptown Girl"));
westlifesong.add(new Song("If I Let You Go"));
Singer westlife = new Singer("Westlife", westlifesong);
singers.add(westlife);
SongAdapter adapter = new SongAdapter(singers);
recyclerView.setAdapter(adapter);
}
}
My Adapter
package com.example.expandableview;
import android.content.Context;
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.thoughtbot.expandablerecyclerview.ExpandableRecyclerViewAdapter;
import com.thoughtbot.expandablerecyclerview.models.ExpandableGroup;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class SongAdapter extends ExpandableRecyclerViewAdapter<SingerViewHolder,SongViewHolder> {
public SongAdapter(List<?extends ExpandableGroup> groups) {
super(groups);
}
#Override
public SingerViewHolder onCreateGroupViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.expandable_recycleview_singer, parent, false);
return new SingerViewHolder(v);
}
#Override
public SongViewHolder onCreateChildViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.expandable_recyclerview_song, parent, false);
return new SongViewHolder(v);
}
#Override
public void onBindChildViewHolder(SongViewHolder holder, int flatPosition, ExpandableGroup group, int childIndex) {
final Song song = (Song) group.getItems().get(childIndex);
holder.bind(song);
}
#Override
public void onBindGroupViewHolder(SingerViewHolder holder, int flatPosition, ExpandableGroup group) {
final Singer singer = (Singer) group;
holder.bind(singer);
}
}
I Also used this code for search view
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.example_menu,menu);
MenuItem searchItem=menu.findItem(R.id.action_search);
SearchView searchView=(SearchView) searchItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
return true;
}
Related
This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed last year.
My Application is crashed when I click on ItemView of RecyclerView, There is no error showing in code.
The data are load in toast but not pass to the other class or what don't know, but when I click any Item the appliaction is crash..
This is my Main RecyclerView Class
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
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;
public class Admin extends AppCompatActivity {
Button addUser;
RecyclerView mainUserRecyclerView;
UserAdapter adapter;
FirebaseDatabase database;
ArrayList<UserInfo> userInfoArrayList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin);
mainUserRecyclerView = findViewById(R.id.mainUserRecyclerView);
mainUserRecyclerView.setLayoutManager(new LinearLayoutManager(this));
addUser = findViewById(R.id.addUserBtn);
database= FirebaseDatabase.getInstance();
DatabaseReference reference = database.getReference().child("userInfo");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for(DataSnapshot dataSnapshot : snapshot.getChildren()){
UserInfo userInfo = dataSnapshot.getValue(UserInfo.class);
userInfoArrayList.add(userInfo);
}
adapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(Admin.this,"Failed to get data",Toast.LENGTH_SHORT).show();
}
});
adapter = new UserAdapter(Admin.this,userInfoArrayList);
mainUserRecyclerView.setAdapter(adapter);
}
public void setAddUser(View view){
Intent intent = new Intent(this,user_detail.class);
startActivity(intent);
}
}
This is my Adapter Class
package com.example.rent;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class UserAdapter extends RecyclerView.Adapter<UserAdapter.viewHolder> {
Context admin;
ArrayList<UserInfo> userInfoArrayList;
public UserAdapter(Admin admin, ArrayList<UserInfo> userInfoArrayList) {
this.admin = admin;
this.userInfoArrayList = userInfoArrayList;
}
#NonNull
#Override
public viewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(admin).inflate(R.layout.user_list_item,parent,false);
return new viewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull UserAdapter.viewHolder holder, int position) {
UserInfo userInfo = userInfoArrayList.get(position);
holder.user_name.setText(userInfo.getShopName());
holder.itemView.setOnClickListener(v -> {
Intent intent = new Intent(admin,Display_User.class);
//Toast.makeText(admin, ""+userInfo.getOneMonthRent(), Toast.LENGTH_SHORT).show();
intent.putExtra("Name",userInfo.getShopName());
intent.putExtra("Rent",userInfo.getOneMonthRent());
intent.putExtra("Complex",userInfo.getComplexName());
intent.putExtra("PaidRent",userInfo.getPaidAmount());
intent.putExtra("DMonth",userInfo.getDefaultMonth());
intent.putExtra("PendingRent",userInfo.getPendingAmount());
admin.startActivity(intent);
});
}
#Override
public int getItemCount() {
return userInfoArrayList.size();
}
public static class viewHolder extends RecyclerView.ViewHolder {
TextView user_name;
public viewHolder(#NonNull View itemView) {
super(itemView);
user_name = itemView.findViewById(R.id.tvUserName);
}
}
}
And The display User class where I have to fetch the data
package com.example.rent;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class Display_User extends AppCompatActivity {
TextView tvName,tvRent,tvComplex,tvPaidRent,tvDefaultMonth,tvPendingRent;
String Sname, rent, complex, paidRent, defaultMonth, pendingRent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_user);
Sname = getIntent().getStringExtra("Name");
rent = getIntent().getStringExtra("Rent");
complex = getIntent().getStringExtra("Complex");
paidRent = getIntent().getStringExtra("PaidRent");
defaultMonth = getIntent().getStringExtra("DMonth");
pendingRent = getIntent().getStringExtra("Pending");
tvName = findViewById(R.id.tvName);
tvName.setText(Sname);
tvRent = findViewById(R.id.tvRent);
tvRent.setText(rent);
tvComplex = findViewById(R.id.tvComplex);
tvComplex.setText(complex);
tvPaidRent = findViewById(R.id.tvPaidRent);
tvPaidRent.setText(paidRent);
tvDefaultMonth = findViewById(R.id.tvDefault);
tvDefaultMonth.setText(defaultMonth);
tvPendingRent = findViewById(R.id.tvPending);
tvPendingRent.setText(pendingRent);
}
}
Have you declared the Activity on the manifest file? And the intent ?
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()
));
}
}
});
I am having a GridList View in which I am passing data from firebase. When I click on the items it works fine without filtering but when I filter it with searchView then it does not update the index of the list and then provides a different item's context.
I do not know how to update the item while filtering.
Homepage.Activity
package com.project.quizapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;
import android.app.SearchManager;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.GridView;
import android.widget.ListAdapter;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import static com.project.quizapp.LogIn.catList;
import static com.project.quizapp.LogIn.selected_cat_index_app;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.project.quizapp.CatGridAdapter;
public class HomePage extends AppCompatActivity {
CatGridAdapter adapter;
private GridView catGrid;
private FirebaseFirestore firebasefirestore;
public static List<CategoryModelClass> resultData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
//Binding view and adding toolbar
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Subjects");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(HomePage.this, dashActivity.class));
}
});
//Adapter to set all the views
catGrid = findViewById(R.id.catGridview);
adapter = new CatGridAdapter(catList);
catGrid.setAdapter(adapter);
}
//Filtering all tthe views
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//Inflating all the views and filtering
getMenuInflater().inflate(R.menu.search, menu);
MenuItem menuitem = menu.findItem(R.id.searchMenu);
SearchView searchview = (SearchView) menuitem.getActionView();
searchview.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
//Calling filters on the search attempt
//adapter.getFilter().filter(newText);
resultData = new ArrayList<>();
for(CategoryModelClass categoryModelClass:catList){
if(categoryModelClass.getName().toLowerCase().contains(newText.toLowerCase())){
resultData.add(categoryModelClass);
}
adapter = new CatGridAdapter(resultData);
catGrid.setAdapter(adapter);
}
return true;
}
});
return true;
}
//Adding search icon to the toolbar
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if(id == R.id.searchMenu){
return true;
}
return super.onOptionsItemSelected(item);
}
}
CatGridAdapter.java
package com.project.quizapp;
import android.content.Intent;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import static com.project.quizapp.LogIn.selected_cat_index_app;
import static java.security.AccessController.getContext;
//Creating the adapter wih the default BaseAdapter
//Also implementing
public class CatGridAdapter extends BaseAdapter {
//List of all the class variables
private List<CategoryModelClass> catList;
//Initializing the list wih constructor
public CatGridAdapter(List<CategoryModelClass> catList) {
this.catList = catList;
}
#Override
public int getCount() {
return catList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if(convertView == null){
//Adding all the views as we get the data from firebase
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cat_item_layout,parent,false);
}
else{
view = convertView;
}
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//selected_cat_index_app = position;
// Toast.makeText(parent.getChildAt(position), catList.get(position).getName()+" "+String.valueOf(catList.indexOf(position)), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(parent.getContext(), SetsActivity.class);
parent.getContext().startActivity(intent);
}
});
((TextView) view.findViewById(R.id.catName)).setText(catList.get(position).getName());
Random rnd = new Random();
int color = Color.argb(255,rnd.nextInt(255),rnd.nextInt(255),rnd.nextInt(255));
view.setBackgroundColor(color);
return view;
}
}
CategoryModelClass.java
package com.project.quizapp;
//Model class to fetch the quiz subjects from the Cloud Firestone
public class CategoryModelClass {
//private variable for ID and the name of
private String id;
private String name;
//constructor
public CategoryModelClass(String id, String name) {
this.id = id;
this.name = name;
}
//methods
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Either implement a Filterable interface in the adapter or update your onQueryTextChange implementation.
Whenever you are typing, every time you are creating a new adapter with filtered data.
try this.. create new method in adapter
public void updateData(List<CategoryModelClass> catList){
this.catList = catList;
notifyDataSetChanged();
}
and call from onQueryTextChange
#Override
public boolean onQueryTextChange(String newText) {
//adapter.getFilter().filter(newText);
resultData = new ArrayList<>();
for (CategoryModelClass categoryModelClass : catList) {
if (categoryModelClass.getName().toLowerCase().contains(newText.toLowerCase())) {
resultData.add(categoryModelClass);
}
adapter.updateData(resultData);
}
return true;
}
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
How can I get String from my database and combine it with Image from my drawable folder. Help Please.
this is my main activity.
package com.apk.foodanalyzer.healthandnutrifactsanalyzer;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import com.apk.foodanalyzer.healthandnutrifactsanalyzer.goactivity.DatabaseHelper;
import com.apk.foodanalyzer.healthandnutrifactsanalyzer.goactivity.GoItem;
import com.apk.foodanalyzer.healthandnutrifactsanalyzer.goactivity.ListGoAdapter;
import com.apk.foodanalyzer.healthandnutrifactsanalyzer.growactivity.GrowDatabaseHelper;
import com.apk.foodanalyzer.healthandnutrifactsanalyzer.growactivity.GrowItem;
import com.apk.foodanalyzer.healthandnutrifactsanalyzer.growactivity.ListGrowAdapter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
/**
* Created by Pavilion on 11/18/2015.
*/
public class Grow extends AppCompatActivity {
private ListView listviewGrow;
private ListGrowAdapter adapter;
private List<GrowItem> mGrowItemList;
private GrowDatabaseHelper mDBHelper;
private SearchView searchtext;
Integer[] imgid = {R.drawable.carp,R.drawable.catfish, R.drawable.cavalla };
#Override
protected void onCreate(Bundle savedInstanceState) {
searchtext = (SearchView) findViewById(R.id.search_text);
super.onCreate(savedInstanceState);
setContentView(R.layout.grow_layout);
listviewGrow = (ListView)findViewById(R.id.listview_growtable);
mDBHelper = new GrowDatabaseHelper(this);
mGrowItemList = mDBHelper.getListGrow();
adapter = new ListGrowAdapter(imgid, this, mGrowItemList);
listviewGrow.setAdapter(adapter);
listviewGrow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View row, int position, long index) {
Toast.makeText(getApplicationContext(), "Position " + position, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Grow.this, GrowValueActivityContent.class);
intent.putExtra("RowId", position);
startActivity(intent);
}
});
}
This is my Adapter. I don't know what to revised this. Hope you would help me.
package com.apk.foodanalyzer.healthandnutrifactsanalyzer.growactivity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.apk.foodanalyzer.healthandnutrifactsanalyzer.R;
import com.apk.foodanalyzer.healthandnutrifactsanalyzer.goactivity.GoItem;
import java.util.List;
/**
* Created by Pavilion on 12/1/2015.
*/
public class ListGrowAdapter extends BaseAdapter {
private Context mContext;
private List<GrowItem> mGrowItemList;
private final Integer[] imgid;
public ListGrowAdapter(Integer[] imgid, Context mContext, List<GrowItem> mGrowItemList) {
this.imgid = imgid;
this.mContext = mContext;
this.mGrowItemList = mGrowItemList;
}
#Override
public int getCount() {
return mGrowItemList.size();
}
#Override
public GrowItem getItem(int position) {
return mGrowItemList.get(position);
}
#Override
public long getItemId(int position) {
return mGrowItemList.get(position).getRowId();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
GrowItem item = getItem(position);
View vv = View.inflate(mContext, R.layout.go_listview, null);
TextView tvFoodDescription = (TextView)vv.findViewById(R.id.txtvw_fooddescription);
ImageView imgFoodImage = (ImageView)vv.findViewById(R.id.food_image);
tvFoodDescription.setText(item.getFoodDescription());
imgFoodImage.setImageResource(imgid[position]);
return vv;
}
}