I am getting an error when trying to set my view to display the ListView for the file I want to display(text file). I am pretty sure it has something to do with the XML. I just want to display the information from this.file = fileop.ReadFileAsList("Installed_packages.txt");. My code:
public class Main extends Activity {
private TextView tv;
private FileOperations fileop;
private String[] file;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.fileop = new FileOperations();
this.file = fileop.ReadFileAsList("Installed_packages.txt");
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.TextView01);
ListView lv = new ListView(this);
lv.setTextFilterEnabled(true);
lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, this.file));
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
setContentView(lv);
}
}
list_item.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="10dp"
android:textSize="16sp"
android:textColor="#000">
</LinearLayout>
main.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1">
<ScrollView
android:id="#+id/SCROLLER_ID"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:fillViewport="true">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="5sp"
android:id="#+id/TextView01"
android:text="#string/hello"/>
</ScrollView>
</LinearLayout>
The ArrayAdapter requires the resource ID to be a TextView XML exception means you don't supply what the ArrayAdapter expects. When you use this constructor:
new ArrayAdapter<String>(this, R.layout.a_layout_file, this.file)
R.Layout.a_layout_file must be the id of a xml layout file containing only a TextView(the TextView can't be wrapped by another layout, like a LinearLayout, RelativeLayout etc!), something like this:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
// other attributes of the TextView
/>
If you want your list row layout to be something a little different then a simple TextView widget use this constructor:
new ArrayAdapter<String>(this, R.layout.a_layout_file,
R.id.the_id_of_a_textview_from_the_layout, this.file)
where you supply the id of a layout that can contain various views, but also must contain a TextView with and id(the third parameter) that you pass to your ArrayAdapter so it can know where to put the Strings in the row layout.
Soution is here
listitem.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textview"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</TextView>
</LinearLayout>
Java code :
String[] countryArray = {"India", "Pakistan", "USA", "UK"};
ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.listitem,R.id.textview, countryArray);
ListView listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(adapter);
If you are getting that message when you are extending an ArrayAdapter, you are getting that error because you have not provided the correct resource id to display the item. Call the super class in the constructor and pass in the resource id of the TextView:
//Pass in the resource id: R.id.text_view
SpinnerAdapter spinnerAddToListAdapter = new SpinnerAdapter(MyActivity.this,
R.id.text_view,
new ArrayList<>());
Adapter:
public class SpinnerAdapter extends ArrayAdapter<MyEntity> {
private Context context;
private List<MyEntity> values;
public SpinnerAdapter(Context context, int textViewResourceId,
List<MyEntity> values) {
//Pass in the resource id: R.id.text_view
super(context, textViewResourceId, values);
this.context = context;
this.values = values;
}
The problem is in the line:
lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, this.file));
Because when i change it to:
lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, this.file));
It works!
Related
In my program, as soon as I create a ListView and I set a Simpleadapter as adapter, I try to get access of a View in this listView in order to change the background of this view depending on a condition. I do it with the method ListView.getChildAt(position). However, I get a nullPointer Exception and i do not understand why. Here is a part of my code that is concerned.
To better understand the code below: I have actually created 2 listViews in the code and Alarm is a class I have implemented. I simply retrieve some pieces of information through this class.
Java Code:
public class SmartAlarm extends AppCompatActivity {
private ListView list_view_alarms;
private ListView list_view_activates;
private List<HashMap<String, String>> listMapOfEachAlarm;
private List<HashMap<String, Integer>> listMapOfActivates;
private SimpleAdapter adapter_alarms;
private SimpleAdapter adapter_activates;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_smart_alarm);
list_view_alarms = (ListView) findViewById(R.id.list_alarm);
list_view_activates = (ListView) findViewById(R.id.list_activate);
listMapOfEachAlarm = new ArrayList<>();
listMapOfActivates = new ArrayList<>();
adapter_alarms = new SimpleAdapter(this, listMapOfEachAlarm, R.layout.item_alarm,
new String[]{"alarm", "title"}, new int[]{R.id.time, R.id.title});
adapter_activates = new SimpleAdapter(this, listMapOfActivates, R.layout.item_activate, new String[]{"alarm_drawable"}, new int[]{R.id.activate});
for (Alarm alarm : alarmList) {
HashMap<String, String> mapOfTheNewAlarm = new HashMap<>();
mapOfTheNewAlarm.put("alarm", alarm.getTime());
mapOfTheNewAlarm.put("title", alarm.getTitle());
listMapOfEachAlarm.add(mapOfTheNewAlarm);
HashMap<String, Integer> mapOfTheAlarmDrawable = new HashMap<>();
if (alarm.getActivated()) {
mapOfTheAlarmDrawable.put("alarm_drawable", R.drawable.alarm_on);
} else {
mapOfTheAlarmDrawable.put("alarm_drawable", R.drawable.alarm_off);
}
listMapOfActivates.add(mapOfTheAlarmDrawable);
}
list_view_alarms.setAdapter(adapter_alarms);
list_view_activates.setAdapter(adapter_activates);
for(int i=0; i<list_view_alarms.getCount();i++)
{
if(conditionRespected()){
list_view_alarms.getChildAt(i)
.setBackgroundColor(getResources().getColor (R.color.dark)); //The compilation error is here because list_view_alarms.getChildAt(i) is null
}
}
}
}
activity_smart_alarm.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/crazy_alarm"
android:orientation="vertical"
android:weightSum="10">
<CheckBox
android:id="#+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:text="Check the box if you want to activate the game" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ListView
android:id="#+id/list_alarm"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="8"
android:choiceMode="singleChoice"
android:divider="#FF0000"
android:dividerHeight="2dp" />
<ListView
android:id="#+id/list_activate"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:choiceMode="singleChoice"
android:divider="#FF0000"
android:dividerHeight="2dp" />
</LinearLayout>
</LinearLayout>
For people interested: To change the background of each view in the listView according to a specific condition, I have finally overrided the method getView() like this :
public View getView(int position, View convertView, ViewGroup parent)
{
convertView = super.getView(position, convertView, parent);
if(condition){
convertView.setBackgroundColor(getResources().getColor(R.color.dark));
}
else
{
convertView.setBackgroundColor(getResources().getColor(R.color.bright));
}
return convertView;
}
You aren't setting your main view. Your listview must be created inside of the view that your activity will actually be using. Right inside of your onCreate() add setContentView(R.layout.activity_main);
You also have to create a layout (in this case activity_main) and your listView has to be child of the activity_main layout
This might be what your activity_main looks like
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
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">
//and inside of here would be your listview
<android.support.v7.widget.ListViewCompat
android:id="#+id/list_alarm"
android:layout_width=""
android:layout_height=""></android.support.v7.widget.ListViewCompat>
</RelativeLayout>
I have the result of a sql query expressed in this way :
//The column attributes of a result table
ArrayList<String> columns_attributes;
// This contains the data of every row of the result
ArrayList<ArrayList<String>> rows_data;
How can i dinamically display it on an activity ? Thanks
MainActivity
public class MainActivity extends AppCompatActivity {
List<String> list = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list.add("Android");
list.add("iPhone");
list.add("Windows");
list.add("Blackberry");
list.add("Mac");
list.add("Laptop");
list.add("LCD");
list.add("Dell");
ArrayAdapter adapter = new ArrayAdapter<String>(MainActivity.this, R.layout.list_view_item, list);
ListView listView = (ListView) findViewById(R.id.mobile_list);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "Clicked: " + list.get(position), Toast.LENGTH_SHORT).show();
}
});
listView.setAdapter(adapter);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.vzw.www.listviewalert.MainActivity">
<ListView
android:id="#+id/mobile_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
list_view_item.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/label"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip"
android:textSize="16dip"
android:textStyle="bold" >
</TextView>
You can iterate over these list with simple for loops like this:
// for columns
for (String colAttr : columns_attributes) {
// do something with the string value
}
// for rows
for (List<String> row : rows_data) {
for (String rowAttr : row) {
// do something with the string value
}
}
To display a dynamic amount of data, a ListView is recommended to do the job. If you just want to display those strings, you can use a ListActivity and assign a ArrayAdapter to that ListView with the setListAdapter() method.
You may want to check this tutorial to get this done.
http://androidexample.com/Create_Listview_With_ListActivity_-_Android_Example/index.php?view=article_discription&aid=66
I'm experiencing the problem "Unfortunately, your listview has stopped working" when i was using the android emulator to run my codes.
Please take a look at my codes thanks!
For activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.it3783.listview.MainActivity">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Choose a location..."/>
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop="false"
android:id="#+id/spLocations"></ListView>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#+id/superHerosTV"
/>
</LinearLayout>
For MainActivity.java:
public class MainActivity extends AppCompatActivity {
ArrayAdapter<CharSequence>adapter;
TextView tvSelection;
ListView lvLocation;
String []strArray;
String []superHeros = {"1. Batman\n 2. SpiderMan", "1. Peter Pan\n2. Superman",
"1. IronMan\n2. Peter Pan", "1. SnowWhite \n2. Gingerbreadman"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_list_item_1, strArray);
tvSelection = (TextView) findViewById(R.id.superHerosTV);
lvLocation = (ListView) findViewById(R.id.spLocations);
Resources myRes = this.getResources();
strArray = myRes.getStringArray(R.array.locationArea);
lvLocation.setAdapter(adapter);
lvLocation.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String text = strArray[position];
tvSelection.setText(text);
}
});
adapter = ArrayAdapter.createFromResource(this, R.array.locationArea, android.R.layout.simple_list_item_1);
}
}
For strings.xml:
<resources>
<string name="app_name">ListView</string>
<string-array name="locationArea">
<item>North</item>
<item>South</item>
<item>East</item>
<item>West</item>
</string-array>
</resources>
adapter = new ArrayAdapter<CharSequence>(this,android.R.layout.simple_list_item_1, strArray);
This line in your onCreate methods takes the strArray, which is not initialized so its value is null.
Now when you set the adapter with null data to the listview, it crashes.
I have 2 xml file
MainActivity.xml
2.Example.xml
I have listview in Example.xml.the code I have written in Example.java. But the data is not displaying in listview..Kindly go through my code
Example.xml
<?xml version="1.0" encoding="utf-8"?>
<ViewSwitcher xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/profileSwitcher"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/listPasscode"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</ListView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test"/>
</LinearLayout>
</ViewSwitcher>
Example.java
public class ListViewAndroidExample extends Activity {
ListView listView ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listView = (ListView) findViewById(R.id.listPasscode);
// Define a new Adapter
// First parameter - Context
// Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is written
// Forth - the Array of data
// Array of strings...
String[] countryArray = {"India", "Pakistan", "USA", "UK"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, countryArray);
// Assign adapter to ListView
listView.setAdapter(adapter);
setContentView(R.layout.activity_list_view_android_example);
}
}
Is linking between xml and java file right ?If not suggest me
Try this..
Add setContentView before initializing the ListView
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view_android_example);
listView = (ListView) findViewById(R.id.listPasscode);
EDIT
Change this..
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, countryArray);
to
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, countryArray);
This question already has answers here:
ArrayAdapter requires ID to be a TextView error
(4 answers)
Closed 8 years ago.
I tried this tutorial http://windrealm.org/tutorials/android/android-listview.php "A Simple Android ListView Example"
But in my test in Eclipse I've crash in android application.
In LogCat I've this:
04-11 20:17:24.170: E/AndroidRuntime(7062):
java.lang.IllegalStateException: ArrayAdapter requires the resource ID
to be a TextView
Why the crash ?
class java
private ListView mainListView;
private ArrayAdapter<String> listAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mains);
mainListView = (ListView) findViewById(R.id.mainListView);
String[] xRemote = Remote.split(";");
ArrayList<String> planetList = new ArrayList<String>();
planetList.addAll(Arrays.asList(xRemote));
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow,
planetList);
listAdapter.addAll(xRemote);
mainListView.setAdapter(listAdapter);
mains.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/mainListView">
</ListView
</LinearLayout>
simplerow.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/rowTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="16sp" >
</TextView>
</LinearLayout>
Use
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow,
R.id.rowTextView, planetList);
The documentation says:
By default this class expects that the provided resource id references
a single TextView. If you want to use a more complex layout, use the
constructors that also takes a field id. That field id should
reference a TextView in the larger layout resource.
In simplerow.xml remove the LinearLayout and directly use TextView as the root