1

I have an ArrayList in my mainActivity which stores String data. After declaring the ArrayList data are inserted from a database to the ArrayList. then when user clicks any element on ListView. I am trying to get data from the ArrayList using index value. Below is the code I am using.

ArrayList<String> list = new ArrayList<String>();
list.add("rice");
list.add("wheat");

Then I try to get data like

String data=list.get(0);
mtTextView.setText(data); //error is shown on this line

Where is the error and why I am getting the error. I cant find any wrong with the code

I followed below thread

assign arraylist value to textview

It tells to convert to string (as they had int value) but already i have string variable.

6
  • 2
    What's the error that is shown? Commented Jan 20, 2016 at 9:12
  • Post more relevant code. Commented Jan 20, 2016 at 9:13
  • Show the code u are loading data from database.. Commented Jan 20, 2016 at 9:14
  • 5
    The only problem in the above code could be that mtTextView is not properly initialized or the list has null elements. Provide more code or add dummy values to setText to validate further. Commented Jan 20, 2016 at 9:15
  • did you define the textview properly Commented Jan 20, 2016 at 9:19

2 Answers 2

0

Make sure you initialise every thing properly. This is my code.

MainActivity.class

public class MainActivity extends AppCompatActivity {

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

        TextView textview = (TextView) findViewById(R.id.text);

        ArrayList<String> list = new ArrayList<String>();
        list.add("rice");
        list.add("wheat");

        String data=list.get(0);
        textview.setText(data);
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.codephillip.intmain.cpgenerator.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/text"
        android:text="Hello World!"/>
</RelativeLayout>
Sign up to request clarification or add additional context in comments.

Comments

0
TextView mtTextView= (TextView) findViewById(R.id.textview);
String data=list.get(0);
mtTextView.setText(data);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.