Spinner OnItemSelected event not being called - java

I'm using the value in a spinner to help filter a list that will be the datasource for a RecyclerView. The OnItemSelect method never seems to be called when I use the spinner
It is an Android application, built in Java, using Pie for the OS. The project was created using the Basic Activity Template.
The Activity Class
package com.logicscrew.android;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import com.logicscrew.android.helpers.APIHelper;
import com.logicscrew.android.helpers.EmployeeAdapter;
import com.logicscrew.android.models.Department;
import com.logicscrew.android.models.Employee;
import java.util.ArrayList;
import java.util.List;
public class ViewByDepartment extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private List<Employee> employees;
private List<Employee> filteredList;
private List<Department> deparments;
private RecyclerView rcView;
private EmployeeAdapter adapter;
private Context context;
private Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
employees = new ArrayList<>();
deparments = new ArrayList<>();
filteredList = new ArrayList<>();
setContentView(R.layout.activity_view_by_department);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
spinner =(Spinner)findViewById(R.id.spnDepartments);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
context = this;
FetchTask task = new FetchTask(new AsyncResponse() {
#Override
public void processFinished(List<Employee> output) {
Log.i("Employees", "Finished");
}
});
DeptTask deptTask = new DeptTask(new DeptResponse() {
#Override
public void processFinished(List<Department> output) {
Log.i("Department", "Finished");
}
});
task.execute();
deptTask.execute();
rcView = findViewById(R.id.rcEmp);
adapter = new EmployeeAdapter(context, filteredList);
rcView.setLayoutManager(new LinearLayoutManager(context));
rcView.setAdapter(adapter);
ArrayAdapter<Department> deptAdapter = new ArrayAdapter<>(
this,
R.layout.spinner,
deparments
);
deptAdapter.setDropDownViewResource(
R.layout.spinner
);
spinner.setAdapter(deptAdapter);
spinner.setOnItemSelectedListener(this);
}
private void filter(){
filteredList.clear();
filteredList.addAll(employees);
for(Employee e : filteredList){
if(e.department != spinner.getSelectedItem()){
filteredList.remove(e);
}
}
adapter.swapDataSet(filteredList);
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
filter();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
private class FetchTask extends AsyncTask<Void, Void, List<Employee>> {
public AsyncResponse delegate = null;
public FetchTask(AsyncResponse asyncResponse){
delegate = asyncResponse;
}
#Override
protected List<Employee> doInBackground(Void... voids) {
return new APIHelper().fetchItems();
}
#Override
protected void onPostExecute(List<Employee> items) {
employees.addAll(items);
filteredList.addAll(items);
adapter.notifyDataSetChanged();
delegate.processFinished(items);
}
}
private class DeptTask extends AsyncTask<Void, Void, List<Department>>{
public DeptResponse delegate;
public DeptTask(DeptResponse response){
delegate = response;
}
#Override
protected List<Department> doInBackground(Void... voids) {
return new APIHelper().fetchDepartments();
}
#Override
protected void onPostExecute(List<Department> items){
deparments.addAll(items);
delegate.processFinished(items);
}
}
public interface AsyncResponse{
void processFinished(List<Employee> output);
}
public interface DeptResponse{
void processFinished(List<Department> output);
}
}
What should happen is when the event is called, it filters the list, removing anyone in the list who is not in a specific department, but the event is never called.

You try put in onCreate :
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int myPosition, long myID) {
//your method
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
}
});

Problem was an Async Race Condition. Fixed by moving the Spinner setup into the processFinished method in DeptTask.
DeptTask deptTask = new DeptTask(new DeptResponse() {
#Override
public void processFinished(List<Department> output) {
Log.i("Department", "Finished");
ArrayAdapter<Department> deptAdapter = new ArrayAdapter<Department>(
getApplicationContext(),
R.layout.spinner,
deparments
);
deptAdapter.setDropDownViewResource(
R.layout.spinner
);
spinner.setAdapter(deptAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Log.i("Selected Item", "I AM INDEED WORKING");
filter((Department)spinner.getSelectedItem());
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
});

Related

Index out of Bound on Item deletion in a Recycler View's adapter

I am trying to create a note-taking app focusing on color-changing.
In one of the activity, I am trying to implement item addition and deletion to the note
picture_of_the_activity.
Item addition obviously works as intended.
The problem is with the deletion, it is very inconsistent: when I delete all the item starting from the last one upward, everything work fine; if I delete items in another order the adapter mess up, do not always delete the correct one and crashes when removing the last item.
I looked it up and found some possible solution (here or in other websites) but couldn't find a solution, or, so I thought.
I created methods inside the adapter addItem() and removeItem() so any changes is done within the class.
Maybe I am misunderstanding a concept or missing something?
Thank you in advance!
some interfaces or protion of the code are missing because I didn't implement some features yet
Activity Code
package com.example.colornoteplus;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Objects;
public class CheckListNoteActivity extends AppCompatActivity{
// note editable views
private EditText titleView;
private TextView titleCharacterCount;
private ImageButton colorView;
private RecyclerView contentView;
private FloatingActionButton fab;
CheckListAdapter adapter;
// toolbar
private Toolbar toolbar;
// Current note
private CheckListNote note;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getNoteFromIntent();
note.getContent().add(new CheckListItem("ONE"));
note.getContent().add(new CheckListItem("TWO"));
note.getContent().add(new CheckListItem("THREE"));
note.getContent().add(new CheckListItem("FOUR"));
note.getContent().add(new CheckListItem("FIVE"));
changeViewsColor(0);
}
// Method used to add menus and configure button action
// like OnClickListeners ...
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Create a submenu for sorting purpose
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_check_list_activity,menu);
return super.onCreateOptionsMenu(menu);
}
// get note from the intent
private void getNoteFromIntent(){
if (!getIntent().getStringExtra(Statics.KEY_NOTE_ACTIVITY).equals(Statics.NOTE_DEFAULT_UID)){
note = MySharedPreferences.LoadCheckListNoteFromSharedPreferences(getIntent().getStringExtra(Statics.KEY_NOTE_ACTIVITY),getApplicationContext());
} else {
note = new CheckListNote();
}
}
private void changeViewsColor(int color){
// set the global theme
setTheme(StyleManager.getTheme(color));
// set the appropriate layout
setContentView(R.layout.activity_check_list_note);
// change status bar color
getWindow().setStatusBarColor(getResources().getColor(StyleManager.getThemeColor(color)));
// set up FAB action
fab = findViewById(R.id.fab_add_item);
fab.setOnClickListener(view -> onFabClickListener());
// setting the toolbar
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setBackgroundColor(getResources().getColor(StyleManager.getThemeColor(color)));
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
// setting the note title
titleView = findViewById(R.id.note_title_view);
titleView.setText("");
titleView.setTextColor(getResources().getColor(StyleManager.getThemeColorDark(color)));
titleView.setHintTextColor(getResources().getColor(StyleManager.getThemeColorLight(color)));
// setting the character counter for the note title
titleCharacterCount = findViewById(R.id.note_title_characters);
String m = titleView.getText().toString().trim().length()+ getString(R.string.text_divider)+ getResources().getInteger(R.integer.title_max_length);
titleCharacterCount.setText(m);
titleCharacterCount.setTextColor(getResources().getColor(StyleManager.getThemeColor(color)));
titleView.addTextChangedListener(new TextWatcher()
{
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int aft)
{
}
#Override
public void afterTextChanged(Editable s)
{
// this will show characters remaining
String msg = titleView.getText().toString().length()+ getString(R.string.text_divider)+ getResources().getInteger(R.integer.title_max_length);
titleCharacterCount.setText(msg);
}
});
// setting the color view
colorView = findViewById(R.id.note_color_view);
colorView.setOnClickListener(view -> buildColorPickDialog());
colorView.setBackgroundResource(StyleManager.getBackground(color));
adapter = new CheckListAdapter(getApplicationContext(),note.getContent(),color);
adapter.setOnItemClickListener(new CheckListAdapter.OnItemClickListener() {
#Override
public void onChecked(int position) {
Toast.makeText(CheckListNoteActivity.this, "Checked item: " +position, Toast.LENGTH_SHORT).show();
}
#Override
public void onUnchecked(int position) {
Toast.makeText(CheckListNoteActivity.this, "Unchecked item: " +position, Toast.LENGTH_SHORT).show();
}
#Override
public void onSetPriority(int position) {
}
#Override
public void onSetReminder(int position) {
}
#Override
public void onDelete(int position) {
adapter.removeItem(position);
Toast.makeText(CheckListNoteActivity.this, "List has "+note.getContent().size()+" elements", Toast.LENGTH_SHORT).show();
}
});
contentView = findViewById(R.id.note_content_view);
contentView.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
contentView.setAdapter(adapter);
}
private void switchColor(int color){
String tempTitle = titleView.getText().toString().trim();
changeViewsColor(color);
titleView.setText(tempTitle);
}
// build the color picker dialog
private void buildColorPickDialog(){
FragmentPickColor fragment = new FragmentPickColor(new ColorAdapter(),5,note.getColor());
fragment.show(getSupportFragmentManager(),Statics.TAG_FRAGMENT_COLOR_PICK);
fragment.setOnItemClickListener(new ColorAdapter.OnItemClickListener() {
#Override
public void OnClickListener(int position) {
note.setColor(position);
switchColor(position);
fragment.dismiss();
}
#Override
public void OnLongClickListener(int position) {
}
});
}
private void onFabClickListener(){
FragmentAddCheckListItem fragment = new FragmentAddCheckListItem(note.getColor());
fragment.show(getSupportFragmentManager(),Statics.TAG_FRAGMENT_ADD_CHECK_LIST_ITEM);
fragment.setOnClickListener(new FragmentAddCheckListItem.OnClickListener() {
#Override
public void onConfirmClickListener() {
fragment.getItem().setDescription(fragment.getInputText());
adapter.addItem(fragment.getItem(),0);
fragment.dismiss();
}
#Override
public void onSetPriorityClickListener() {
}
#Override
public void onSetDueTimeClickListener() {
FragmentDatePicker datePicker = new FragmentDatePicker();
datePicker.show(getSupportFragmentManager(),Statics.TAG_FRAGMENT_DATE_PICKER);
datePicker.setOnDateSet((year, month, day) -> {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR,year);
c.set(Calendar.MONTH,month);
c.set(Calendar.DAY_OF_MONTH,day);
fragment.getItem().setDueDate(c.getTime().getTime());
fragment.setDueTimeText(DateFormat.getDateInstance().format(new Date(fragment.getItem().getDueDate())));
});
}
});
}
}
Adapter
package com.example.colornoteplus;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.RecyclerView;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
public class CheckListAdapter extends RecyclerView.Adapter<CheckListAdapter.MyViewHolder> {
public CheckListAdapter(Context context,ArrayList<CheckListItem> list, int color) {
this.list = list;
this.color = color;
this.context = context;
}
final private ArrayList<CheckListItem> list;
final private int color;
final private Context context;
private OnItemClickListener listener;
#NonNull
#Override
public CheckListAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new CheckListAdapter.MyViewHolder(LayoutInflater.
from(parent.getContext()).
inflate(R.layout.item_check_list,parent,false));
}
#Override
public void onBindViewHolder(#NonNull CheckListAdapter.MyViewHolder holder, int position) {
CheckListItem currentItem = list.get(position);
holder.background.setBackgroundResource(StyleManager.getBackgroundLight(color));
holder.checkBox.setOnCheckedChangeListener((compoundButton, b) -> {
if (b) listener.onChecked(position);
else listener.onUnchecked(position);
});
holder.title.setTextColor(context.getResources().getColor(StyleManager.getThemeColorDark(color)));
holder.title.setHintTextColor(context.getResources().getColor(StyleManager.getThemeColor(color)));
assert currentItem != null;
holder.title.setText(currentItem.getDescription().trim());
holder.dueTimeText.setTextColor(context.getResources().getColor(StyleManager.getThemeColor(color)));
holder.dueTimeText.setText(currentItem.getDoneDate() != -1 ? DateFormat.getDateInstance().format(new Date(currentItem.getDueDate())) : context.getString(R.string.set_reminder));
holder.dueTimeText.setOnClickListener(view -> listener.onSetReminder(position));
holder.priorityText.setTextColor(context.getResources().getColor(StyleManager.getThemeColor(color)));
holder.priorityText.setText(currentItem.priorityToString(context));
holder.priorityText.setOnClickListener(view -> listener.onSetPriority(position));
holder.delete.setBackgroundResource(StyleManager.getBackground(color));
holder.delete.setOnClickListener(view -> {
// listener.onDelete(position);
removeItem(position);
});
}
#Override
public int getItemCount() {
return list.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
CheckBox checkBox;
ConstraintLayout background;
EditText title;
ImageButton delete;
TextView priorityText,dueTimeText;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
checkBox = itemView.findViewById(R.id.item_check_box);
title = itemView.findViewById(R.id.item_title);
dueTimeText = itemView.findViewById(R.id.item_due_time_text);
priorityText = itemView.findViewById(R.id.item_priority_text);
delete = itemView.findViewById(R.id.item_delete);
background = itemView.findViewById(R.id.item_background);
}
}
public void addItem(CheckListItem item,int position){
if (position < 0){
list.add(item);
notifyItemInserted(list.size()-1);
}
else {
list.add(position,item);
notifyItemInserted(position);
}
}
public void removeItem(int position){
list.remove(position);
notifyItemRemoved(position);
}
public void setOnItemClickListener(OnItemClickListener listener){
this.listener = listener;
}
public interface OnItemClickListener{
void onChecked(int position);
void onUnchecked(int position);
void onSetPriority(int position);
void onSetReminder(int position);
void onDelete(int position);
}
}
public void addItem(CheckListItem item, int position) {
if (position >= 0) {
list.add(position, item);
notifyItemInserted(position);
}
}
public void removeItem(int position) {
if (position >= 0) {
list.remove(position);
notifyItemRemoved(position);
}
}
And in onBindViewHolder use holder.getAdapterPosition() instead of position in your listeners like this:
holder.delete.setOnClickListener(view -> {
// listener.onDelete(position);
removeItem(holder.getAdapterPosition());
});

Pass data from the main activity to another activity using intent in android studio

I have a problem when passing data from the main activity to another activity using Intents.
I made MainActivity, BaiHat class and SecondActivity for getting data from the MainActivity.
Open logcat, there is an error like this:
(java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String java.lang.Object.toString()' on a null object
reference
at com.myappnvt.truyendulieu.MainActivity$1.onItemClick(MainActivity.java:30))
MainActivity.java:30 is line " String ten_bai_hat = listView.getItemAtPosition(position).toString();"
Here is the code:
package com.myappnvt.truyendulieu;
import android.os.Parcel;
import android.os.Parcelable;
import java.lang.reflect.Array;
public class BaiHat implements Parcelable {
private String tenBaiHat;
private int tenFile;
public BaiHat(String tenBaiHat, int tenFile) {
this.tenBaiHat = tenBaiHat;
this.tenFile = tenFile;
}
public BaiHat(Parcel in) {
tenBaiHat = in.readString();
tenFile = in.readInt();
}
public static final Creator<BaiHat> CREATOR = new Creator<BaiHat>() {
#Override
public BaiHat createFromParcel(Parcel in) {
return new BaiHat(in);
}
#Override
public BaiHat[] newArray(int size) {
return new BaiHat[size];
}
};
public String getTenBaiHat() {
return tenBaiHat;
}
public void setTenBaiHat(String tenBaiHat) {
this.tenBaiHat = tenBaiHat;
}
public int getTenFile() {
return tenFile;
}
public void setTenFile(int tenFile) {
this.tenFile = tenFile;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(tenBaiHat);
dest.writeInt(tenFile);
}
public static final Parcelable.Creator<BaiHat> creator = new Parcelable.Creator<BaiHat>(){
public BaiHat createFromParcel(Parcel in){
return new BaiHat(in);
}
public BaiHat[] newArray (int size){
return new BaiHat[size];
}
};
}
package com.myappnvt.truyendulieu;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
BaiHatAdapter adapter;
ListView listView;
ArrayList<BaiHat> baiHatArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Addlist();
adapter = new BaiHatAdapter(MainActivity.this, R.layout.dong_bai_hat, baiHatArrayList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String ten_bai_hat = listView.getItemAtPosition(position).toString();
startActivity(new Intent(getApplicationContext(),SecondActivity.class)
.putExtra("BAIHAT", baiHatArrayList)
.putExtra("TENBAIHAT", ten_bai_hat)
.putExtra("POSITION",position));
}
});
}
private void Addlist(){
listView = (ListView) findViewById(R.id.listViewdanhsach);
baiHatArrayList = new ArrayList<>();
baiHatArrayList.add(new BaiHat("Bến tương tư - Quang Linh", R.raw.ben_tuong_tu_quang_linh));
baiHatArrayList.add(new BaiHat("Buồn trong kỷ niệm - Đan Nguyên", R.raw.buon_trong_ky_niem_dan_nguyen));
baiHatArrayList.add(new BaiHat("Cát bụi cuộc đời - Phi Nhung", R.raw.cat_bui_cuoc_doi_phi_nhung));
baiHatArrayList.add(new BaiHat("Cho vừa lòng em - Như Nguyệt", R.raw.cho_vua_long_em_nhu_nguyet));
baiHatArrayList.add(new BaiHat("Chuyến đò không em - Tuấn Vũ", R.raw.chuyen_do_khong_em_tuan_vu));
}
}
package com.myappnvt.truyendulieu;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.widget.TextView;
import java.util.ArrayList;
public class SecondActivity extends AppCompatActivity {
String bai_hat ="";
int vi_tri =0;
TextView txtlaydulieu;
ArrayList<BaiHat> baiHatArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
txtlaydulieu = (TextView) findViewById(R.id.textViewlaydulieu);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
baiHatArrayList = (ArrayList) bundle.getParcelableArrayList("BAIHAT");
bai_hat = baiHatArrayList.get(vi_tri).getTenBaiHat().toString();
String songName = intent.getStringExtra("TENBAIHAT");
txtlaydulieu.setText(songName);
txtlaydulieu.setSelected(true);
vi_tri = bundle.getInt("POSITION",0);
Uri uri = Uri.parse(baiHatArrayList.get(vi_tri).toString());
MediaPlayer mediaPlayer = MediaPlayer.create(getApplicationContext(), uri);
mediaPlayer.start();
}
}
can you try to get item like this. instead of getting the list from the adapter you can also retrieve the source like belo. The error says nullpointer exception that means you are not getting the data from adapter. So instead try below once.
String ten_bai_hat = baiHatArrayList.get(position).toString();
Full code:
public class MainActivity extends AppCompatActivity {
BaiHatAdapter adapter;
ListView listView;
ArrayList<BaiHat> baiHatArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Addlist();
adapter = new BaiHatAdapter(MainActivity.this, R.layout.dong_bai_hat, baiHatArrayList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String ten_bai_hat = baiHatArrayList.get(position).toString();
startActivity(new Intent(getApplicationContext(),SecondActivity.class)
.putExtra("BAIHAT", baiHatArrayList)
.putExtra("TENBAIHAT", ten_bai_hat)
.putExtra("POSITION",position));
}
});
}
private void Addlist(){
listView = (ListView) findViewById(R.id.listViewdanhsach);
baiHatArrayList = new ArrayList<>();
baiHatArrayList.add(new BaiHat("Bến tương tư - Quang Linh", R.raw.ben_tuong_tu_quang_linh));
baiHatArrayList.add(new BaiHat("Buồn trong kỷ niệm - Đan Nguyên", R.raw.buon_trong_ky_niem_dan_nguyen));
baiHatArrayList.add(new BaiHat("Cát bụi cuộc đời - Phi Nhung", R.raw.cat_bui_cuoc_doi_phi_nhung));
baiHatArrayList.add(new BaiHat("Cho vừa lòng em - Như Nguyệt", R.raw.cho_vua_long_em_nhu_nguyet));
baiHatArrayList.add(new BaiHat("Chuyến đò không em - Tuấn Vũ", R.raw.chuyen_do_khong_em_tuan_vu));
}
}
Try to implement your BaiHatAdapter like this:
public class BaiHatAdapter extends ArrayAdapter {
public BaiHatAdapter(#NonNull Context context, int layout, int textViewId, #NonNull List<BaiHat> objects) {
super(context, layout, textViewId, objects);
}
#Nullable
#Override
public Object getItem(int position) {
BaiHat item = (BaiHat) super.getItem(position);
return (item != null && item.getTenBaiHat() != null) ? item.getTenBaiHat() : "Default TenBaiHat Text";
}
}
textViewId - id of TextView that will display the ten_bai_hat text.
Here you override the getItem method to return the tenBaiHat value. If either the item is null or the tenBaiHat string is null, then return some default text.

The Recyclerview is not showing the list

I'm trying to fetch data from an API and show the data into a recycler view. That API Contains an image URL and id. And I want to show the image from the URL and the id in the recycler view. But when I go to the Activity the recycler view is not showing the list. It is fetching the data from the API very well but it is not showing the data in the Recyclerview in a list format.
RecyclerviewAdapter.java
package com.madhulata.shriresume.shared;
import android.content.Context;
import android.util.Log;
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.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.madhulata.shriresume.R;
import java.util.ArrayList;
public class RecyclerviewAdapter extends RecyclerView.Adapter<RecyclerviewAdapter.ViewHolder>{
private ArrayList<String> mImageNames;
private ArrayList<String> mId;
private Context mContext;
public RecyclerviewAdapter(ArrayList<String> mImageNames, ArrayList<String> mId, Context mContext) {
this.mImageNames = mImageNames;
this.mId = mId;
this.mContext = mContext;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.resume_format,parent,false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
Log.d("Recycler","on Bind Called");
Glide.with(mContext)
.asBitmap()
.load(mImageNames.get(position))
.into(holder.resumeImage);
holder.resumeId.setText(mId.get(position));
holder.constraintLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(mContext, mImageNames.get(position), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return mImageNames.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView resumeImage;
TextView resumeId;
ConstraintLayout constraintLayout;
public ViewHolder(#NonNull View itemView) {
super(itemView);
resumeImage = itemView.findViewById(R.id.resumeLogo);
resumeId = itemView.findViewById(R.id.resumeId);
constraintLayout = itemView.findViewById(R.id.resumeTypeLayout);
}
}
}
***********************************SelectResume.java********************
package com.madhulata.shriresume.activity_dir;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.madhulata.shriresume.R;
import com.madhulata.shriresume.models.ResumeType;
import com.madhulata.shriresume.shared.RecyclerviewAdapter;
import com.madhulata.shriresume.shared.RetrofitClient;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class SelectResume extends AppCompatActivity {
RecyclerView selectResumeList;
private static final String TAG = "SignupActivity";
private ArrayList<String> mId;
private ArrayList<String> mUrls;
ProgressBar p;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_resume);
mId = new ArrayList<>();
mUrls = new ArrayList<>();
selectResumeList = findViewById(R.id.selectResumeList);
getResume();
}
private void initRecyclerView(){
Log.i("Value","init Recycler View");
RecyclerviewAdapter adapter = new RecyclerviewAdapter(mUrls,mId,this);
selectResumeList.setAdapter(adapter);
selectResumeList.setLayoutManager(new LinearLayoutManager(this));
}
private void getResume(){
Log.i("Value","Call method");
Call<List<ResumeType>> call = RetrofitClient.getInstance().getApi().getResume();
call.enqueue(new Callback<List<ResumeType>>() {
#Override
public void onResponse(Call<List<ResumeType>> call, Response<List<ResumeType>> response) {
if (!response.isSuccessful()){
Toast.makeText(SelectResume.this, response.code(), Toast.LENGTH_SHORT).show();
}else{
List<ResumeType> resume = response.body();
for (ResumeType r : resume){
mUrls.add(r.getUrl());
mId.add(r.getId());
Log.i("Value", mId.toString());
}
}
Log.i("Value","Call method 3");
}
#Override
public void onFailure(Call<List<ResumeType>> call, Throwable t) {
Toast.makeText(SelectResume.this, "Something went wrong!", Toast.LENGTH_SHORT).show();
}
});
initRecyclerView();
}
}
Why it is not showing?
Your initRecyclerView(); called before you update your data from the services. Retrofit callback works in a separate thread.
Try this instead of your method
private void getResume(){
Log.i("Value","Call method");
Call<List<ResumeType>> call = RetrofitClient.getInstance().getApi().getResume();
call.enqueue(new Callback<List<ResumeType>>() {
#Override
public void onResponse(Call<List<ResumeType>> call, Response<List<ResumeType>> response) {
if (!response.isSuccessful()){
Toast.makeText(SelectResume.this, response.code(), Toast.LENGTH_SHORT).show();
}else{
List<ResumeType> resume = response.body();
for (ResumeType r : resume){
mUrls.add(r.getUrl());
mId.add(r.getId());
Log.i("Value", mId.toString());
}
initRecyclerView();
}
Log.i("Value","Call method 3");
}
#Override
public void onFailure(Call<List<ResumeType>> call, Throwable t) {
Toast.makeText(SelectResume.this, "Something went wrong!", Toast.LENGTH_SHORT).show();
}
});
}
You can set adapter once at start in onCreate() even if your data is empty. You can add data later and call notifyDataSetChanged() on the adapter. The RecyclerView will be updated accordingly. This will save you from the overhead of setting adapter to RecyclerView each time you get some data.
public class SelectResume extends AppCompatActivity {
RecyclerView selectResumeList;
private static final String TAG = "SignupActivity";
private ArrayList<String> mId;
private ArrayList<String> mUrls;
ProgressBar p;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_resume);
mId = new ArrayList<>();
mUrls = new ArrayList<>();
selectResumeList = findViewById(R.id.selectResumeList);
initRecyclerView();
getResume();
}
private void initRecyclerView(){
Log.i("Value","init Recycler View");
RecyclerviewAdapter adapter = new RecyclerviewAdapter(mUrls, mId, this);
selectResumeList.setAdapter(adapter);
selectResumeList.setLayoutManager(new LinearLayoutManager(this));
}
private void getResume(){
Log.i("Value","Call method");
Call<List<ResumeType>> call = RetrofitClient.getInstance().getApi().getResume();
call.enqueue(new Callback<List<ResumeType>>() {
#Override
public void onResponse(Call<List<ResumeType>> call, Response<List<ResumeType>> response) {
if (!response.isSuccessful()) {
Toast.makeText(SelectResume.this, response.code(), Toast.LENGTH_SHORT).show();
} else {
List<ResumeType> resume = response.body();
for (ResumeType r : resume){
mUrls.add(r.getUrl());
mId.add(r.getId());
Log.i("Value", mId.toString());
}
adapter.notifyDataSetChanged();
}
Log.i("Value","Call method 3");
}
#Override
public void onFailure(Call<List<ResumeType>> call, Throwable t) {
Toast.makeText(SelectResume.this, "Something went wrong!", Toast.LENGTH_SHORT).show();
}
});
}
}
You receive the objects to show into RecyclerView from async network call. You need to update the adapter on the callback of your network call. Moreover I advice to initialize the adapter with empty list on the activity created, and after when you receive your data update the list with notifyDataSetChanged()
https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html#notifyDataSetChanged()

Getting error index out of bound exception in my recyclerview

I'm trying to get favourite items in favourite list from main list.When i click on favourite icon in mainlist, favouritelist get updating but when i remove any favourite from favouritelist and trying to add more favourites from mainlist i get error index out of bound exception
MainActivity
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends AppCompatActivity implements RecyclerViewClickListener{
RecyclerView simpleListView;
static Context ctx;
String diseaseList[];
SharedPreference sharedPreference;
DiseaseAdapter da;
List<String> newDiseaseList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ctx=this;
sharedPreference = new SharedPreference();
diseaseList= new String[]{"Abscess",
"Allergies",
"Amnesia",
"Anemia",
"Andropause",
"Angina",
"Weight Loss"};
Arrays.sort(diseaseList);
newDiseaseList = Arrays.asList(diseaseList);
simpleListView= (RecyclerView)findViewById(R.id.simpleListView);
LinearLayoutManager lm=new LinearLayoutManager(MainActivity.this);
simpleListView.setLayoutManager(lm);
/* DividerItemDecoration di=new DividerItemDecoration(MainActivity.this,lm.getOrientation());
simpleListView.addItemDecoration(di);*/
da=new DiseaseAdapter(newDiseaseList,ctx,this);
simpleListView.setAdapter(da);
simpleListView.setHasFixedSize(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_favorites:
Intent i=new Intent(this,Favourite.class);
this.startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
da.notifyDataSetChanged();
}
#Override
public void recyclerViewListClicked(View view, int position) {
ImageView button = (ImageView) view.findViewById(R.id.imgbtn_favorite);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(ctx, newDiseaseList.get(position));
Toast.makeText(ctx,
"add to favourites",
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.star_colour);
} else {
sharedPreference.removeFavorite(ctx, newDiseaseList.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.ic_action_name);
Toast.makeText(ctx,
"removed from favourites",
Toast.LENGTH_SHORT).show();
}
}
}
Favourite.java
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.Collections;
import java.util.List;
public class Favourite extends AppCompatActivity implements RecyclerViewClickListener {
RecyclerView favoriteList;
SharedPreference sharedPreference;
List<String> favorites;
DiseaseAdapter diseaseAdapter;
static Context ctx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favourite);
ctx=this;
sharedPreference = new SharedPreference();
favorites = sharedPreference.getFavorites(ctx);
Collections.sort(favorites);
favoriteList = (RecyclerView)findViewById(R.id.favListView);
LinearLayoutManager lm=new LinearLayoutManager(ctx);
favoriteList.setLayoutManager(lm);
favoriteList.setHasFixedSize(true);
if (favorites == null) {
showAlert(getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
} else {
if (favorites.size() == 0) {
showAlert(
getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
}
if (favorites != null) {
diseaseAdapter = new DiseaseAdapter(favorites,ctx,this);
favoriteList.setAdapter(diseaseAdapter);
}
}
}
public void showAlert(String title, String message) {
if (ctx != null) {
AlertDialog alertDialog = new AlertDialog.Builder(ctx)
.create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setCancelable(false);
// setting OK Button
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// activity.finish();
getFragmentManager().popBackStackImmediate();
}
});
alertDialog.show();
}
}
#Override
public void recyclerViewListClicked(View view, int position) {
ImageView button = (ImageView) view
.findViewById(R.id.imgbtn_favorite);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(ctx,
favorites.get(position));
Toast.makeText(
ctx,
ctx.getResources().getString(
R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.star_colour);
} else {
sharedPreference.removeFavorite(ctx,
favorites.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.ic_action_name);
/* diseaseAdapter.remove(favorites
.get(position));*/
diseaseAdapter.remove(position);
Toast.makeText(
ctx,
ctx.getResources().getString(
R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
}
}
Adapter
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by admin on 12/4/2017.
*/
public class DiseaseAdapter extends RecyclerView.Adapter<DiseaseAdapter.DiseaseAdapterViewHolder> {
List <String> data;
Context ctx;
private static RecyclerViewClickListener itemListener;
SharedPreference sharedPreference;
DiseaseAdapter(List <String> data, Context ctx, RecyclerViewClickListener itemListener){
this.data=data;
this.ctx=ctx;
sharedPreference = new SharedPreference();
this.itemListener = itemListener;
notifyDataSetChanged();
}
#Override
public DiseaseAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater=LayoutInflater.from(parent.getContext());
View view= inflater.inflate(R.layout.activity_listview,parent,false);
return new DiseaseAdapterViewHolder(view);
}
#Override
public void onBindViewHolder(DiseaseAdapterViewHolder holder, int position) {
final String title=data.get(position);
holder.textView1.setText(title);
if (checkFavoriteItem(title)) {
holder.imageButton.setImageResource(R.drawable.star_colour);
holder.imageButton.setTag("red");
} else {
holder.imageButton.setImageResource(R.drawable.ic_action_name);
holder.imageButton.setTag("grey");
}
}
#Override
public int getItemCount() {
return data.size();
}
class DiseaseAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView textView1;
ImageView imageButton;
public DiseaseAdapterViewHolder(View itemView) {
super(itemView);
textView1=(TextView) itemView.findViewById(R.id.textView);
imageButton=(ImageView)itemView.findViewById(R.id.imgbtn_favorite);
imageButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
notifyDataSetChanged();
itemListener.recyclerViewListClicked(v, this.getLayoutPosition());
}
}
/*Checks whether a particular product exists in SharedPreferences*/
public boolean checkFavoriteItem(String checkProduct) {
boolean check = false;
List<String> favorites = sharedPreference.getFavorites(ctx);
if (favorites != null) {
for (String product : favorites) {
if (product.equals(checkProduct)) {
check = true;
break;
}
}
}
return check;
}
public void add(String product) {
data.add(product);
notifyDataSetChanged();
}
public void remove(int position) {
data.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, data.size());
notifyDataSetChanged();
}
}
SharedPreference
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import com.google.gson.Gson;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SharedPreference {
public static final String PREFS_NAME = "PRODUCT_APP";
public static final String FAVORITES = "Product_Favorite";
public SharedPreference() {
super();
}
// This four methods are used for maintaining favorites.
public void saveFavorites(Context context, List<String> favorites) {
SharedPreferences settings;
Editor editor;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(favorites);
editor.putString(FAVORITES, jsonFavorites);
editor.commit();
}
public void addFavorite(Context context, String product) {
List<String> favorites = getFavorites(context);
if (favorites == null)
favorites = new ArrayList<String>();
favorites.add(product);
saveFavorites(context, favorites);
}
public void removeFavorite(Context context, String product) {
List<String> favorites = getFavorites(context);
if (favorites != null) {
favorites.remove(product);
saveFavorites(context, favorites);
}
}
public ArrayList<String> getFavorites(Context context) {
SharedPreferences settings;
List<String> favorites ;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
String [] favoriteItems = (gson.fromJson(jsonFavorites,String [].class));
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList<String>(favorites);
} else
return null;
return (ArrayList<String>) favorites;
}
}
This is an error that i'm getting
FATAL EXCEPTION: main
Process: com.example.admin.fav, PID: 10974
java.lang.IndexOutOfBoundsException: Invalid index 3, size is 3
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.example.admin.fav.Favourite.recyclerViewListClicked(Favourite.java:145)
at com.example.admin.fav.DiseaseAdapter$DiseaseAdapterViewHolder.onClick(DiseaseAdapter.java:90)
at android.view.View.performClick(View.java:5207)
at android.view.View$PerformClick.run(View.java:21168)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Problem in your listener. You are using same adapter class for both MainActivity recylerview & Favourite activity recylerview. After you go back from favourite activity to Mainactivity still your listener read from Favourite activity. Thats the issue.
Solution
Create Static field to hold listener value here am created in SharedPreference Class:
public class SharedPreference {
public static final String PREFS_NAME = "PRODUCT_APP";
public static final String FAVORITES = "Product_Favorite";
/*Added*/
private static RecyclerViewClickListener listener;
public RecyclerViewClickListener getListener() {
return listener;
}
public void setListener(RecyclerViewClickListener listener) {
SharedPreference.listener = listener;
}
/*Added*/
...
}
Add this code to MainActivity & Favourite Activity 'OnCreate' method
sharedPreference.setListener(this);
public class MainActivity extends AppCompatActivity implements RecyclerViewClickListener{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreference.setListener(this);
....
}
public class Favourite extends AppCompatActivity implements RecyclerViewClickListener{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favourite);
sharedPreference.setListener(this);
....
}
Change Adapter 'OnClick method' to
#Override
public void onClick(View v) {
notifyDataSetChanged();
itemListener = sharedPreference.getListener();
itemListener.recyclerViewListClicked(v, this.getLayoutPosition());
}
And Finally change in MainActivity 'resume' method
#Override
protected void onResume() {
super.onResume();
sharedPreference.setListener(this);
da.notifyDataSetChanged();
}
Hope it helps.!
In your DiseaseAdapterViewHolder change the onclick methode to,
#Override
public void onClick(View v) {
itemListener.recyclerViewListClicked(v, this.getLayoutPosition());
notifyDataSetChanged();
}

Open new activity from Recyclerview containing cards

Have an apparently simple task of -
Display a list of items using recycler view and each item should be card view.On click of any item new screen should open which shows detail of that item.
I already have seen various questions posted on the same topic, I would appreciate a little help on the attempt ive made rather than redirecting me there, since I'm pretty new and unable to understand how exactly to implement just by seeing those answers.I have tried to follow a tutorial closely but clearly have failed in replicating the results.HERE ARE THE FILES
MainActivity.java
. package com.example.hardikvats.recylerviewdemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private String[] phones={"MotoX","Nokia Asha","Lumia 710","Iphone 7s"};
private String[] OperatingSytem={"Android","Symbian","Windows","Ios"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RecyclerView recyclerView= (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setItemAnimator(new DefaultItemAnimator());
MyAdapter adapter=new MyAdapter(this,phones);
recyclerView.setAdapter(adapter);
}
}
MyAdapter.java
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Hardik Vats on 20-Jan-17.
*/
public class MyAdapter extends RecyclerView.Adapter<MyHolder> {
Context c;
String[] phones;
String[] OperatingSystem;
//CONSTRUCTOR
public MyAdapter(Context c, String[] PhoneModel){
this.c=c;
this.phones=PhoneModel;
//this.OperatingSystem=OperatingSystem;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
//INFLATING FROM XML TO JAVA VIEW
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.model,null);
MyHolder holder=new MyHolder(v);
return holder;
}
#Override
public void onBindViewHolder(MyHolder holder, int position) {
holder.PhoneModel.setText(phones[position]);
holder.setItemClickListner(new ItemClickListner() {
#Override
public void onItemClick(View v, int position) {
Intent i=new Intent(c,DetailActivity.class);
i.putExtra("OS name",OperatingSystem[position]);
}
});
}
#Override
public int getItemCount() {
return phones.length;
}
}
MyHolder.java
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
/**
* Created by Hardik Vats on 20-Jan-17.
*/
public class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView PhoneModel;
ItemClickListner icl;
public MyHolder(View itemView) {
super(itemView);
PhoneModel=(TextView) itemView.findViewById(R.id.MobilePhone);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
this.icl.onItemClick(v,getLayoutPosition());
}
public void setItemClickListner(ItemClickListner itemClickListner){
this.icl=itemClickListner;
}
}
DetailActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class DetailActivity extends AppCompatActivity {
TextView OperatingSystem;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail2);
Intent i=getIntent();
final String OperatingSystem =i.getExtras().getString("Operating System");
}
}
ItemClickListner.java(Interface)
`import android.view.View;
/**
* Created by Hardik Vats on 20-Jan-17.
*/
public interface ItemClickListner {
void onItemClick(View v, int position);
}`
The goal is to click each list item from phones array and get an activity listing the OS in a new activity in a new textfield
after i.putExtra("OS NAME ....
add this line
c.startActivity(c,DetailActivity.class);
As you did, in order that changes to be small, try this:
holder.PhoneModel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(c,DetailActivity.class);
i.putExtra("OS name",OperatingSystem[holder.getAdapterPosition()]);
}
});
Holder will always retain your position.
//set on item click listener like this
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Toast.makeText(MainActivity.this, "Card at " + position + " is clicked", Toast.LENGTH_SHORT).show();
// here you can start your detail Activity
Intent i=new Intent(c,DetailActivity.class);
i.putExtra("OS name",OperatingSystem[position]);
c.startActivity(i);
}
}));
// here is the on item click listener class
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
GestureDetector mGestureDetector;
public interface OnItemClickListener{
public void onItemClick(View view, int position);
}
public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View childView = rv.findChildViewUnder(e.getX(),e.getY());
if(childView != null && mListener != null && mGestureDetector.onTouchEvent(e)){
mListener.onItemClick(childView, rv.getChildAdapterPosition(childView));
return true;
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override`enter code here`
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}

Categories

Resources