First of all, thank you for your answers! I\'m new for Android and this is my problem;
I want to take values of string array to listview.
Program works fin
remove android:entries
from your .xml file & define the string array into
String[] number = getResources().getStringArray(R.id.numbers);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, number);
Change to
String [] fiilliste;
ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.verbs);
fiilliste = getResources().getStringArray(R.array.fi);
// move this in onCreate
I assume you have the string array fi in strings.xml
.
You probably got NullPointerException
. You require activity context for getResources()
. So move it inside onCreate
.
here is what I did. i have created a string-array in array.xml
<resources>
<string-array name="numbers">
<item>1</item>
<item>2</item>
<item>3</item>
<item>4</item>
<item>5</item>
<item>6</item>
<item>7</item>
<item>8</item>
<item>9</item>
<item>10</item>
</string-array>
and put a lisView in my xml layout
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/listView"
android:entries="@array/numbers"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
here is my MainActivity look like.
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
ListView listView;
String[] number;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
number = getResources().getStringArray(R.array.numbers);
listView = (ListView) findViewById(R.id.listView);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, number);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView textView = (TextView) view;
Toast.makeText(this, textView.getText() , Toast.LENGTH_SHORT).show();
}
}
Your problem is that the code should be put in on create or any other function. Not as static variable