1

I have written a piece of code, to get some information through the website and display it in a ListView. I am not able to configure why i am getting the force close error. I am pasting the log cat along with the code. Please help me find and solve the error

11-07 21:43:14.729: E/AndroidRuntime(2799): FATAL EXCEPTION: main
11-07 21:43:14.729: E/AndroidRuntime(2799): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.air.test/com.air.test.MainActivity}: java.lang.NullPointerException
11-07 21:43:14.729: E/AndroidRuntime(2799):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
11-07 21:43:14.729: E/AndroidRuntime(2799):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
11-07 21:43:14.729: E/AndroidRuntime(2799):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
11-07 21:43:14.729: E/AndroidRuntime(2799):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
11-07 21:43:14.729: E/AndroidRuntime(2799):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-07 21:43:14.729: E/AndroidRuntime(2799):     at android.os.Looper.loop(Looper.java:130)
11-07 21:43:14.729: E/AndroidRuntime(2799):     at android.app.ActivityThread.main(ActivityThread.java:3683)
11-07 21:43:14.729: E/AndroidRuntime(2799):     at java.lang.reflect.Method.invokeNative(Native Method)
11-07 21:43:14.729: E/AndroidRuntime(2799):     at java.lang.reflect.Method.invoke(Method.java:507)
11-07 21:43:14.729: E/AndroidRuntime(2799):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
11-07 21:43:14.729: E/AndroidRuntime(2799):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
11-07 21:43:14.729: E/AndroidRuntime(2799):     at dalvik.system.NativeStart.main(Native Method)
11-07 21:43:14.729: E/AndroidRuntime(2799): Caused by: java.lang.NullPointerException
11-07 21:43:14.729: E/AndroidRuntime(2799):     at java.util.Arrays$ArrayList.<init>(Arrays.java:47)
11-07 21:43:14.729: E/AndroidRuntime(2799):     at java.util.Arrays.asList(Arrays.java:169)
11-07 21:43:14.729: E/AndroidRuntime(2799):     at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:138)
11-07 21:43:14.729: E/AndroidRuntime(2799):     at com.air.test.MainActivity.onCreate(MainActivity.java:59)
11-07 21:43:14.729: E/AndroidRuntime(2799):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-07 21:43:14.729: E/AndroidRuntime(2799):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
11-07 21:43:14.729: E/AndroidRuntime(2799):     ... 11 more

Code

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

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    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);

    listView.setAdapter(adapter);
}

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

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

    @Override
    protected void onPreExecute() {
        pd = ProgressDialog.show(MainActivity.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 {
            doInBg();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        pd.dismiss();
    }
}

public void doInBg() {
    try {
        final String msgURL = "http://example.com/message?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);
        }
        values = String.valueOf(response).split("<br/>");
        adapter.notifyDataSetChanged();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
2
  • this String.valueOf(spinner1.getSelectedItem().toString() .replace(" ", "%20")); causing problem because ui elements is not accessible in doInBackground Commented Nov 12, 2012 at 14:43
  • @imrankhan thats not the problem at all. because the code was running perfectly when i assigned static value to values Commented Nov 12, 2012 at 14:45

2 Answers 2

4

When this line is run, values is null.

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

To solve this, initialize values before that line.

values = new String[0];

Or, if you want it to contain something:

values = new String[]{ "Value 1", "Value 2" };

EDIT:

Having checked your AsyncTask implementation, here's what I would do:

I would first of all initialize the value using this code:

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

Secondly, I would get rid of your values String array as a class property. (Delete the line private String[] values;)

Thirdly, I would change the AsyncTask to <Void, String, Void>.

Fourthly, assuming that this code would give you the correct result:

values = String.valueOf(response).split("<br/>");

Here I would replace that line with:

String[] values = String.valueOf(response).split("<br/>");
for (String str : values) publishProgress(str);

And then, in your AsyncTask, have this method:

@Override
protected void onProgressUpdate(String... values) {
    adapter.add(values[0]);
}

I hope that works for you.

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

4 Comments

I want the values to be added dynamically from the website. Therefore i have used this code values = String.valueOf(response).split("<br/>");
@TapanDesai I have edited my answer to something I think should work with your AsyncTask.
Thanks for the reply and sorry if i am wrong but did you forget to complete this step in your answer? Thirdly, I would change the AsyncTask to .
@TapanDesai Sorry about that, it was interpreted as an HTML tag I guess, it should say <Void, String, Void>.
3

You need to set your String array values before attempting to create the adapter.

This line will fail because values is null:

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

3 Comments

I am doing that using AsyncTask to assign value to values
Then you will need to set an initial value (i.e. an empty array) and then make sure you're properly synchronizing the variable if you're setting it from the doInBackground() method.
Change the declaration to: private String[] values = new String[0];

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.