得到错误 - java.lang.UnsupportedOperationException

时间:2012-11-12 17:01:46

标签: android arrays string listview

我已经编写了一些代码来将数据从网页设置为listview。我已成功阅读网页,并在String数组中存储了必要的数据。现在我想使用ListView将其分配给ArrayAdapter,但数据未在listview中设置。请帮我解决错误:

完整日志CAT

11-07 23:41:40.150: E/AndroidRuntime(3400): FATAL EXCEPTION: main
11-07 23:41:40.150: E/AndroidRuntime(3400): java.lang.UnsupportedOperationException
11-07 23:41:40.150: E/AndroidRuntime(3400):     at java.util.AbstractList.add(AbstractList.java:411)
11-07 23:41:40.150: E/AndroidRuntime(3400):     at java.util.AbstractList.add(AbstractList.java:432)
11-07 23:41:40.150: E/AndroidRuntime(3400):     at android.widget.ArrayAdapter.add(ArrayAdapter.java:178)
11-07 23:41:40.150: E/AndroidRuntime(3400):     at com.air.test.Smscollection$sendMessageAsync.onPostExecute(Smscollection.java:91)
11-07 23:41:40.150: E/AndroidRuntime(3400):     at com.air.test.Smscollection$sendMessageAsync.onPostExecute(Smscollection.java:1)
11-07 23:41:40.150: E/AndroidRuntime(3400):     at android.os.AsyncTask.finish(AsyncTask.java:417)
11-07 23:41:40.150: E/AndroidRuntime(3400):     at android.os.AsyncTask.access$300(AsyncTask.java:127)
11-07 23:41:40.150: E/AndroidRuntime(3400):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
11-07 23:41:40.150: E/AndroidRuntime(3400):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-07 23:41:40.150: E/AndroidRuntime(3400):     at android.os.Looper.loop(Looper.java:130)
11-07 23:41:40.150: E/AndroidRuntime(3400):     at android.app.ActivityThread.main(ActivityThread.java:3683)
11-07 23:41:40.150: E/AndroidRuntime(3400):     at java.lang.reflect.Method.invokeNative(Native Method)
11-07 23:41:40.150: E/AndroidRuntime(3400):     at  java.lang.reflect.Method.invoke(Method.java:507)
11-07 23:41:40.150: E/AndroidRuntime(3400):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
11-07 23:41:40.150: E/AndroidRuntime(3400):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
11-07 23:41:40.150: E/AndroidRuntime(3400):     at dalvik.system.NativeStart.main(Native Method)

输出logcat以验证数据是否存储在String array

11-07 23:03:47.640: I/NEW VAUES(3192): Happiness is Like a Butterfly, You run after it, It keeps flying away. But if you stand still, It comes and Sits On You Wish you lots of Butterflies
11-07 23:03:47.640: I/NEW VAUES(3192): Happiness is Like a Butterfly, You run after it, It keeps flying away. But if you stand still, It comes and Sits On You Wish you lots of Butterfly
11-07 23:03:47.640: I/NEW VAUES(3192): Happiness is Like a Butterfly, You run after it, It keeps flying away. But if you stand still, It comes and Sits On You Wish you lots of Butterfies
11-07 23:03:47.640: I/NEW VAUES(3192): Happiness is Like a Butterfly, You run after it, It keeps flying away. But if you stand still, It comes and Sits On You Wish you lots of Butterfly
11-07 23:03:47.640: I/NEW VAUES(3192): Happiness is Like a Butterfly, You run after it, It keeps flying away. But if you stand still, It comes and Sits On You Wish you lots of Butterflies
11-07 23:03:47.640: I/VALUES(3192): Happiness is Like a Butterfly, You run after it, It keeps flying away. But if you stand still, It comes and Sits On You Wish you lots of Butterflies<br/>Happiness is Like a Butterfly, You run after it, It keeps flying away. But if you stand still, It comes and Sits On You Wish you lots of Butterfly<br/>Happiness is Like a Butterfly, You run after it, It keeps flying away. But if you stand still, It comes and Sits On You Wish you lots of Butterfies<br/>Happiness is Like a Butterfly, You run after it, It keeps flying away. But if you stand still, It comes and Sits On You Wish you lots of Butterfly<br/>Happiness is Like a Butterfly, You run after it, It keeps flying away. But if you stand still, It comes and Sits On You Wish you lots of Butterflies

CODE

public class Smscollection extends Activity {

private Spinner spinner1;
private ProgressDialog pd;
private StringBuilder response;
private ListView listView;
private String[] values = new String[0];
private ArrayAdapter<String> adapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_smscollection);
    listView = (ListView) findViewById(R.id.mylist);
    spinner1 = (Spinner) findViewById(R.id.spinnerCategory);
    spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {

        public void onItemSelected(AdapterView<?> av, View view, int id,
                long ids) {
            new sendMessageAsync().execute();
        }

        public void onNothingSelected(AdapterView<?> av) {
        }
    });

    adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, android.R.id.text1, values);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_smscollection, menu);
    return true;
}

private class sendMessageAsync extends AsyncTask<Void, Void, String> {

    @Override
    protected void onPreExecute() {
        pd = ProgressDialog.show(Smscollection.this, null, "Loading...",
                true, true);
    }

    @Override
    protected void onCancelled() {
        Toast.makeText(getApplicationContext(),
                "Message Sending Cancelled", Toast.LENGTH_LONG).show();
    }

    @Override
    protected String doInBackground(Void... arg0) {
        try {
            return doInBg();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        pd.dismiss();
        if (result == null) {
            // request failed!
            // return;
        }
        values = String.valueOf(result).split("<br/>");
        adapter.clear();
        for (String str : values) {
            adapter.add(str);
        }
        adapter.notifyDataSetChanged();
        listView.setAdapter(adapter);
    }
}

public String doInBg() {
    String responseRes = null;
    try {
        final String msgURL = "http://freesmsit.tk/msg/messages.php?category="
                + String.valueOf(spinner1.getSelectedItem().toString()
                        .replace(" ", "%20"));
        URLConnection connection = new URL(msgURL).openConnection();
        connection.setRequestProperty("Accept-Charset", "UTF-8");
        InputStream responseStream = connection.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(responseStream));
        response = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            response.append(line);
        }
        responseRes = response.toString();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return responseRes;
}
}

3 个答案:

答案 0 :(得分:4)

如果您使用array作为ArrayAdapter的数据,该数组将转换为特殊的ArrayList(不是平台中的正常数组),但尚未实现addremove方法(您只能修改该列表中已存在的项目)。因此,当您尝试使用方法add向适配器添加项目时,应用程序将失败,并显示您看到的异常。

解决方案是将values中使用的ArrayAdapter数组替换为List,例如ArrayList(正常的)。

private ArrayList<String> values = new ArrayList<String>();

然后修改其余代码以使用列表而不是数组。

答案 1 :(得分:0)

这应该有效:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, values);

    listView.setAdapter(adapter);

答案 2 :(得分:0)

您正在使用适配器非通用数组 - String []

涉及通用List接口方法(add,remove,clear)的适配器上的任何操作都将失败**

private String[] values = new String[0];

adapter = new ArrayAdapter<String>(this,
        android.R.layout.simple_list_item_1, android.R.id.text1, values);

这样:

解决方案1:

  • 在代码中使用Arrays.asList([]):

    adapter = new ArrayAdapter<String>(this,
        android.R.layout.simple_list_item_1, android.R.id.text1, Arrays.asList(values));
    

解决方案2:

  • 使用新数组初始化(构造函数):

    List<String> valuesAsArray = newArrayList<String>(values);
    

解决方案3:

  • 声明你的&#34;值变量&#34;作为变量实现List接口

    List<String> values = new ArrayList<>();