为什么添加listView显示数据后app崩溃

Why app crashes after listView is added to display data

这个问题是我之前 post 的后续问题(link 如下所示)。我已经成功地扫描了 RFID 标签,然后将这些标签存储在一个集合中,因此不会输入重复项。但是,当我随后尝试使用 listView 显示它时,会产生运行时错误。完整代码如下所示。

public class MainActivity extends AppCompatActivity {

  private Set<String> epc = new HashSet<>();

  private TextView textView;

  ListView listView;
  ArrayAdapter<String> contactAdapter;

  public void multipleRead(View view)
  {
    try {
    // Get global RFID Reader instance
        RFIDReader reader = RFID.open();

        reader.inventory(new RFIDCallback() {
                             @Override
                             public void onTagRead(Tag tag) {
                                 epc.add(tag.getEPC());
                             }
                         }
        );

    }
    catch (ReaderException e) {
        Toast.makeText(this, "Error: " + e, Toast.LENGTH_LONG).show();
    }
  }

  public void display()
  {
    contactAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, 
                     (List<String>) epc);
    listView.setAdapter(contactAdapter);
    //runOnUiThread(new Runnable() { public void run() { textView.append(set + "\n"); }});
  }

  public void stopRead(View v)
  {
    try {
        // Get global RFID Reader instance

        RFIDReader reader = RFID.open();
        reader.stop();
        reader.close();
        display();
    }
    catch (ReaderException e) {
        Toast.makeText(this, "Error: " + e, Toast.LENGTH_LONG).show();
    }
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    textView = (TextView)findViewById(R.id.tag_id);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
  }
}

后续question。产生的运行时错误是:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.myapplication, PID: 3908
java.lang.IllegalStateException: Could not execute method for android:onClick

at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:4463)
at android.view.View$PerformClick.run(View.java:18770)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5292)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4463) 
at android.view.View$PerformClick.run(View.java:18770) 
at android.os.Handler.handleCallback(Handler.java:808) 
at android.os.Handler.dispatchMessage(Handler.java:103) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:5292) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640) 
at dalvik.system.NativeStart.main(Native Method) 
Caused by: java.lang.ClassCastException: java.util.HashSet cannot be cast to java.util.List
at com.example.user.myapplication.MainActivity.display(MainActivity.java:106)
at com.example.user.myapplication.MainActivity.stopRead(MainActivity.java:121)
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:4463) 
at android.view.View$PerformClick.run(View.java:18770) 
at android.os.Handler.handleCallback(Handler.java:808) 
at android.os.Handler.dispatchMessage(Handler.java:103) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:5292) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640) 
at dalvik.system.NativeStart.main(Native Method) 

我该如何解决这个问题?

这个错误是我包含这段代码后造成的:

 contactAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, 
                     (List<String>) epc);
 listView.setAdapter(contactAdapter);

您不能简单地将 Set 转换为 List,您必须将其转换为:

(java 8)

 contactAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, 
    epc.stream().collect(Collectors.toCollection(ArrayList::new));

旧版本:

 contactAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, new ArrayList<>(epc));

但我建议改为java8或更高。