OnItemClick doesn't works - java

I created a custom class containing the parameters for an ArrayList, the Container to the Fragments and the Fragment's classes.
Like you see:
package com.example.android.testeclickitem;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class CustomClass {
private int mImage;
private String mName;
private String mLocalization;
private static int mFragmentI;
private static int mFragmentII;
private static int mFragmentIII;
public CustomClass (int image, String name, String localization, int fragmentI, int fragmentII, int fragmentIII){
mImage = image;
mName = name;
mLocalization = localization;
mFragmentI = fragmentI;
mFragmentII = fragmentII;
mFragmentIII = fragmentIII;
}
public int getImage() {
return mImage;
}
public void setImage(int mImage) {
this.mImage = mImage;
}
public String getName() {
return mName;
}
public void setName(String mName) {
this.mName = mName;
}
public String getLocalization() {
return mLocalization;
}
public void setLocalization(String mLocalization) {
this.mLocalization = mLocalization;
}
public static int getFragmentI() {return mFragmentI;}
public void setFragmentI(int mFragmentI) {
this.mFragmentI = mFragmentI;
}
public static int getFragmentII() {
return mFragmentII;
}
public void setFragmentII(int mFragmentII) {
this.mFragmentII = mFragmentII;
}
public static int getFragmentIII() {
return mFragmentIII;
}
public void setFragmentIII(int mFragmentIII) {
this.mFragmentIII = mFragmentIII;
}
public static class FragmentInflaterI extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(getFragmentI(), container, false);
}
}
public static class FragmentInflaterII extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(getFragmentII(), container, false);
}
}
public static class FragmentInflaterIII extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(getFragmentIII(), container, false);
}
}
static class Fragments extends FragmentPagerAdapter {
public Fragments (android.support.v4.app.FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
return new FragmentInflaterI();
} else if (position == 1){
return new FragmentInflaterII();
} else {
return new FragmentInflaterIII();
}
}
#Override
public int getCount() {
return 3;
}
}
public static class Container extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set the content of the activity to use the activity_main.xml layout file
setContentView(R.layout.layout_container);
// Find the view pager that will allow the user to swipe between fragments
ViewPager viewPager = (ViewPager) findViewById(R.id.layout_container);
// Create an adapter that knows which fragment should be shown on each page
Fragments adapter = new Fragments(getSupportFragmentManager());
// Set the adapter onto the view pager
viewPager.setAdapter(adapter);
}
}
}
On main class, i added the ArrayList and the OnItemClickListener with an Intent to open the Container and Fragments:
package com.example.android.testeclickitem;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
import static com.example.android.testeclickitem.CustomClass.Container;
public class Hoteis extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hoteis);
final ArrayList <CustomClass> lista = new ArrayList<>();
CustomClass hoteis = new CustomClass(0, "", "", 0, 0, 0);
hoteis.setImage(R.mipmap.ic_hotel_white_48dp);
hoteis.setName(getString(R.string.name_hotel));
hoteis.setLocalization(getString(R.string.local_hotel));
hoteis.setFragmentI(R.layout.fragment_hotel1_perfil);
hoteis.setFragmentII(R.layout.fragment_hotel1_preco);
hoteis.setFragmentIII(R.layout.fragment_hotel1_contato);
lista.add(hoteis);
CustomClass hoteis2 = new CustomClass(0, "", "", 0, 0, 0);
hoteis2.setImage(R.mipmap.ic_hotel_white_48dp);
hoteis2.setName(getString(R.string.name_hotel2));
hoteis2.setLocalization(getString(R.string.local_hotel2));
hoteis.setFragmentI(R.layout.fragment_hotel2_perfil);
hoteis.setFragmentII(R.layout.fragment_hotel2_preco);
hoteis.setFragmentIII(R.layout.fragment_hotel2_contato);
lista.add(hoteis2);
CustomClassAdapter itemAdapter = new CustomClassAdapter(this, lista);
ListView listView = (ListView) findViewById(R.id.lista_hoteis);
listView.setAdapter(itemAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Intent openFragment = new Intent(Hoteis.this, Container.class);
startActivity(openFragment);
}
});
}
}
The problem is: on click in any item of list, ever uses the lasts fragments declared - not the fragments declared on respective clicked item.
I try:
CustomClass customClass = list.get(position);
and
Intent openFragment = new Intent(Hoteis.this, Container.class);
startActivity(openFragment);
But doesn't works.
Does anyone know how to do the "OnItemClick" recognizes the position?

I think its because your fragments are declared as static. Because of the properties of static, your fragments are the same across all instances of CustomClass. You should read up on the static keyword here

Related

Why isn't onBindViewHolder getting called when I make a selection?

My scrolling list is displaying properly.
OnBindViewHolder is called for each item in initial display and when scrolling brings new items into view.
When I click on an item, I do see my ItemDetailsLookup and getItemDetails functions getting called, HOWEVER it doesn't call the OnBindViewHolder, and so setActivated isn't getting run.
The documentation for androidx.recyclerview.selection says "... When the user selects an item the library will record that in SelectionTracker then notify RecyclerView that the state of the item has changed. This will ultimately cause the value to be rebound by way of RecyclerView.Adapter#onBindViewHolder..." and I think I've done everything up to this point, but I must have missed something...
Any ideas?
Thanks
Here's my fragment:
package com.example.smartflashcards;
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.selection.ItemDetailsLookup;
import androidx.recyclerview.selection.SelectionPredicates;
import androidx.recyclerview.selection.SelectionTracker;
import androidx.recyclerview.selection.StableIdKeyProvider;
import androidx.recyclerview.selection.StorageStrategy;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class StackSelectionFragment extends Fragment {
private static final String ARG_COLUMN_COUNT = "column-count";
private int mColumnCount = 1;
static SelectionTracker<Long> tracker;
public StackSelectionFragment() {
}
#SuppressWarnings("unused")
public static StackSelectionFragment newInstance(int columnCount) {
StackSelectionFragment fragment = new StackSelectionFragment();
Bundle args = new Bundle();
args.putInt(ARG_COLUMN_COUNT, columnCount);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_stack_selection_list, container, false);
File directory = getActivity().getFilesDir();
List<String> filesList = new ArrayList(Arrays.asList(directory.list()));
if (view instanceof RecyclerView) {
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
recyclerView.setAdapter(new MyItemRecyclerViewAdapter(filesList));
recyclerView.getAdapter().hasStableIds();
this.tracker = new SelectionTracker.Builder<Long>(
"stack_selector",
recyclerView,
new StableIdKeyProvider(recyclerView),
new MyDetailsLookup(recyclerView),
StorageStrategy.createLongStorage()
).withSelectionPredicate(SelectionPredicates.<Long>createSelectAnything()).build();
}
return view;
}
final class MyDetailsLookup extends ItemDetailsLookup {
private final RecyclerView mRecyclerView;
MyDetailsLookup(RecyclerView recyclerView) {
mRecyclerView = recyclerView;
}
public #Nullable
ItemDetails getItemDetails(#NonNull MotionEvent e) {
View view = mRecyclerView.findChildViewUnder(e.getX(), e.getY());
if (view != null) {
RecyclerView.ViewHolder holder = mRecyclerView.getChildViewHolder(view);
if (holder instanceof MyItemRecyclerViewAdapter.ViewHolder) {
return ((MyItemRecyclerViewAdapter.ViewHolder)holder).getItemDetails();
}
}
return null;
}
}
}
Here's my adapter:
package com.example.smartflashcards;
import androidx.annotation.Nullable;
import androidx.recyclerview.selection.ItemDetailsLookup;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.smartflashcards.databinding.FragmentStackSelectionBinding;
import java.util.List;
public class MyItemRecyclerViewAdapter extends RecyclerView.Adapter<MyItemRecyclerViewAdapter.ViewHolder> {
private final List<String> mValues;
public MyItemRecyclerViewAdapter(List<String> items) {
setHasStableIds(true);
mValues = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(FragmentStackSelectionBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false));
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = getItemId(position);
holder.mContentView.setText(mValues.get(position));
holder.mContentView.setActivated(StackSelectionFragment.tracker.isSelected((long) position));
}
#Override
public int getItemCount() {
return mValues.size();
}
#Override
public long getItemId(int position) {
return (long)position;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final TextView mIdView;
public final TextView mContentView;
public Long mItem;
public ViewHolder(FragmentStackSelectionBinding binding) {
super(binding.getRoot());
mIdView = binding.itemNumber;
mContentView = binding.content;
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
public ItemDetailsLookup.ItemDetails<Long> getItemDetails() {
return new ItemDetailsLookup.ItemDetails<Long>() {
#Override
public int getPosition() {
return getAbsoluteAdapterPosition();
}
#Nullable
#Override
public Long getSelectionKey() {
return mItem;
}
};
}
}
}
By following the example at https://github.com/Thumar/recyclerview-selection/tree/master/app
I was able to get it working. See my working code below.
But I still don't know which of the changes made it work and why.
If anyone figures out what was causing my problem, please post a comment or answer.
Any and all other feedback is welcome as well.
THANKS
Here's my new fragment:
package com.example.smartflashcards;
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.selection.ItemDetailsLookup;
import androidx.recyclerview.selection.Selection;
import androidx.recyclerview.selection.SelectionPredicates;
import androidx.recyclerview.selection.SelectionTracker;
import androidx.recyclerview.selection.StableIdKeyProvider;
import androidx.recyclerview.selection.StorageStrategy;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class StackSelectionFragment extends Fragment {
// TODO: Customize parameter argument names
private static final String ARG_COLUMN_COUNT = "column-count";
// TODO: Customize parameters
private int mColumnCount = 1;
SelectionTracker<Long> tracker; //TODO: add private?
private StackSelectionListener listener;
public interface StackSelectionListener {
public void onSelectStack(String stack);
}
String selections = "";
/**
* Mandatory empty constructor for the fragment manager to instantiate the
* fragment (e.g. upon screen orientation changes).
*/
public StackSelectionFragment() {
}
// TODO: Customize parameter initialization
#SuppressWarnings("unused")
public static StackSelectionFragment newInstance(int columnCount) {
StackSelectionFragment fragment = new StackSelectionFragment();
Bundle args = new Bundle();
args.putInt(ARG_COLUMN_COUNT, columnCount);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_stack_selection_list, container, false);
File directory = getActivity().getFilesDir();
List<String> filesList = new ArrayList(Arrays.asList(directory.list()));
// Set the adapter
if (view instanceof RecyclerView) {
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
if (mColumnCount <= 1) {
recyclerView.setLayoutManager(new LinearLayoutManager(context));
} else {
recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
}
MyItemRecyclerViewAdapter adapter = new MyItemRecyclerViewAdapter(filesList);
recyclerView.setAdapter(adapter);
adapter.hasStableIds();
this.tracker = new SelectionTracker.Builder<Long>(
"stack_selector",
recyclerView,
new StableIdKeyProvider(recyclerView),
new MyDetailsLookup(recyclerView),
StorageStrategy.createLongStorage()
).withSelectionPredicate(SelectionPredicates.<Long>createSelectAnything()).build();
adapter.injectTracker(this.tracker);
SelectionTracker.SelectionObserver<Long> observer = new SelectionTracker.SelectionObserver<Long>() {
#Override
public void onSelectionChanged() {
super.onSelectionChanged();
//TODO: replace this placeholder action with something useful
selections = "";
tracker.getSelection().forEach(item -> selections += adapter.getContent(item.intValue()));//selections += item);
//listener.onSelectStack("selections"); //This causes an error???
Context context = getContext();
Toast toast = Toast.makeText(context, selections, Toast.LENGTH_LONG);
toast.show();
}
};
this.tracker.addObserver(observer);
}
return view;
}
final class MyDetailsLookup extends ItemDetailsLookup {
private final RecyclerView mRecyclerView;
MyDetailsLookup(RecyclerView recyclerView) {
mRecyclerView = recyclerView;
}
public #Nullable
ItemDetails getItemDetails(#NonNull MotionEvent e) {
View view = mRecyclerView.findChildViewUnder(e.getX(), e.getY());
if (view != null) {
RecyclerView.ViewHolder holder = mRecyclerView.getChildViewHolder(view);
if (holder instanceof MyItemRecyclerViewAdapter.ViewHolder) {
return ((MyItemRecyclerViewAdapter.ViewHolder)holder).getItemDetails();
}
}
return null;
}
}
Here's my new adapter:
package com.example.smartflashcards;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.selection.ItemDetailsLookup;
import androidx.recyclerview.selection.SelectionTracker;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
public class MyItemRecyclerViewAdapter extends RecyclerView.Adapter<MyItemRecyclerViewAdapter.ViewHolder> {
private final List<String> mValues;
private SelectionTracker<Long> selectionTracker;
public MyItemRecyclerViewAdapter(List<String> items) {
setHasStableIds(true); //TODO: remove redundancy between this and "recyclerView.getAdapter().hasStableIds()" in the Fragment
mValues = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_stack_selection, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
String item = this.mValues.get(position);
holder.bind(item, selectionTracker.isSelected((long) position));
}
#Override
public int getItemCount() {
return mValues.size();
}
#Override
public long getItemId(int position) {
return (long)position;
}
public String getContent(int position) {
return mValues.get(position);
}
public void injectTracker(SelectionTracker<Long> tracker)
{
this.selectionTracker = tracker;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final TextView mContentView;
public ViewHolder(#NonNull View itemView) {
super(itemView);
mContentView = itemView.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
public void bind(String item, Boolean activate) {
this.mContentView.setText(item);
itemView.setActivated(activate); //TODO: understand how "itemView" exists outside of the constructor
}
public ItemDetailsLookup.ItemDetails<Long> getItemDetails() {
return new ItemDetailsLookup.ItemDetails<Long>() {
#Override
public int getPosition() {
return getAbsoluteAdapterPosition();
}
#Nullable
#Override
public Long getSelectionKey() {
return (long) getAbsoluteAdapterPosition();
}
};
}
}
}

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.

E/RecyclerView: No adapter attached; skipping layout. Despite initializing adapter

Following this guide, I tried implementing RecycleView into Fragments. I got the error
E/RecyclerView: No adapter attached; skipping layout
The recycle view don't display anything
I tried
recyclerview No adapter attached; skipping layout
RecyclerView in Fragment : No adapter attached skipping layout
and many more.
My Code:
package com.example.celebrity_proper;
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
/**
* A simple {#link Fragment} subclass.
*/
public class MainFragment extends Fragment {
private RecyclerView choiceRecycleView2 = null;
private ChoiceAdapter adapter = null;
private ArrayList<Choice> choiceArrayList;
public MainFragment() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("Go here", "41");
View view = inflater.inflate(R.layout.fragment_main, container, false);
choiceRecycleView2 = view.findViewById(R.id.choiceRecycleView);
choiceRecycleView2.setLayoutManager(new LinearLayoutManager(getActivity()));
choiceArrayList = new ArrayList<>();
adapter = new ChoiceAdapter(getActivity(), choiceArrayList);
choiceRecycleView2.setAdapter(adapter);
createListData();
return view;
}
public void createListData() {
Choice choice = new Choice("Adolf Hitler");
choiceArrayList.add(choice);
choice = new Choice("Kim Jong Un");
Log.d("Item Count", String.valueOf(adapter.getItemCount()));
choiceArrayList.add(choice);
adapter.notifyDataSetChanged();
}
}
class Choice {
private String name;
public Choice(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
class ChoiceAdapter extends RecyclerView.Adapter<ChoiceViewHolder> {
private Context context;
private ArrayList<Choice> choices;
public ChoiceAdapter(Context context, ArrayList<Choice> choices) {
this.context = context;
this.choices = choices;
}
#NonNull
#Override
public ChoiceViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.choice_row, parent, false);
return new ChoiceViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ChoiceViewHolder holder, int position) {
Choice choice = choices.get(position);
holder.setDetails(choice);
}
#Override
public int getItemCount() {
return choices.size();
}
}
class ChoiceViewHolder extends RecyclerView.ViewHolder {
private TextView choice_row_text;
public ChoiceViewHolder(View view) {
super(view);
choice_row_text = view.findViewById(R.id.choice_row_text);
}
public void setDetails(Choice choice) {
choice_row_text.setText(choice.getName());
}
}
You are sending empty list to adapter constructor. Right Way
choiceRecycleView2 = view.findViewById(R.id.choiceRecycleView);
choiceRecycleView2.setLayoutManager(new LinearLayoutManager(getActivity()));
choiceArrayList = new ArrayList<>();
createListData();
adapter = new ChoiceAdapter(getActivity(), choiceArrayList);
choiceRecycleView2.setAdapter(adapter);
adapter.notifyDataSetChanged();
public void createListData() {
Choice choice = new Choice("Adolf Hitler");
choiceArrayList.add(choice);
choice = new Choice("Kim Jong Un");
Log.d("Item Count", String.valueOf(adapter.getItemCount()));
choiceArrayList.add(choice);
}
Give Orientation to LayoutManager.
Sample Code.
LinearLayoutManager manager = new LinearLayoutManager(this);
managersetOrientation(LinearLayoutManager.VERTICAL);
list.setLayoutManager(manager);
choiceRecycleView2.setAdapter( adapter );
So apparently it is an issue with AMD processor. I can't prove it since I am kicked from that class, I finished that class 2 months ago

How can i get the 3 textview from recyclerview and pass it to dialogbox

Im new to android programming so can you provide me the right code.
this is my code. the data is from sqlite. my problem is . How can i get the 3 textview from recyclerview and pass it to dialogbox when clicked? i finally made dialogbox but i can get only the position of the item i want to get all of the three textview data. please help me.
FragmentMeal.java
package inncharge.poy.madrigal.innchargev1.fragments;
import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import inncharge.poy.madrigal.innchargev1.R;
import inncharge.poy.madrigal.innchargev1.database.DatabaseHelper;
import inncharge.poy.madrigal.innchargev1.adapters.VivzAdapter;
/**
* A simple {#link Fragment} subclass.
* Use the {#link FragmentMeal#newInstance} factory method to
* create an instance of this fragment.
*/
public class FragmentMeal extends Fragment {
private DatabaseHelper db;
private RecyclerView recyclerView;
private VivzAdapter adapter;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment FragmentMeal.
*/
// TODO: Rename and change types and number of parameters
public static FragmentMeal newInstance(String param1, String param2) {
FragmentMeal fragment = new FragmentMeal();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public FragmentMeal() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
db = new DatabaseHelper(getActivity());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_meal, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.mealList);
adapter = new VivzAdapter(getActivity(),db.getMealData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getActivity(), recyclerView, new ClickListener() {
#Override
public void onClick(View view, int postion) {
final Dialog dialog = new Dialog(getActivity());
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setContentView(R.layout.custom_dialog);
dialog.show();
final EditText editText = (EditText)dialog.findViewById(R.id.editText_pin);
Button submitButton = (Button)dialog.findViewById(R.id.submit_button);
Button cancelButton = (Button)dialog.findViewById(R.id.cancel_button);
submitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = editText.getText().toString();
Toast.makeText(getActivity(), "Pin submitted is : " + text, Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.cancel();
}
});
}
#Override
public void onLongClick(View view, int position) {
Toast.makeText(getActivity(), "onLongClick" + position, Toast.LENGTH_SHORT).show();
}
}));
return view;
}
class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener){
Log.d("VIVZ", "constructor invoked ");
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e) {
Log.d("VIVZ","onSingleTapUp " + e);
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null){
clickListener.onLongClick(child, recyclerView.getChildAdapterPosition(child));
}
Log.d("VIVZ", "onLongPress " + e);
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)){
clickListener.onClick(child, rv.getChildAdapterPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
Log.d("VIVZ","onTouchEvent "+ e);
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public static interface ClickListener {
public void onClick(View arg1, int arg2);
public void onLongClick(View view, int position);
}
}
VivzAdapter.java
package inncharge.poy.madrigal.innchargev1.adapters;
import android.content.ClipData;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Collections;
import java.util.List;
import inncharge.poy.madrigal.innchargev1.R;
import inncharge.poy.madrigal.innchargev1.fragments.FragmentMeal;
import inncharge.poy.madrigal.innchargev1.pojo.Contact;
import inncharge.poy.madrigal.innchargev1.pojo.Information;
/**
* Created by Madrigal on 7/18/2015.
*/
public class VivzAdapter extends RecyclerView.Adapter<VivzAdapter.MyViewHolder> {
private Context context;
private final LayoutInflater inflater;
List<Contact> data = Collections.emptyList();
public VivzAdapter(Context context, List<Contact> data){
this.context=context;
inflater = LayoutInflater.from(context);
this.data=data;
}
public void delete(int position){
data.remove(position);
notifyItemRemoved(position);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.custom_row, parent, false);
Log.d("VIVZ","onCreateHolder called ");
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Contact current = data.get(position);
Log.d("VIVZ", "onBindViewHolder called " + position);
holder.itemId.setText(String.valueOf(current.getId()));
holder.title.setText(current.getName());
holder.email.setText(current.getEmail());
}
#Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView title;
public TextView email;
public TextView itemId;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.listTextName);
email = (TextView) itemView.findViewById(R.id.listTextUname);
itemId = (TextView) itemView.findViewById(R.id.listTextId);
}
#Override
public void onClick(View v) {
}
}
}
Slidenerd makes some great videos, he helped me a lot as well when I started.
You might want to reconsider what you're trying to do and approach it differently... Why would you want to pass 3 textview from your UI into a dialog?
This is going to be painful.
Seems like you're going to have to extend DialogFragment (i'm assuming that's what you're using for a dialog, maybe an alert?). Create a static factory method inside the DialogFragment like this...
public class MyDialog extends DialogFragment {
private static tv1, tv2, tv3;
public static MyDialog newInstance(TextView tv1, TextView tv2, TextView tv3){
MyDialog.tv1 = tv1;
MyDialog.tv2 = tv2;
MyDialog.tv3 = tv3;
return new MyDialog();
}
}
Once you have this complete, create this dialog fragment inside that onClick method in the ViewHolder class. Instantiate the DialogFragment by doing this...
MyDialog.newInstance(title,email,itemId).show(getFragmentManager(),"dialog_tag");
Like i said before, it's seems sloppy and is probably error prone. There may be a better way of doing this but this is all I can think of off the top of my head. Let me know how it works out for you.. or perhaps revise your question so we can better help you reach a better solution to what you're trying to do.

"Set wallpaper" button function, Android

I've created a custom gallery; however, the "Set wallpaper" button will not set the wallpaper. Here's the wallpaper.java I have. I'm just lost on how to implement OnClickListener and then set my button to use an onclicklistener like so:
buttonName.setOnClickListener(this);
package com.totem;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Gallery.LayoutParams;
import java.io.IOException;
import java.io.InputStream;
public class Wallpaper extends Activity implements
AdapterView.OnItemSelectedListener, AdapterView.OnItemClickListener {
private static final String LOG_TAG = "Home";
private static final Integer[] THUMB_IDS = {
R.drawable.andy_small,
};
private static final Integer[] IMAGE_IDS = {
R.drawable.andy,
};
private Gallery mGallery;
private boolean mIsWallpaperSet;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.wallpaper_chooser);
mGallery = (Gallery) findViewById(R.id.gallery);
mGallery.setAdapter(new ImageAdapter(this));
mGallery.setOnItemSelectedListener(this);
mGallery.setOnItemClickListener(this);
}
#Override
protected void onResume() {
super.onResume();
mIsWallpaperSet = false;
}
#SuppressWarnings("unchecked")
public void onItemSelected(AdapterView parent, View v, int position, long id) {
getWindow().setBackgroundDrawableResource(IMAGE_IDS[position]);
}
#SuppressWarnings("unchecked")
public void onItemClick(AdapterView parent, View v, int position, long id) {
selectWallpaper(position);
}
private synchronized void selectWallpaper(int position) {
if (mIsWallpaperSet) {
return;
}
mIsWallpaperSet = true;
try {
InputStream stream = getResources().openRawResource(IMAGE_IDS[position]);
setWallpaper(stream);
setResult(RESULT_OK);
finish();
} catch (IOException e) {
Log.e(LOG_TAG, "Failed to set wallpaper " + e);
}
}
#SuppressWarnings("unchecked")
public void onNothingSelected(AdapterView parent) {
}
public boolean onTouchEvent(MotionEvent event, Object Action_Down) {
getAction(Action_Down);
selectWallpaper(mGallery.getSelectedItemPosition());
return true;
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return THUMB_IDS.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
i.setImageResource(THUMB_IDS[position]);
i.setAdjustViewBounds(true);
i.setLayoutParams(new Gallery.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
i.setBackgroundResource(android.R.drawable.picture_frame);
return i;
}
}
}
Parsed in 0.242 seconds, using GeSHi 1.0.8.4
Go to http://www.xtensivearts.com/topics/tutorials/ there are video tutorials that will help you with the onclicklisteners
are you set user permission in androidmanifest file for set Wallpaper?
<uses-permission android:name="android.permission.SET_WALLPAPER" />

Categories

Resources