package eu.andykrzemien.dog4u;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
class Size {
private int id;
private String SizeName;
public Size(int id, String sizeName) {
this.id = id;
SizeName = sizeName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSizeName() {
return SizeName;
}
public void setSizeName(String sizeName) {
SizeName = sizeName;
}
public String toString(){
return getId()+" "+getSizeName();
}
}
class Activities {
private int id;
private String ActivityName;
public Activities(int id, String activityName) {
this.id = id;
ActivityName = activityName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getActivityName() {
return ActivityName;
}
public void setActivityName(String activityName) {
ActivityName = activityName;
}
public String toString() {
return getId()+ " "+getActivityName();
}
}
class Children {
private int id;
private String ChildrenName;
public Children(int id, String childrenName) {
this.id = id;
ChildrenName = childrenName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getChildrenName() {
return ChildrenName;
}
public void setChildrenName(String childrenName) {
ChildrenName = childrenName;
}
public String toString() {
return getId()+" "+getChildrenName();
}
}
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
ListView sizeList;
ListView activityList;
ListView childrenList;
Button button;
public static final String TAG = "MyActivity";
public void inItListViews() {
sizeList= findViewById(R.id.sizeList);
activityList= findViewById(R.id.activityList);
childrenList= findViewById(R.id.childrenList);
}
public void dogMatches() {
Size s1 = new Size(1,"Miniature");
Size s2 = new Size(2,"Small");
Size s3 = new Size(3,"Medium");
Size s4 = new Size(4,"Large");
Size s5 = new Size(5,"Giant");
Size [] size = new Size[]{s1,s2,s3,s4,s5};
ArrayAdapter<Size> adapter1 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,size);
this.sizeList.setAdapter(adapter1);
Activities a1 = new Activities(1,"Lazy");
Activities a2 = new Activities(2,"Light Active");
Activities a3 = new Activities(3,"Very Active");
Activities[] activities = new Activities[]{a1,a2,a3};
ArrayAdapter<Activities> adapter2 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,activities);
this.activityList.setAdapter(adapter2);
Children c1 = new Children(1,"Like");
Children c2 = new Children(2,"Doesn't matter");
Children[] children = new Children[]{c1,c2};
ArrayAdapter<Children> adapter3 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_activated_1,children);
this.childrenList.setAdapter(adapter3);
}
public void processResult() {
Log.d(TAG,"Result button clicked");
int pos1= sizeList.getCheckedItemPosition();
int pos2 = activityList.getCheckedItemPosition();
int pos3 = childrenList.getCheckedItemPosition();
Size sSelected= (Size) sizeList.getItemAtPosition(pos1);
Activities aSelected=(Activities) activityList.getItemAtPosition(pos2);
Children cSelected=(Children) childrenList.getItemAtPosition(pos3);
if(sSelected!=null && aSelected!=null && cSelected!=null){
Log.d(TAG,"result "+ sSelected.getSizeName()+" : "+ aSelected.getActivityName()+ " " + cSelected.getChildrenName());
String petSeeker = yourBest(sSelected,aSelected,cSelected);
Toast.makeText(this,petSeeker,Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this,"Please Select Something",Toast.LENGTH_SHORT).show();
}
}
public void buttonPressed() {
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
processResult();
}
});
}
private String yourBest(Size s, Activities a, Children c) {
String doThis;
if(s.getSizeName().equalsIgnoreCase("small")
&& a.getActivityName().equalsIgnoreCase("lazy")
&& c.getChildrenName().equalsIgnoreCase("like")){
Toast.makeText(this,"Chihuahua",Toast.LENGTH_LONG).show();
doThis="Chihuahua";
}
else if(s.getSizeName().equalsIgnoreCase("small")
&& a.getActivityName().equalsIgnoreCase("light active")
&& c.getChildrenName().equalsIgnoreCase("like")){
doThis="Labrador";
} else{
doThis="Find a cat";
}
return doThis;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inItListViews();
dogMatches();
buttonPressed();
}
#Override
public void onClick(View v) {
}
}
The app is running but the problem is that I can't get the result of three listViews. Is it something with the ListView or with the method? After pressing button I get only else message. Maybe there is some method to check the listView because maybe they aren't coded with the press of the mouse. I'm really stuck and need at least some advice not a ready solution.
Instead of using getCheckedItemPosition() to get the position of the selected list item, use listView.setOnItemClickListener()
So you can remove below statements, and make po1-pos3 as global fields
int pos1= sizeList.getCheckedItemPosition();
int pos2 = activityList.getCheckedItemPosition();
int pos3 = childrenList.getCheckedItemPosition();
As below:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
int pos1, pos2, pos3;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inItListViews();
dogMatches();
buttonPressed();
sizeList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
pos1 = position;
}
});
activityList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
pos2 = position;
}
});
childrenList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
pos3 = position;
}
});
}
And to get a list item for a position:
sizeList.getAdapter().getItem(pos1);
activityList.getAdapter().getItem(pos2);
childrenList.getAdapter().getItem(pos3);
First of all I think it will be better without implementing View.OnClickListener, because you don't use it. Second - you can put a breakpoint at:
int pos1 = sizeList.getCheckedItemPosition();
Debug it and then you will see what is going wrong.
And last, I suggest creating a custom interface that will allow you to find out what position was checked.
Related
I have a recyclerview of tasks. When user will swipe an element I want to change one parameter(variable "isChecked" from false to true - that will mean the task is completed) in that task.
I created new ItemTouchHelper instance in my activity:
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
Sorted current = adapter.getSortedAtPosition(viewHolder.getAdapterPosition());
int time = current.getSortedDuration() + current.getSortedTimeBegin();
int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
int minute = Calendar.getInstance().get(Calendar.MINUTE);
if (hour > time/60){
//change
Toast.makeText(ShowSortedActivity.this, "check1", Toast.LENGTH_SHORT).show();
}
else if (hour == time/60){
if (minute > time % 60){
//change
Toast.makeText(ShowSortedActivity.this, "check2", Toast.LENGTH_SHORT).show();
}
else{
//do nothing
Toast.makeText(ShowSortedActivity.this, "uncheck1", Toast.LENGTH_SHORT).show();
}
}
else{
//do nothing
Toast.makeText(ShowSortedActivity.this, "uncheck2", Toast.LENGTH_SHORT).show();
}
}
}).attachToRecyclerView(showSorted);
}
Here I'm getting the task of class "Sorted" and check if the ending time of the task is less than the current time of the day. If so, I want to change the variable.
My adapter class:
public class SortedAdapter extends RecyclerView.Adapter<SortedAdapter.SortedViewHolder> {
private List<Sorted> list = new ArrayList<>();
#NonNull
#Override
public SortedViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.tasks2_layout , parent, false);
return new SortedAdapter.SortedViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull final SortedViewHolder holder, final int position) {
final Sorted data = list.get(position);
holder.title.setText(data.getSortedName());
holder.date.setText(data.getSortedDate());
holder.category.setText(String.valueOf(data.getSortedCategory()));
holder.attach.setText(String.valueOf(data.isSortedAttach()));
holder.to.setText(String.valueOf(toTime(data.getSortedDuration() + data.getSortedTimeBegin())));
holder.from.setText(String.valueOf(toTime(data.getSortedTimeBegin())));
holder.isChecked.setText(String.valueOf(data.isChecked()));
}
public void setSortedData(List<Sorted> sortedList){
this.list = sortedList;
notifyDataSetChanged();
}
public Sorted getSortedAtPosition(int position){
return list.get(position);
}
public void setSorted(Sorted data){
}
#Override
public int getItemCount() {
return list.size();
}
static class SortedViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
private TextView title;
private TextView date;
private TextView from;
private TextView to;
private TextView category;
private TextView attach;
private TextView isChecked;
SortedViewHolder(#NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.tv_title1);
date = itemView.findViewById(R.id.tv_date1);
from = itemView.findViewById(R.id.tv_from3);
to = itemView.findViewById(R.id.tv_to3);
category = itemView.findViewById(R.id.tv_category1);
attach = itemView.findViewById(R.id.tv_attach1);
isChecked = itemView.findViewById(R.id.tv_isChecked);
}
}
private static String toTime(int a) {
String s = "";
int b = a/60;
int c = a%60;
if (c < 10) {
s = b + " : " + 0 + c;
}
else {
s = b + " : " + c;
}
return s;
}
}
Sorted class:
#Entity
public class Sorted {
#PrimaryKey(autoGenerate = true)
public int id;
public String name;
public int timeBegin;
public int duration;
public int category;
public boolean attach;
public String date;
public String categoryChart;
public boolean checked;
public Sorted(String name, int timeBegin, int duration, int category, boolean attach, String date, String categoryChart, boolean checked) {
this.name = name;
this.timeBegin = timeBegin;
this.duration = duration;
this.category = category;
this.attach = attach;
this.date = date;
this.categoryChart = categoryChart;
this.checked = checked;
}
public void setSortedId(int id) {
this.id = id;
}
public String getSortedName() {
return name;
}
public int getSortedTimeBegin() {
return timeBegin;
}
public int getSortedDuration() {
return duration;
}
public int getSortedCategory() {
return category;
}
public boolean isSortedAttach() {
return attach;
}
public String getSortedDate() {
return date;
}
public String getSortedCategoryChart() {
return categoryChart;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
}
My problem is that I don't really understand how to do it. Is there any way to update the data, not create a new task? Or do I need to delete the task I got and insert a new one, with one parameter changed? Maybe I could do it the same way I update the list? :
public void setSortedData(List<Sorted> sortedList){
this.list = sortedList;
notifyDataSetChanged();
}
Or maybe I don't need to deal with my adapter, only with database? (I'm using Room).
Thanks in advance for help. If it's needed, I will add more information to the question.
In method onSwipe to change UI you only need call some method to set for model current and call adapter.notifyItemChange(viewHolder.getAdapterPosition()) no need create new object or new list
I know you using Room don't forget update it to database. Additional if you using RxJava or Flow and LiveData one thing you need is update entity. Room auto update new list for you
I am trying to get the details of the Recipe from which Recipe I have clicked in recycler view. I am using this to go to an edit/delete feature. Here is the code for my main activity.
The details that I am trying to get is getting the Name, Ingredients and method.
public class MainActivity extends AppCompatActivity implements RecipeListAdapter.OnItemClickListener {
private RecipeViewModel mRecipeViewModel;
public static final int NEW_WORD_ACTIVITY_REQUEST_CODE = 1;
public String Name;
public String Ingredients;
public String Method;
private RecipeListAdapter mAdapter;
private RecipeDao recDao;
private LiveData<List<Recipe>> RecipeList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.recyclerview);
final RecipeListAdapter adapter = new RecipeListAdapter(this);
recyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(MainActivity.this);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecipeViewModel = new ViewModelProvider(this).get(RecipeViewModel.class);
mRecipeViewModel.getAllRecipes().observe(this, new Observer<List<Recipe>>() {
#Override
public void onChanged(#Nullable final List<Recipe> recipes) {
// Update the cached copy of the words in the adapter.
adapter.setWords(recipes);
}
});
void onItemClick(int position) {
//Delete Below test to pass data through
Recipe recipe = new Recipe("Test", "Yeet", "Jim");
// showAlertDialogBox();
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("Edit or Delete...");
alertDialog.setPositiveButton("Edit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent update = new Intent(MainActivity.this, UpdateRecipeActivity.class);
update.putExtra("Name", recipe.getName());
update.putExtra("Ingredients", recipe.getIngredients());
update.putExtra("Method", recipe.getMethod());
startActivity(update);
}
});
alertDialog.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Delete
}
});
alertDialog.show();
}
Here is the Recipe.class if you needed it!
#Entity(tableName = "recipe_table")
public class Recipe {
#PrimaryKey(autoGenerate = true)
#ColumnInfo(name= "recipeId")
private int RecipeId;
private String name;
private String Ingredients;
private String Method;
#Ignore
public Recipe(String name, String Ingredients, String Method) {
this.RecipeId = RecipeId;
this.name = name;
this.Ingredients = Ingredients;
this.Method = Method;
}
public Recipe(String name) {
this.name = name;
}
public void changeText1(String text){
name = text;
}
//Add Image somehow!
public int getRecipeId() {
return RecipeId;
}
public void setRecipeId(int recipeId) {
RecipeId = recipeId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMethod() {
return Method;
}
public void setMethod(String method) {
Method = method;
}
public String getIngredients() {
return Ingredients;
}
public void setIngredients(String ingredients) {
Ingredients = ingredients;
}
}
If you need anymore files, these are the files I have:
- RecipeListAdapter
- RecipeDao
- RecipeRepository
- RecipeRoomDatabase
- RecipeViewModel
Recipe Adapter code
public class RecipeListAdapter extends RecyclerView.Adapter {
private OnItemClickListener mListener;
private List recipeList;
public interface OnItemClickListener{
void onItemClick(int position, Recipe recipe);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
class RecipeViewHolder extends RecyclerView.ViewHolder {
private final TextView recipeItemView;
private RecipeViewHolder(View itemView) {
super(itemView);
recipeItemView = itemView.findViewById(R.id.textView);
itemView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if (mListener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
mListener.onItemClick(position,
recipeList.get(getAdapterPosition()));
}
}
}
});
}
}
private final LayoutInflater mInflater;
private List<Recipe> mRecipes; // Cached copy of words
RecipeListAdapter(Context context) {
mInflater = LayoutInflater.from(context);
this.recipeList = recipeList;
}
#Override
public RecipeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = mInflater.inflate(R.layout.recyclerview_item, parent,
false);
return new RecipeViewHolder(itemView);
}
#Override
public void onBindViewHolder(RecipeViewHolder holder, int position) {
if (mRecipes != null) {
Recipe current = mRecipes.get(position);
holder.recipeItemView.setText(current.getName());
} else {
// Covers the case of data not being ready yet.
holder.recipeItemView.setText("No Recipes");
}
}
void setWords(List<Recipe> recipes){
mRecipes = recipes;
notifyDataSetChanged();
}
// getItemCount() is called many times, and when it is first called,
// mWords has not been updated (means initially, it's null, and we can't
return null).
#Override
public int getItemCount() {
if (mRecipes != null)
return mRecipes.size();
else return 0;
}
public interface OnNoteListener{}
}
Inside the onItemClick there is one more parameter need to add.
void onItemClick(int position, Recipe recipe) {
//Delete selected recipe from recipe list
arrayList.remove(recipe)
}
The onItemClick method will get called from adapter, from there you have to pass the selected receipe. In the adapter you have to use recipeList.get(getAdapterPosition()) to get the clicked receipe and pass this to the interface method, onItemClick along with the position.
So your code will look like this way inside the adapter,
itemClickListener.onItemClick(position,
recipeList.get(getAdapterPosition()))
Just as a note, please ensure instead of List, you need to take ArrayList to perform remove operation.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
in my app i have a Mysql and im getting data with volley and populating recyclerView with it and to be clear i have a Restaurant list that populates the recyclerView and if you long press a restaurant you can add a note to that specific restaurant so i need the restaurant id and its positon because my note table in my dataBase is a child table that is connected to Restaurant table with FK and uses restaurant id as a refrence, i dont know why im getting NPE for the adapter.getPosition please help
MainActivity
public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener{
RecyclerView recyclerView;
RecyclerView.Adapter mAdapter;
RecyclerView.LayoutManager layoutManager;
SwipeRefreshLayout swipeRefreshLayout;
RestaurantAdapter adapter;
List<Restaurant> restaurants = new ArrayList<>();
String request_url = "https://localhost/api/all_fastfoods.php";
String post_url= "https://localhost/api/add_note.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipeRefreshLayout=findViewById(R.id.swipe_layout);
swipeRefreshLayout.setOnRefreshListener(this);
recyclerView = findViewById(R.id.recycleViewContainer);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
restaurants = new ArrayList<>();
registerForContextMenu(recyclerView);
getData();
NukeSSLCerts.nuke();
}
private void getData() {
swipeRefreshLayout.setRefreshing(true);
sendRequest();
}
public void sendRequest(){
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, request_url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
restaurants.clear();
for (int i = 0; i < response.length(); i++) {
Restaurant restaurant = new Restaurant();
try {
JSONObject jsonObject = response.getJSONObject(i);
restaurant.setId(jsonObject.getInt("restaurant_id"));
restaurant.setName(jsonObject.getString("restaurant_name"));
restaurant.setAddress(jsonObject.getString("restaurant_address"));
restaurant.setImage(jsonObject.getInt("restaurant_image_type"));
restaurant.setHasNote(jsonObject.getBoolean("restaurant_has_note"));
swipeRefreshLayout.setRefreshing(false);
} catch (JSONException e) {
swipeRefreshLayout.setRefreshing(false);
Log.i("Error",e.toString());
e.printStackTrace();
}
restaurants.add(restaurant);
}
mAdapter = new RestaurantAdapter(MainActivity.this, restaurants);
recyclerView.setAdapter(mAdapter);
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("Volley Error:", String.valueOf(error));
}
});
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
queue.add(jsonArrayRequest);
}
public boolean onContextItemSelected(MenuItem item) {
final Restaurant restaurant= new Restaurant();
if (item.getTitle().equals("Add Note")){
AlertDialog.Builder notepad = new AlertDialog.Builder(MainActivity.this);
LayoutInflater noteInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View notepadView = noteInflater.inflate(R.layout.notes,null,false);
notepad.setView(notepadView);
final AlertDialog notepadDialog = notepad.create();
notepadDialog.getWindow().getAttributes().windowAnimations = R.style.customdialog;
notepadDialog.show();
final EditText notepadedit = notepadView.findViewById(R.id.notepad);
final Button addnote = notepadView.findViewById(R.id.fab);
notepadedit.requestFocus();
addnote.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JSONObject update = new JSONObject();
JSONObject postparams = new JSONObject();
try {
postparams.put("Content-Type", "application/json");
postparams.put("Accept", "application/json");
postparams.put("note_content",notepadedit.getText());
postparams.put("note_date_time",System.currentTimeMillis());
postparams.put("restaurant_id",restaurants.get(adapter.getPosition()).getId());
update.put("restaurant_has_note",true);
} catch (JSONException e) {
e.printStackTrace();
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, post_url, postparams, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Toast.makeText(getApplicationContext(), "SuccessFull", Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.i("PostLog", String.valueOf(error));
}
}
RecyclerView Adapter
public class RestaurantAdapter extends RecyclerView.Adapter<RestaurantAdapter.MyViewHolder> implements View.OnClickListener{
private Context context;
private List<Restaurant> restaurantList;
private int position;
public int getPosition() {return position;}
public void setPosition(int position) {this.position = position; }
public RestaurantAdapter(Context context,List <Restaurant> restaurantList){
this.context = context;
this.restaurantList = restaurantList;
}
#Override
public void onClick(View view){
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener{
public TextView FastFoodName;
public TextView FastFoodAddress;
ImageView icon,noteIcon;
MyViewHolder(View itemView){
super(itemView);
icon = itemView.findViewById(R.id.type_ic);
FastFoodName = itemView.findViewById(R.id.listview_name);
FastFoodAddress = itemView.findViewById(R.id.listview_address);
noteIcon = itemView.findViewById(R.id.note_icon);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
menu.add(0, 1, 0, "Add Note");
menu.add(0, 2, 1, "All Notes");
}
}
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout,parent,false);
return new MyViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, int position) {
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
setPosition(holder.getAdapterPosition());
return false;
}
});
Restaurant restaurant = restaurantList.get(position);
holder.FastFoodName.setText(restaurant.getName());
holder.FastFoodAddress.setText(restaurant.getAddress());
switch (restaurant.getImage()){
case 1:
holder.icon.setImageResource(R.drawable.phoneorderr);
break;
case 2:
holder.icon.setImageResource(R.drawable.sitdownn);
break;
case 3:
holder.icon.setImageResource(R.drawable.takeaway);
break;
}
holder.noteIcon.setImageResource(R.drawable.notepadicon);
if(restaurant.isHasNote()){
holder.noteIcon.setVisibility(View.VISIBLE);
}else {
holder.noteIcon.setVisibility(View.INVISIBLE);
}
}
#Override
public int getItemCount() {
return restaurantList.size();
}
#Override
public long getItemId(int position) {
return position;
}
}
and My Model class
public class Restaurant implements Serializable {
private int id;
private String name;
private String address;
private int type;
private boolean hasNote = false;
private int image;
public Restaurant() {
}
public Restaurant(String name, String address,int type){
this.name = name;
this.address = address;
this.type = type;
}
public Restaurant(int id, String name, String address,int type){
this.id = id;
this.name = name;
this.address = address;
this.type = type;
}
public Restaurant(int id, String name, String address, int type,int image) {
this.id = id;
this.name = name;
this.address = address;
this.type = type;
this.image = image;
}
public int getId() { return id;}
public void setId (int id) { this.id = id;}
public String getName() {
return name;
}
public void setName(String name) { this.name = name;}
public boolean isHasNote(){
return hasNote;
}
public void setHasNote(boolean hasNote){
this.hasNote = hasNote;
}
public String getAddress() { return address;}
public void setAddress(String address) { this.address = address;}
public void setType(int type) {this.type = type;}
public int getType() {return type;}
public int getImage() {return image;}
public void setImage(int image) {this.image = image;}
}
You have not initialized adapter. Try to initialize it before use.
public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener{
//remove this
//RecyclerView.Adapter mAdapter;
//User this everywhere
RestaurantAdapter adapter;
.....
public void sendRequest() {
....
adapter = new RestaurantAdapter(MainActivity.this, restaurants);
recyclerView.setAdapter(adapter);
....
}
}
I am getting the values from api(which list of Names with Id which i stored in model)- How to set this Name to AutoComplete and get both Name and Id on dropdown selection.
This will set a Name in autocomplete and getting name at onItemClick but how to get ID?
Model class
public class MeetingContactModel implements Serializable {
private String id;
private String text;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
MyActivity class
OnCreate :
calling autocomplete adapter
setMeetingContactAuto(autoContact, contactList);
autoContact.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
strContact =(String) parent.getItemAtPosition(position);
// strContactCode = code.get(position);
}
});
private void setMeetingContactAuto(AutoCompleteTextView autoContact, final ArrayList<MeetingContactModel> xcontactList) {
List<String> names = new AbstractList<String>() {
#Override
public int size() { return xcontactList.size(); }
#Override
public String get(int i) {
code.clear();
code.add(xcontactList.get(i).getText());
return xcontactList.get(i).getText();
}
};
autoContact.setThreshold(1);
autoContact.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, names));
}
Not able to get Id - Please let me know to get it
Implement toString() method in your model class
public class MeetingContactModel implements Serializable {
private String id;
private String text;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
#Override
public String toString() {
return text;
}
}
// Fetch your selected model
autoContact.setAdapter(new ArrayAdapter<>(requireContext(), R.layout.spinner_item_ranking, contactList));
autoContact.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MeetingContactModel m=(MeetingContactModel) parent.getItem(position);
String name=m.getText();
String id=m.getId();
}
});
I have a fragment that is suppose to show a list of Game objects. When the fragment starts, I read all the Game objects from the database and add them to a List. It all works fine until the size of the list reaches 12. If it does, the App crashes even before the fragment is shown. If the list is bigger than 13 then it only crashes if I scroll all the way down and try and show the Games that are below.
Any ideas on what could cause this? I don´t really believe the RecyclerView is the problem.
Here are my classes. Please let me know if you need more information.
Any help would be very welcome.
My Game class
public class Game extends RealmObject{
#PrimaryKey
private long id;
private RealmList<Coordinates> mGameCoordinates;
private RealmList<Coordinates> mDrinkingStopsCoordinates;
private RealmList<Team> mTeams;
private String mDate;
private boolean mIsGameFinished;
private long mStartTime;
private long mFinishTime;
private long mTimeTaken;
public Game(RealmList<Team> teams, String date, long id) {
mTeams = teams;
mDate = date;
this.id = id;
}
public int getGameSize(){
int size = mTeams.size();
return size;
}
public String getDate() {
return mDate;
}
public void setDate(String date) {
mDate = date;
}
public RealmList<Team> getTeams() {
return mTeams;
}
public void setTeams(RealmList<Team> teams) {
mTeams = teams;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
//Default empty constructor - must be present
public Game(){
}
public RealmList<Coordinates> getDrinkingStopsCoordinates() {
return mDrinkingStopsCoordinates;
}
public void setDrinkingStopsCoordinates(RealmList<Coordinates> drinkingStopsCoordinates) {
mDrinkingStopsCoordinates = drinkingStopsCoordinates;
}
public RealmList<Coordinates> getGameCoordinates() {
return mGameCoordinates;
}
public void setGameCoordinates(RealmList<Coordinates> gameCoordinates) {
mGameCoordinates = gameCoordinates;
}
public long getStartTime() {
return mStartTime;
}
public void setStartTime(long startTime) {
mStartTime = startTime;
}
public long getFinishTime() {
return mFinishTime;
}
public void setFinishTime(long finishTime) {
mFinishTime = finishTime;
}
public long getTimeTaken() {
mTimeTaken = mFinishTime - mStartTime;
return mTimeTaken;
}
public void setTimeTaken(long timeTaken) {
mTimeTaken = timeTaken;
}
public boolean isGameFinished() {
return mIsGameFinished;
}
public void setGameFinished(boolean gameFinished) {
mIsGameFinished = gameFinished;
}
}
My Fragment
public class OldGameFragment extends Fragment {
private static final String TAG = "OldGameFragment";
private RecyclerView mRecyclerView;
private TextView mTextViewPlayers;
private TextView mTextViewDate;
private RecyclerAdapter mRecyclerAdapter;
private Toolbar myToolbar;
private String mStringReadyToShow;
private List<Game> mGames;
private RealmResults<Game> playerRealmResults;
private List<Game> mGameRealmList = new ArrayList<>();
private Realm mRealm;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_old_game, container,false);
//DB
mRealm = Realm.getDefaultInstance();
//Singleton
ActivityStateSingleton activityStateSingleton = ActivityStateSingleton.getInstance();
activityStateSingleton.setActivityFlag(1);
mRecyclerView = (RecyclerView)v.findViewById(R.id.recyclerview_player_list);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
//Toolbar
myToolbar = (Toolbar)v.findViewById(R.id.my_toolbar_old_game);
myToolbar.setTitle(R.string.drawer_old_game);
myToolbar.setTitleTextColor(0xffffffff);
((AppCompatActivity)getActivity()).setSupportActionBar(myToolbar);
((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
readFromDB();
return v;
}
//Fragment
public static OldGameFragment newInstance(){
return new OldGameFragment();
}
public void readFromDB(){
RealmResults<Game> playerRealmResults = mRealm.where(Game.class).findAll();
int count = 0;
for(Game game : playerRealmResults){
mGameRealmList.add(game);
count++;
Log.d(TAG, "Count " + count);
}
mRecyclerAdapter = new RecyclerAdapter(mGameRealmList);
mRecyclerView.setAdapter(mRecyclerAdapter);
mRecyclerView.addItemDecoration(new SimpleDividerItemDecoration(getContext()));
mRecyclerAdapter.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(long id) {
Intent intent = GameOverviewActivity.toGameOverview(getActivity(), id);
startActivity(intent);
}
});
mRecyclerAdapter.notifyDataSetChanged();
}
/*RecyclerView*/
public class RecyclerHolder extends RecyclerView.ViewHolder {
private Game mGame;
private SwipeRevealLayout mSwipeRevealLayout;
private View mDeleteView;
public RecyclerHolder(View itemView) {
super(itemView);
mTextViewPlayers = (TextView)itemView.findViewById(R.id.list_item_player_teams);
mTextViewDate = (TextView)itemView.findViewById(R.id.list_item_date);
mSwipeRevealLayout = (SwipeRevealLayout)itemView.findViewById(R.id.swipe_layout);
mDeleteView = (View) itemView.findViewById(R.id.delete_layout);
}
public void bindPlayer(Game game){
mGame = game;
String name = game.getTeams().get(0).getTeamName();
int num = game.getTeams().get(0).getPlayers().size();
String text = name + "(" + num + ")";
for(Team t : game.getTeams()){
if(!text.contains(t.getTeamName())){
name = t.getTeamName();
num = t.getPlayers().size();
text += " vs. " + name + "(" + num + ")";
}
mDeleteView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(getContext(),
R.style.AlertDialogCustom));
builder.setTitle(R.string.dialog_alert_title).setMessage(R.string.delete_game)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
mRecyclerAdapter.dismissGame(getAdapterPosition(), mGames.get(getAdapterPosition()).getId());
}
}).setNegativeButton("Nein", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getContext(), "No", Toast.LENGTH_SHORT).show();
}
});
AlertDialog dialog = builder.create();
dialog.show();
//So it won´t show the white borders around the round egdges
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
}
});
}
mTextViewPlayers.setText(text);
String date = getResources().getString(R.string.date) + game.getDate();
String space = " ";
mTextViewDate.setText(space + date);
}
}
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerHolder>{
/* This object helps you save/restore the open/close state of each view*/
private final ViewBinderHelper mViewBinderHelper = new ViewBinderHelper();
private OnItemClickListener mOnItemClickListener;
public RecyclerAdapter(List<Game> realmResults){
mGames = realmResults;
/*To only open one row at the time*/
mViewBinderHelper.setOpenOnlyOne(true);
}
#Override
public RecyclerHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View v = layoutInflater.inflate(
R.layout.list_item_game_rows, parent, false);
return new RecyclerHolder(v);
}
#Override
public void onBindViewHolder(RecyclerHolder holder, final int position) {
final Game game = mGames.get(position);
final String data = mGames.get(position).toString();
// You need to provide a String id which uniquely defines the data object.
mViewBinderHelper.bind(holder.mSwipeRevealLayout, data);
holder.bindPlayer(game);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
mOnItemClickListener.onItemClick(game.getId());
}
};
mTextViewDate.setOnClickListener(listener);
mTextViewPlayers.setOnClickListener(listener);
}
#Override
public int getItemCount() {
return mGames.size();
}
/*Dismiss Game*/
public void dismissGame(int position, final long id){
mGames.remove(position);
this.notifyItemRemoved(position);
mRealm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
RealmResults<Game> gameRealmResults = mRealm.where(Game.class).equalTo("id", id).findAll();
gameRealmResults.deleteAllFromRealm();
}
});
}
public OnItemClickListener getOnItemClickListener(){
return mOnItemClickListener;
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener){
this.mOnItemClickListener = onItemClickListener;
}
}
}
EDIT:
Here is the Log:
FATAL EXCEPTION: main Process: bosseln.swenden.de.bosseln, PID: 23424
Theme: themes:{default=overlay:com.init.designloper.init_v001, iconPack:com.init.designloper.init_v001, fontPkg:com.init.designloper.init_v001, com.android.systemui=overlay:com.init.designloper.init_v001, com.android.systemui.navbar=overlay:com.init.designloper.init_v001}
java.lang.ArrayIndexOutOfBoundsException: rowIndex > available rows: 0 > 0
at io.realm.internal.LinkView.nativeGetTargetRowIndex(Native Method)
at io.realm.internal.LinkView.getTargetRowIndex(LinkView.java:81)
at io.realm.RealmList.get(RealmList.java:448)
at bosseln.swenden.de.bosseln.fragments.OldGameFragment$RecyclerHolder.bindPlayer(OldGameFragment.java:149)
at bosseln.swenden.de.bosseln.fragments.OldGameFragment$RecyclerAdapter.onBindViewHolder(OldGameFragment.java:223)
at bosseln.swenden.de.bosseln.fragments.OldGameFragment$RecyclerAdapter.onBindViewHolder(OldGameFragment.java:195)
at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6279)
at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6312)
at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5258)
at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5521)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5363)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5359)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2141)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1525)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1488)
at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:585)
at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3506)
at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:3254)
at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3767)
at android.view.View.layout(View.java:16639)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1079)
at android.view.View.layout(View.java:16639)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
at android.view.View.layout(View.java:16639)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
at android.view.View.layout(View.java:16639)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1735)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1579)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1488)
at android.view.View.layout(View.java:16639)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
at android.view.View.layout(View.java:16639)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1735)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1579)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1488)
at android.view.View.layout(View.java:16639)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
at com.android.internal.policy.PhoneWindow$DecorView.onLayout(PhoneWindow.java:2934)
at android.view.View.layout(View.java:16639)
at android.view.ViewGroup.layout(ViewGroup.java:5437)
at android.
Please check the rows in the database, I think there may be some null value you are getting at row number 13.