0

I converted my listview into a recyclerview. It works when I run the code and displays fine. However, I want when I click on an item on the recyclerview, it returns that particular item. I am using a toast message in order to test that. Instead of returning that item, it shows "com.example.android.basicrecycle.Word@52809370" in the Toast message. How do I show that item instead?

MainActivity.java

public class MainActivity extends AppCompatActivity implements WordAdapter.ListItemClickListener{
    private RecyclerView mRecyclerView;
    private WordAdapter mWordAdapter;

    //Create a Toast variable called mToast to store the current Toast
    private Toast mToast;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Database of words

        final ArrayList<Word> words = new ArrayList<Word>();
        words.add(new Word("one", "uno"));
        words.add(new Word("two", "dos"));
        words.add(new Word("three", "tres"));
        words.add(new Word("four", "cuatro"));
        words.add(new Word("five", "cinco"));
        words.add(new Word("six", "seis"));
        words.add(new Word("seven", "siete"));
        words.add(new Word("eight", "ocho"));
        words.add(new Word("nine", "nueve"));
        words.add(new Word("ten", "diez"));
        words.add(new Word("eleven", "once"));
        words.add(new Word("twelve", "doce"));
        words.add(new Word("thirteen", "trece"));
        words.add(new Word("fourteen", "catorce"));
        words.add(new Word("fifteen", "quince"));

        mRecyclerView = (RecyclerView) findViewById(R.id.list);

        // use this setting to improve performance if you know that changes
        // in content do not change the layout size of the RecyclerView
        mRecyclerView.setHasFixedSize(true);

        // use a linear layout manager
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);

        mRecyclerView.setLayoutManager(layoutManager);

        // Pass in this as the ListItemClickListener to the WordAdapter constructor
        mWordAdapter = new WordAdapter(words, this);
        mRecyclerView.setAdapter(mWordAdapter);

        //The "NextButton launches DetailActivity
        Button nextButton = (Button)findViewById(R.id.next_button);
        nextButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                Intent intent = new Intent(getApplicationContext(), DetailActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    public void onListItemClick(ArrayList<Word> words, int i) {
        //In the beginning of the method, cancel the Toast if it isn't null
        if (mToast != null) {
            mToast.cancel();
        }

        //Show a Toast when an item is clicked, displaying that item number that was clicked
        String toastMessage = "Hello " + String.valueOf(words.get(i));
        mToast = Toast.makeText(this, toastMessage, Toast.LENGTH_LONG);

        mToast.show();
    }
}

Word.java

public class Word {
    /** Default translation for the word */
    private String mEnglishTranslation;

    /** Spanish translation for the word */
    private String mSpanishTranslation;

    /**
     * Create a new Word object.
     *
     * @param englishTranslation is the word in a language that the user is already familiar with
     *                           (such as English)
     * @param spanishTranslation is the word in the Spanish language
     */
    public Word(String englishTranslation, String spanishTranslation) {
        mEnglishTranslation = englishTranslation;
        mSpanishTranslation = spanishTranslation;
    }

    /**
     * Get the default translation of the word.
     */
    public String getEnglishTranslation() {
        return mEnglishTranslation;
    }

    /**
     * Get the Spanish translation of the word.
     */
    public String getSpanishTranslation() {
        return mSpanishTranslation;
    }
}

WordAdapter.java

public class WordAdapter extends RecyclerView.Adapter <WordAdapter.ViewHolder>{
    //add An on-click handler that we've defined to make it easy for an Activity to interface with RecyclerView
    final private ListItemClickListener mOnClickListener;

    private ArrayList<Word> words;

    //Add an interface called ListItemClickListener. Within that interface, define a void method called onListItemClick that takes an int as a parameter
    public interface ListItemClickListener {
        void onListItemClick(ArrayList<Word> words, int i);
    }

    //Add a ListItemClickListener as a parameter to the constructor and store it in mOnClickListener
    public WordAdapter(ArrayList<Word> words, ListItemClickListener listener) {
        mOnClickListener = listener;
        this.words = words;
    }
    //Inflate an item view
    @Override
    public WordAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item, viewGroup, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(WordAdapter.ViewHolder viewHolder, int i) {
        // Retrieve the data for that position
        viewHolder.mEnglish.setText( words.get(i).getEnglishTranslation());
        viewHolder.mSpanish.setText( words.get(i).getSpanishTranslation());
    }

    @Override
    public int getItemCount() {
        return words.size();
    }

    //Implement OnClickListener in the ViewHolder class
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        private TextView mEnglish;
        private TextView mSpanish;

        public ViewHolder(View view) {
            super(view);

            mEnglish = (TextView)view.findViewById(R.id.english_textview);

            mSpanish = (TextView)view.findViewById(R.id.spanish_textview);
            //Call setOnClickListener on the View passed into the constructor (use 'this' as the OnClickListener)
            view.setOnClickListener(this);
        }

        //Override onClick, passing the clicked item's position (getAdapterPosition()) to mOnClickListener via its onListItemClick method
        @Override
        public void onClick(View view) {
            int i = getAdapterPosition();
            mOnClickListener.onListItemClick(words, i);
        }
    }
}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/list"
        android:scrollbars="vertical"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="7"
        android:background="#FFFFFF"
        xmlns:android="http://schemas.android.com/apk/res/android" />
    <Button
        android:id="@+id/next_button"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_gravity="center_horizontal"
        android:layout_weight="1"
        android:text="Next"/>
</LinearLayout>

list_item.xml

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="8dp">
    <TextView
        android:id="@+id/english_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#000000"
        tools:text="English" />
    <TextView
        android:id="@+id/spanish_textview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#000000"
        tools:text="Spanish" />
</LinearLayout>

build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.android.basicrecycle"
        minSdkVersion 17
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    compile 'com.android.support:recyclerview-v7:26.1.0'
}

logcat

03-16 23:01:55.280 1805-1805/com.example.android.basicrecycle V/WordAdapter.class: Hello: 0
03-16 23:01:55.280 1805-1805/com.example.android.basicrecycle V/WordAdapter.class: com.example.android.basicrecycle.Word@52809280
03-16 23:17:29.828 1805-1805/com.example.android.basicrecycle V/WordAdapter.class: Hello: 0
03-16 23:17:29.828 1805-1805/com.example.android.basicrecycle V/WordAdapter.class: com.example.android.basicrecycle.Word@52809280
03-16 23:17:39.368 1805-1805/com.example.android.basicrecycle V/WordAdapter.class: Hello: 3
03-16 23:17:39.368 1805-1805/com.example.android.basicrecycle V/WordAdapter.class: com.example.android.basicrecycle.Word@52809370
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Vinmister
  • 1
  • 1
  • Possible duplicate of [Java code output is weird?](https://stackoverflow.com/questions/24923929/java-code-output-is-weird) – DogeAmazed Mar 17 '18 at 09:13
  • too much code to look through: if you have questions provide your code as [mvce](https://stackoverflow.com/help/mcve). – Patrick Artner Mar 17 '18 at 10:18

1 Answers1

0

You just have to call the obect, not the value. Remove String.valueOf(...), is not necessary:

String toastMessage = "Hello " + words.get(i);

or use:

Word word = words.get(i);
String toastMessage = "Hello " + word.getEnglishTranslation() 
                    + " - " + word.getSpanishTranslation();

You are trying to show the whole object. In order to properly show the content of the Word object, you need to override toString() as well inside it. Something like:

public class Word {

    ...

    @Override
    public String toString() {
        return "EnglishTranslation: " + mEnglishTranslation 
            + "\nSpanishTranslation: " + mSpanishTranslation; 
    }
}

I also recommend you to include the toast inside the holder, and use directly the object.

adalpari
  • 3,052
  • 20
  • 39