1

I have written some code to set data to listview from a webpage. I have read the webpage successfully and stored necessary data in String array. Now i want to assign that to ListView using ArrayAdapter but the data is not getting set in listview. Please help me solve the error:

FULL LOG 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)

Output of logcat so as to verify that data is being stored in 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
  • How about posting the logcat for the exception itself? That would be more useful. Commented Nov 12, 2012 at 17:05
  • @TedHopp i have added the full log cat output Commented Nov 12, 2012 at 17:15
  • funny, this should work as ArrayAdapter is supposed to provide an actual List when you pass an array. I would create a new Adapter rather than clearing and adding new items. Commented Nov 12, 2012 at 17:27

3 Answers 3

4

If you use an array as the data for an ArrayAdapter that array will be transformed into a special ArrayList(not the normal one from the platform) which doesn't have implemented the add and remove methods(you can only modify the items already present in that list). So, when you'll try to add items to the adapter with the method add the app will fail with the exception you see.

The solution is to replace the values array that you use in the ArrayAdapter with a List, like an ArrayList(the normal one).

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

and then modify the rest of your code to use the list instead of an array.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much... you made my day, or let say "night"!
0

This should work:

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

    listView.setAdapter(adapter);

4 Comments

what is items here? because in my code i dont have anything whose object name is items
Most of this stuff is here.
@SwiftAppDesign i have successfully created a listview using array with static values. but now i want to assign dynamic values by reading the webpage. this is where i am facing the problem
@SwiftAppDesign please refer my whole code. i think you will get a better idea about what am i trying to do
0

You are using on adapter non generic array - String[]

any operation on adapter involving generic List interface methods (add, remove, clear) will fail**

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

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

so:

solution 1:

  • using Arrays.asList([]) in code:

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

solution 2:

  • using new array initialization (constructor):

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

solution 3:

  • declare your "values variable" as variable implementing List interface

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.