错误java.lang.String无法强制转换为java.lang.Integer

时间:2017-01-16 17:57:07

标签: java android arraylist

即使在研究互联网上的类似错误之后,我仍然无法理解错误 我创建一个整数的ArrayList,然后只是尝试用.get()读取它,得到错误Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer,即使我没有使用任何字符串与这个ArrayList。

以下是代码的一部分:

package com.example.reixa.todolist;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

public class ListActivity extends Activity {

LinearLayout        linearList;
CheckBox            checkBox;
ArrayList<String>   checkList= new ArrayList<>();
ArrayList<Integer>  checkState = new ArrayList<>();
Bundle              bundle;
String              stuff;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_list);
    readItems();
    linearList = (LinearLayout) findViewById(R.id.linear_list);
    bundle = getIntent().getExtras();
    stuff = bundle.getString("name");

    for (int i = 0; i < checkList.size(); i++)
    {
        checkBox = new CheckBox(this);
        checkBox.setId(i);
        checkBox.setText(checkList.get(i));
        checkBox.setOnClickListener(getOnClickSomething(checkBox));
        linearList.addView(checkBox);
        if (checkState.get(i) == 0)  // error here
            checkBox.setChecked(!checkBox.isChecked());

    }
}

public void onAddItem(View v) {
    EditText etNewItem = (EditText) findViewById(R.id.etNewItem);
    String itemText = etNewItem.getText().toString();
    checkList.add(itemText);
    checkState.add(0);
    etNewItem.setText("");
    writeItems();

    checkBox = new CheckBox(this);
    checkBox.setId(checkList.size());
    checkBox.setText(itemText);
    checkBox.setOnClickListener(getOnClickSomething(checkBox));
    linearList.addView(checkBox);
}

View.OnClickListener getOnClickSomething(final Button button) {
    return new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Log.d("ON CLICK", "CheckBox ID: " + button.getId() + " Text: " + button.getText().toString());
            if (checkState.get(button.getId()) == 0)
                checkState.set(button.getId(), 1);
            else
                checkState.set(button.getId(), 0);
        }
    };
}

private void readItems() {
    File filesDir = getFilesDir();

    bundle = getIntent().getExtras();
    stuff = bundle.getString("name");

    File todoFile = new File(filesDir, stuff);
    try {
        checkList = new ArrayList<>(FileUtils.readLines(todoFile));
        checkState = new ArrayList<>(FileUtils.readLines(todoFile));
    } catch (IOException e) {
        checkList = new ArrayList<>();
        checkState = new ArrayList<>();
    }
}

private void writeItems() {
    File filesDir = getFilesDir();
    bundle = getIntent().getExtras();
    stuff = bundle.getString("name");

    File todoFile = new File(filesDir, stuff);
    try {
        FileUtils.writeLines(todoFile, checkList);
        FileUtils.writeLines(todoFile, checkState);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
}

有问题的ArrayList是checkState,错误发生的行是if (checkState.get(i) == 0)

3 个答案:

答案 0 :(得分:0)

你的问题就在这里

checkState = new ArrayList<>(FileUtils.readLines(todoFile));

readLines()返回List<String> 其中checkState的类型为List<Integer>,因此为ClassCastException。

答案 1 :(得分:0)

如果您收到此异常,则意味着您已将#pragma once #define _WINSOCK_DEPRECATED_NO_WARNINGS #pragma comment (lib,"ws2_32.lib") #include <WinSock2.h> #include <WS2tcpip.h> #include <string> #include <iostream> SOCKET NewConnection; bool ListenForConnection(int PORT, std::string IP) { WSADATA wsadata; int wsa_error = WSAStartup(0x0202, &wsadata); if (wsa_error) { std::cerr << WSAGetLastError() << std::endl; return false; } if (wsadata.wVersion != 0x0202) { std::cerr << WSAGetLastError() << std::endl; WSACleanup(); return false; } SOCKADDR_IN IncomingClient; IncomingClient.sin_family = AF_INET; IncomingClient.sin_port = htons(PORT); inet_pton(AF_INET, IP.c_str(), &(IncomingClient)); NewConnection = socket(AF_INET, SOCK_STREAM, NULL); if (NewConnection == INVALID_SOCKET) { std::cerr << "Error: " << NewConnection << std::endl; return false; } if (bind(NewConnection, (LPSOCKADDR)&IncomingClient, sizeof(IncomingClient) == SOCKET_ERROR)) { std::cerr << "Error: SOCKET_ERROR (-1)" << std::endl; return false; } listen(NewConnection, SOMAXCONN); } int main() { int PORT = 1337; std::string IP = "0.0.0.0"; ListenForConnection(PORT, IP); system("pause"); return 0; } 加载到String ArrayList,并根据您当前的代码,最可疑的部分是方法{{1在其中加载checkState作为下一个:

readItems

知道你以完全相同的方式初始化checkState // Here is your problem, you load it using String instead of Integer checkState = new ArrayList<>(FileUtils.readLines(todoFile)); checkList,很明显其中一个列表会包含错误类型的对象。

答案 2 :(得分:-2)

您将checkList声明为String数组。您无法使用==检查String是否等于整数(或int)。如果要比较它们,您需要将String转换为int,或将int转换为字符串。

如果checkList包含String格式的数字,则可以执行此操作。

if(Integer.parseInt(checkState.get(0)) == 0)

或者,如果它确实是一个字符串,那么你可以这样做

if(checkState.get(0).equals("0"))

或者,如果你真的想检查列表大小,你可以这样做

if(checkState.size() == 0)