Search code examples
javaandroidandroid-viewpager

What am I doing wrong that is causing this error with a custom viewpager in Android?


After looking at various tuts and SO questions, I'm pretty sure I know how to display limited results within a viewpager from a remote database. Yet when I run the app, I get the following error. I've checked the url through a browser with no errors so I know it can't be null so I'm confused and not sure where this is going wrong. The PHP code limits the results to the last 5 rows in the database in desc order.

LogCat

Process: com.curtrostudios.custompagertest, PID: 22057 java.lang.NullPointerException at com.curtrostudios.custompagertest.MainActivity$2.onResponse(MainActivity.java:59) at com.curtrostudios.custompagertest.MainActivity$2.onResponse(MainActivity.java:50) at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65) at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99) at android.os.Handler.handleCallback(Handler.java:733) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5072) 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:786) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602) at dalvik.system.NativeStart.main(Native Method)

Main Activity

    public class MainActivity extends AppCompatActivity {
    private ViewPager pageView;
    private String TAG = "Featured View";
    private String FEAT_URL = "http://localhost/testing/featured.php";
    private ArrayList<FeaturedModel> fdata;
    private FeaturedAdapter featAdapt;

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

        pageView = (ViewPager)findViewById(R.id.featuredView);

        JsonArrayRequest request = new JsonArrayRequest(FEAT_URL,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString()); try {
                            for(int i=0;i<response.length();i++){
                                String pid=response.getJSONObject(i).getString("pid");
                                String name=response.getJSONObject(i).getString("prod_name");
                                String img = response.getJSONObject(i).getString("prod_pic");

                                fdata.add(new FeaturedModel(pid, name, img));
                            }
                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        featAdapt=new FeaturedAdapter(MainActivity.this, fdata);
                        pageView.setAdapter(featAdapt);
                        //dialog.dismiss();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d(TAG, "Error: " + error.getMessage());
                //dialog.dismiss();
            }
        });

        VolleyController.getInstance().addToRequestQueue(request, TAG);





    }

    @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);
    }
}

Data Model

    public class FeaturedModel {
    private String pid;
    private String prod_name;
    private String prod_pic;

    public FeaturedModel(String pid,String prod_name,String prod_pic){
        this.pid=pid;
        this.prod_name=prod_name;
        this.prod_pic=prod_pic;

    }

    public String getPID(){
        return pid;

    }
    public String getName(){
        return prod_name;

    }
    public String getImageURL(){
        return prod_pic;
    }


}

Pager Adapter

    public class FeaturedAdapter extends PagerAdapter {
    private ArrayList<FeaturedModel> feature;
    private Context context;
    private static LayoutInflater inflater = null;

    public FeaturedAdapter(MainActivity mainActivity, ArrayList<FeaturedModel> data) {

        feature=data;
        context=mainActivity;

        inflater = ( LayoutInflater )context.
                getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return feature.size();
    }

    public class Holder
    {
        TextView ftitle;
        NetworkImageView fimg;

    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {

        Holder holder = new Holder();
        View rowView;
        rowView = inflater.inflate(R.layout.feature_row, null);
        holder.ftitle=(TextView) rowView.findViewById(R.id.featTitle);
        holder.fimg=(NetworkImageView)rowView.findViewById(R.id.featImg);
        holder.ftitle.setText(feature.get(position).getName());

        // If you are using NetworkImageView
        holder.fimg.setImageUrl(feature.get(position).getImageURL(), VolleyController.getInstance().getImageLoader());


        container.addView(rowView);
        return rowView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((RelativeLayout)object);
    }

}

Result from browser

    [
    {
        "pid": "45",
        "prod_name": "Product 45",
        "prod_pic": "http://localhost/images/testone.png",
        "prod_desc": "some description",

    },
    {
        "pid": "44",
        "prod_name": "Product 44",
        "prod_pic": "http://localhost/images/testtwo.png",
        "prod_desc": "some description",

    },
    {
        "pid": "43",
        "prod_name": "Product 43",
        "prod_pic": "http://localhost/images/testone.png",
        "prod_desc": "some description",

    },
    {
        "pid": "42",
        "prod_name": "Product 42",
        "prod_pic": "http://localhost/images/testtwo.png",
        "prod_desc": "some description",

    },
    {
        "pid": "41",
        "prod_name": "Product 41",
        "prod_pic": "http://localhost/images/testone.png",
        "prod_desc": "some description",

    }
]

Solution

  • Your ArrayList fdata is not initialized. Call fdata = new ArrayList<>(); before adding/selecting items from it.