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

Asset copy not completing
Read data from sqlitedatabase using date
Automatically Pairing A Bluetooth Remote to Android Tablet
Corona/Lua: unable to access table value after collision
HTML 5 local storage between app and browser
Adding Menu Items to jfeinstein10's SlidingMenu Library
relation between gradle version and gradle build tool version
How do I check if Android GPS is still scanning or position is fixed? not just check if enabled
requestFileSystem() in cordova not work on android app
Android - GraphView - ArrayList
android - upload pictures to dropbox
Android emulator (unfortunately app has stopped) [duplicate]
INSTALL_FAILED_DEXOPT when using GreenDao
Android get time of a call from CallLog
Prevent ADB output from showing in Android Studio
Video downloading issue in android

Categories

HOME
phpword
hyperlink
jmeter
wakanda
android-studio-2.2
components
sh
owl-carousel
sublimetext
google-cloud-functions
emscripten
3d-reconstruction
azure-container-service
fosrestbundle
endeca
watson-conversation
comsol
qsqlquery
aws-sdk
symfony-console
symbols
poedit
mongoid6
ms-access-web-app
google-cast
xbox
utorrent
record
r-grid
biztalk-rule-engine
searchkit
sql-server-ce
zoomify
xdocreport
connection-pool
protein-database
health-monitoring
typesafe-config
laravel-elixir
lpsolve
apache-directory
oim
flask-restful
openrasta
vugen
lightning
x-ray
podscms
page-replacement
boxing
payload
janus
flac
mathcad
django-1.10
pure-css
actor-platform
parfor
flex4.6
watch-os-2
ng-grid
dimension
jclouds
hadoop-partitioning
createprocess
fuzzywuzzy
nullable
grgit
java-money
avisynth
dllimport
lazybones
django-urls
poppler
opserver
typemock
baasbox
ansi
public-html
contrast
nsmenu
create.js
personalization
reflector
eclipse-kepler
neos-server
asdf
nevron
adobe-media-server
isa-swizzling
tournament
twitterizer
cloudfiles
zen
escrow
fdf

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