-6

I created a layout named activity_category and activity named CategoryActivity the code of which is as follows

public class CategoryActivity extends Activity {
    private LazyItemLoadAdapter adapter;
    private int[] selectionId;
    private Item[] item_data;
    private GridView grid;
    private TextView textview;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.activity_category);

        ActionBarUtils.setActionBar(this);
        String id=getIntent().getExtras().getString("id");

        try{
            AsyncData data=new AsyncData();
            data.execute(Constants.SERVER+"cat_adlist.php?id="+id);

            grid = (GridView) findViewById(R.id.gridViewAllItems);
        }catch(NotFoundException n){

        }
    }

    private class AsyncData extends AsyncTask<String, Void, Item[]>{

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            setProgressBarIndeterminateVisibility(true);
        }

        @Override
        protected Item[] doInBackground(String... params) {
            String str=null;
            try {
                str = CustomHttpClient
                        .executeHttpGet(params[0]);
                Log.i("Category Data", str);
                JSONArray array = new JSONArray(str);
                item_data = new Item[array.length()];
                selectionId = new int[array.length()];

                for (int i = 0; i < item_data.length; i++) {
                    JSONObject jdata = array.getJSONObject(i);
                    String path = Constants.THUMBS
                            + jdata.getString("name");
                    int itemid = jdata.getInt("id");
                    item_data[i] = new Item(itemid, path, jdata.getString("title"),
                            jdata.getString("price"));
                    selectionId[i] = jdata.getInt("subcategory_id");// change the
                                                                    // field name
                                                                    // here
                }

            }catch(JSONException j){

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return item_data;
        }

        @Override
        protected void onPostExecute(Item[] result) {

            adapter = new LazyItemLoadAdapter(CategoryActivity.this, R.layout.text_below_images, result);

            grid.setAdapter(adapter);
            if (result.length == 0) {
                grid.setVisibility(View.GONE);
                textview.setVisibility(View.VISIBLE);
            } else {
                grid.setVisibility(View.VISIBLE);
                textview.setVisibility(View.GONE);
            }
            TextView numResults=(TextView) findViewById(R.id.textView2);
            numResults.setText("Found "+String.valueOf(result.length)+" results");
            setProgressBarIndeterminateVisibility(false);
            super.onPostExecute(result);
        }

    }
}

The logcat is as follows -

05-07 17:09:58.340: E/AndroidRuntime(2242): FATAL EXCEPTION: main
05-07 17:09:58.340: E/AndroidRuntime(2242): Process: com.opaxlabs.salepurchase, PID: 2242
05-07 17:09:58.340: E/AndroidRuntime(2242): java.lang.NullPointerException
05-07 17:09:58.340: E/AndroidRuntime(2242):     at com.opaxlabs.salepurchase.CategoryActivity$AsyncData.onPostExecute(CategoryActivity.java:115)
05-07 17:09:58.340: E/AndroidRuntime(2242):     at com.opaxlabs.salepurchase.CategoryActivity$AsyncData.onPostExecute(CategoryActivity.java:1)
05-07 17:09:58.340: E/AndroidRuntime(2242):     at android.os.AsyncTask.finish(AsyncTask.java:632)
05-07 17:09:58.340: E/AndroidRuntime(2242):     at android.os.AsyncTask.access$600(AsyncTask.java:177)
05-07 17:09:58.340: E/AndroidRuntime(2242):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
05-07 17:09:58.340: E/AndroidRuntime(2242):     at android.os.Handler.dispatchMessage(Handler.java:102)
05-07 17:09:58.340: E/AndroidRuntime(2242):     at android.os.Looper.loop(Looper.java:136)
05-07 17:09:58.340: E/AndroidRuntime(2242):     at android.app.ActivityThread.main(ActivityThread.java:5017)
05-07 17:09:58.340: E/AndroidRuntime(2242):     at java.lang.reflect.Method.invokeNative(Native Method)
05-07 17:09:58.340: E/AndroidRuntime(2242):     at java.lang.reflect.Method.invoke(Method.java:515)
05-07 17:09:58.340: E/AndroidRuntime(2242):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-07 17:09:58.340: E/AndroidRuntime(2242):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-07 17:09:58.340: E/AndroidRuntime(2242):     at dalvik.system.NativeStart.main(Native Method)

As you can see I am getting a null pointer exception. initially it was because I was using a wrong layout but I have corrected that but the problem persists. Please help me with your suggestions. Thanks in advance.

Sanket Kachhela
  • 10,861
  • 8
  • 50
  • 75
Pankaj Agarwal
  • 117
  • 1
  • 16
  • Which one is line 115 ? – Sanjeev May 07 '14 at 12:03
  • Write the Following line grid = (GridView) findViewById(R.id.gridViewAllItems); before executing Async task – Usman Kurd May 07 '14 at 12:08
  • Which line in your code is the line 115 (where there is a problem; aka a NULL element). And several points: you run your AsynTask before initializing the grid variable; does R.layout.text_below_images exist?; ... – grattmandu03 May 07 '14 at 12:08
  • You need to learn how to debug your application. When a NullPointerException is raised at a specific line, it means that one element on this line is never initialized. Have a look at the link provided by Mat. – grattmandu03 May 07 '14 at 12:14
  • line 115 is out of range. There is no line 115. There are only 105 lines in the code. – Pankaj Agarwal May 07 '14 at 12:17

2 Answers2

2

You forget to initialize your TextView textview which is in your onPostExecute method.

     @Override
    protected void onPostExecute(Item[] result) {

           TextView textview =(TextView) findViewById(R.id.textView2);
        adapter = new LazyItemLoadAdapter(CategoryActivity.this, R.layout.text_below_images, result);

        grid.setAdapter(adapter);
        if (result.length == 0) {
            grid.setVisibility(View.GONE);
            textview.setVisibility(View.VISIBLE); 
        } else {
            grid.setVisibility(View.VISIBLE);
            textview.setVisibility(View.GONE);
        }
       TextView numResults=(TextView) findViewById(R.id.textView2);
        numResults.setText("Found "+String.valueOf(result.length)+" results");
        setProgressBarIndeterminateVisibility(false);
        super.onPostExecute(result);
    }
GrIsHu
  • 29,068
  • 10
  • 64
  • 102
  • 1
    GridView is initialised, but the TextView which he is using is not: `textview.setVisibility(View.VISIBLE);` – hardartcore May 07 '14 at 12:09
  • Indeed textview was not initialized. Initializing it solved the problem. @Android-Developer can you post your reply so I can select it as correct answer? – Pankaj Agarwal May 07 '14 at 12:26
  • @Pankaj TextView was initialized but it was in `onPostExecute` it was unable to get the `TextView` because it was initialized after the `if` loop in your `onPostExecute` method. – GrIsHu May 07 '14 at 12:33
  • @GrIsHu actually there were two textviews. One as you said was initialized after if block and the other which was in the if block was never initialized. Thanks anyway. – Pankaj Agarwal May 07 '14 at 12:37
  • @Pankaj Thats what the mistake. I have mentioned that its always better to initialize all your views in `onCreate` – GrIsHu May 07 '14 at 12:41
1

First of all the best practice which I think you should follow is to organise your code in blocks. Initialise all your views after setContentView() no matter when you are using them. If you start doing this you won't have exceptions thrown like this one which you have.

The problem in your code is that you are not initialising your textView variable and using it in your onPostExecute() method of AsyncTask. Your onCreate should look like this:

@Override
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.activity_category);

        grid = (GridView) findViewById(R.id.gridViewAllItems);
        textview = (TextView) findViewById(R.id.myTextView);
        numResults = (TextView) findViewById(R.id.textView2);

        // Start your AsyncTask here ...

}
hardartcore
  • 16,886
  • 12
  • 75
  • 101