android


Android Studio: java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView


Android and Java newbie here. I was following a guide to create a stopwatch (among other things) in Android, and wanted to add a lap function and button, but I get the following error:
05-10 17:33:49.255 21844-21844/com.example.emily.a362first E/ArrayAdapter: You must supply a resource ID for a TextView
05-10 17:33:49.259 21844-21844/com.example.emily.a362first D/AndroidRuntime: Shutting down VM
05-10 16:37:25.618 15181-15181/com.example.emily.a362first E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.emily.a362first, PID: 15181
java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView
And then it says it is caused by:
Caused by: java.lang.ClassCastException: android.widget.ListView cannot be cast to android.widget.TextView
The other buttons work fine, so I excluded the code for them just to be concise, but can provided it if needed. I know there's probably plenty of other things wrong with this since I'm new to this. I assume it's something easyI have seen this and similar questions asked before, but the solutions to those questions didn't seem to work for me.
Here's the relevant java code and XML files. The other buttons work fine, and the app doesn't crash with any of them.
public class Stopwatch extends AppCompatActivity {
TextView currentTimeTextView;
Button btnStart, btnStop, btnRestart, btnLap;
long time_in_milliseconds, start_time, time_buff, update_time;
Handler handler;
int seconds, minutes, milliseconds, counter;
/* Stuff for the Lapping feature */
ListView listView;
String[] ListElements = new String[]{};
List<String> lapTimesArrayList;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stopwatch);
currentTimeTextView = (TextView) findViewById(R.id.currentTime);
btnStart = (Button) findViewById(R.id.btnStart);
btnStop = (Button) findViewById(R.id.btnStop);
btnRestart = (Button) findViewById(R.id.btnRestart);
btnLap = (Button) findViewById(R.id.btnLap);
listView = (ListView) findViewById(R.id.listViewLapTimes);
counter = 0;
handler = new Handler();
lapTimesArrayList =
new ArrayList<String>(Arrays.asList(ListElements));
adapter = new ArrayAdapter<String>(Stopwatch.this,
R.layout.activity_stopwatch, R.id.listViewLapTimes,
lapTimesArrayList);
listView.setAdapter(adapter);
//... omitted
btnLap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
counter++;
lapTimesArrayList.add(String.valueOf(counter) + ". "
+ currentTimeTextView.getText().toString());
}
});
}
public Runnable runnable = new Runnable() {
public void run() {
time_in_milliseconds = SystemClock.uptimeMillis() - start_time;
update_time = time_buff + time_in_milliseconds;
seconds = (int) (update_time / 1000);
minutes = seconds / 60;
seconds %= 60;
milliseconds = (int) (update_time % 1000);
currentTimeTextView.setText("" + minutes + ":" + String.format("%02d", seconds) + ":" +
String.format("%03d", milliseconds));
handler.postDelayed(this, 0);
}
};
}
And here's the relevant parts of the XML layout file
<?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:id="#+id/activity_stopwatch"
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="16dp"
android:background="#drawable/background_generic"
tools:context="com.example.emily.a362first.Stopwatch">
<!-- Lap times !-->
<ListView
android:id="#+id/listViewLapTimes"
android:layout_below="#+id/btnLap"
android:layout_marginTop="12dp"
android:overScrollMode="never"
android:divider="#null"
android:scrollbars="none"
android:layout_marginBottom="60dp"
android:layout_width="wrap_content"
android:textAlignment="center"
android:layout_height="match_parent"
android:layout_toEndOf="#+id/btnStart">
</ListView>
<!-- Displays total time elapsed !-->
<TextView
android:id="#+id/currentTime"
android:text="#string/initial_time"
android:includeFontPadding="false"
android:textStyle="normal"
android:textSize="60sp"
android:textColor="#ffffff"
android:gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:fontFamily="serif-monospace" />
<Button
android:id="#+id/btnLap"
android:textSize = "50sp"
android:background="#drawable/circular_button"
android:layout_width="100dp"
android:alpha="0.25"
android:layout_height="100dp"
android:layout_below="#+id/currentTime"
android:layout_centerHorizontal="true"
android:layout_marginTop="11dp" />
</RelativeLayout>
Any help is appreciated!
Reason for error:
You are using ArrayAdapter(android.content.Context, int, int, T[]) constructor, wherein the third argument is the id of the TextView within the layout resource to be populated but you are passing the id of the ListView (R.id.listViewLapTimes)
Resolution:
Follow Android: How to put ListView in XML? to create list item layout for your ListView (listViewLapTimes) and then send id of that TextView into ArrayAdapter() construtor call.
Example:
Your lap_item.xml representing individual lap information (for example, 00:25:49) will contain just a TextView with id 'lap_tv'
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/lap_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
Then, your constructor call can be as follows:
new ArrayAdapter<String>(Stopwatch.this,
R.layout.activity_stopwatch,
R.id.lap_tv, // <- this line is changed
lapTimesArrayList);
Best practice:
Given all above, RecyclerView is a better option than ListView for the reasons mentioned in Android Recyclerview vs ListView with Viewholder. Creating Lists using RecyclerView is easy to learn and yet powerful.

Related Links

Android MediaCodec + Surfaceview not smooth
How to multiply two EditTexts?
Can multiple Android Wears can be paired to a single Android Device
How to put ArrayList object to parameter on getParam
Unable to Logout after android Facebook Login
Are Snackbar Components available in Android L preview sdk?
Debugging a widget before launching the app
Android get sound recording volume
Test if the encrypted SD card is prepared and ready for use on device restart - sd card state?
SuperUser not working properly in CyanogenMod 11
Android ANR when trying to start service
Alarm Manager - triggers after every 2 hours
why text is texted wrongly in this method in android?
Broadcast Reciever Declaration in Manifest
How to save custom Objects onSaveInstanceState without implementing parcelable
Google play developer distribution agreement has changed [closed]

Categories

HOME
windows
porting
eslint
pagination
google-spreadsheet
numbers
camera
yandex
google-apps
jetty
crystal-reports-2013
frontend
nstableheaderview
lanczos
fabric.io
project
drop-down-menu
google-chrome-app
appcelerator-studio
siddhi
filechannel
php-5.6
stellar.js
supervisor
symmetricds
flatpak
capistrano3
red5
google-content-api
imessage
ag
squashfs
apktool
firebase-analytics
bioinformatics
browser-sync
nsurl
kudu
git-squash
code-snippets
card.io
baidu-map
amazon-ses
protein-database
filesystemwatcher
metaprogramming
c9.io
magento-1.9.3
android-softkeyboard
http-request
avcapturedevice
pom.xml
reportservice2010
zenhub
qtranslate
otp
payload
janus
rackspace-cloud
angular2-testing
meteor-packages
stax
omxplayer
expectations
udpclient
spreadjs
fuzzywuzzy
kendo-upload
jbase
sapi
opl
xenomai
computer-architecture
pax-exam
gamekit
public-html
rapidsvn
packet-sniffers
mruby
android-vibration
genymotion-call
trdion2011
personalization
tinyxml
paste
twitter-bootstrap-rails
cfcache
ice-cube
abstract-data-type
superscrollorama
redis-py
frameworkelementfactory
vfs
fusefabric
floating-point-exceptions
node-redis
ikimagebrowserview
update-statement
lr
drawtobitmap
dataform
unattended-processing
qglwidget
aspmenu
google-wave
dojo-dnd
wspbuilder

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App