0

i want show items with images which comes from the server into my ListView but am getting exception...i have added volly also in my dependencies but dont know why its not coming.. here is my SubMenu Activity

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;



import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.*;
import com.android.volley.toolbox.JsonArrayRequest;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


public class SubMenu  extends AppCompatActivity {


    // Log tag
    private static final String TAG = SubMenu.class.getSimpleName();

    // Movies json url
    private static final String url = "http://cloud.granddubai.com/broccoli/menu_typeitem.php";
    private ProgressDialog pDialog;
    private List<Movie> movieList = new ArrayList<Movie>();
    private ListView listView;
    private CustomListAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sub_menu);

        listView = (ListView) findViewById(R.id.list1);
        adapter = new CustomListAdapter(this, movieList);
        listView.setAdapter(adapter);

        pDialog = new ProgressDialog(this);
        // Showing progress dialog before making http request
        pDialog.setMessage("Loading...");
        pDialog.show();

        // changing action bar color
        getActionBar().setBackgroundDrawable(
                new ColorDrawable(Color.parseColor("#1b1b1b")));

        // Creating volley request obj
        JsonArrayRequest movieReq = new JsonArrayRequest(url,
                new com.android.volley.Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        hidePDialog();

                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {

                                JSONObject obj = response.getJSONObject(i);
                                Movie movie = new Movie();
                                movie.setTitle(obj.getString("name"));
                                movie.setThumbnailUrl(obj.getString("image"));
                                //  movie.setRating(((Number) obj.get("rating"))
                                //      .doubleValue());
                                //movie.setYear(obj.getInt("releaseYear"));

                                // Genre is json array
                                JSONArray genreArry = obj.getJSONArray("genre");
                                ArrayList<String> genre = new ArrayList<String>();
                                for (int j = 0; j < genreArry.length(); j++) {
                                    genre.add((String) genreArry.get(j));
                                }
                                //  movie.setGenre(genre);

                                // adding movie to movies array
                                movieList.add(movie);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }

                        // notifying list adapter about data changes
                        // so that it renders the list view with updated data
                        adapter.notifyDataSetChanged();
                    }
                }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hidePDialog();

            }
        });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(movieReq);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hidePDialog();
    }

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }

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

}

here is my Movie.java class

 import java.util.ArrayList;

public class Movie {
    private String title, thumbnailUrl;

    private double rating;
    private ArrayList<String> genre;

    public Movie() {
    }


    public Movie(String name, String thumbnailUrl, int year, double rating,
                 ArrayList<String> genre) {
        this.title = name;
        this.thumbnailUrl = thumbnailUrl;
        //this.year = year;
    //  this.rating = rating;
        //this.genre = genre;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String name) {
        this.title = name;
    }

    public String getThumbnailUrl() {
        return thumbnailUrl;
    }

    public void setThumbnailUrl(String thumbnailUrl) {
        this.thumbnailUrl = thumbnailUrl;
    }

//  public int getYear() {return year;}

//  public void setYear(int year) {
    //  this.year = year;
    //}

//  public double getRating() {
    //  return rating;
    //}

//  public void setRating(double rating) {
    //  this.rating = rating;
    //}

    //public ArrayList<String> getGenre() {
        //return genre;
    //}

//  public void setGenre(ArrayList<String> genre) {
        //this.genre = genre;
    //}

}

here is my CustomListAdapter

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;

import java.util.List;

//import info.androidhive.customlistviewvolley.app.AppController;
//import info.androidhive.customlistviewvolley.model.Movie;

public class CustomListAdapter extends BaseAdapter {
    private Activity activity;
    private LayoutInflater inflater;
    private List<Movie> movieItems;
    ImageLoader imageLoader = AppController.getInstance().getImageLoader();

    public CustomListAdapter(Activity activity, List<Movie> movieItems) {
        this.activity = activity;
        this.movieItems = movieItems;
    }

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

    @Override
    public Object getItem(int location) {
        return movieItems.get(location);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (inflater == null)
            inflater = (LayoutInflater) activity
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null)
            convertView = inflater.inflate(R.layout.list_item1, null);

        if (imageLoader == null)
            imageLoader = AppController.getInstance().getImageLoader();
        NetworkImageView thumbNail = (NetworkImageView) convertView
                .findViewById(R.id.imgs);
        TextView title = (TextView) convertView.findViewById(R.id.type1);
        //TextView rating = (TextView) convertView.findViewById(R.id.rating);
        //TextView genre = (TextView) convertView.findViewById(R.id.genre);
        //TextView year = (TextView) convertView.findViewById(R.id.releaseYear);

        // getting movie data for the row
        Movie m = movieItems.get(position);

        // thumbnail image
        thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);

        // title
        title.setText(m.getTitle());

        // rating
        //rating.setText("Rating: " + String.valueOf(m.getRating()));

        // genre
        //String genreStr = "";
        //for (String str : m.getGenre()) {
        //  genreStr += str + ", ";
    //  }
    //  genreStr = genreStr.length() > 0 ? genreStr.substring(0,
        //      genreStr.length() - 2) : genreStr;
        //genre.setText(genreStr);

        // release year
    //  year.setText(String.valueOf(m.getYear()));

        return convertView;
    }

}

Here is my AppController.java

import android.app.Application;
import android.text.TextUtils;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

public class AppController extends Application {

    public static final String TAG = AppController.class.getSimpleName();

    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;

    private static AppController mInstance;

    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized AppController getInstance() {
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    public ImageLoader getImageLoader() {
        getRequestQueue();
        if (mImageLoader == null) {
            mImageLoader = new ImageLoader(this.mRequestQueue,
                    new LruBitmapCache());
        }
        return this.mImageLoader;
    }

    public <T> void addToRequestQueue(Request<T> req, String tag) {
        // set the default tag if tag is empty
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }

    public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}

one more thing i am unable to Import this two into my project

//import info.androidhive.customlistviewvolley.app.AppController;
//import info.androidhive.customlistviewvolley.model.Movie;

this is my list_item1.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    >

    <!-- Product id (pid) - will be DDEN - used to pass to other activity -->


    <com.android.volley.toolbox.NetworkImageView
        android:id="@+id/imgs"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <TextView
            android:id="@+id/idq"
            android:layout_width="30dp"
            android:layout_height="30dp"/>

        <TextView
            android:id="@+id/type1"
            android:textSize="20dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

    </LinearLayout>

here is my json response from postmant

[
  {
    "id": "1",
    "name": "Bianca Pizza",
    "image": "http://cloud.granddubai.com/broccoli/uploads/"
  },
  {
    "id": "2",
    "name": "Cheese Pizza",
    "image": "http://cloud.granddubai.com/broccoli/uploads/Cheese.png"
  },
  {
    "id": "3",
    "name": "Chicken BBQ Pizza:",
    "image": "http://cloud.granddubai.com/broccoli/uploads/Chicken BBQ.png"
  },
  {
    "id": "4",
    "name": "Deluxe Pizza",
    "image": "http://cloud.granddubai.com/broccoli/uploads/Deluxe.png"
  },
  {
    "id": "5",
    "name": "Greek Pizza",
    "image": "http://cloud.granddubai.com/broccoli/uploads/Greek.png"
  },
  {
    "id": "6",
    "name": "Hawaiian Pizza",
    "image": "http://cloud.granddubai.com/broccoli/uploads/Hawaiian.png"
  },
  {
    "id": "7",
    "name": "Meat Lovers Pizza",
    "image": "http://cloud.granddubai.com/broccoli/uploads/Meat Lovers.png"
  },
  {
    "id": "8",
    "name": "Pepperoni Pizza",
    "image": ""
  },
  {
    "id": "9",
    "name": "Shrimp Pizza",
    "image": ""
  },
  {
    "id": "10",
    "name": "Vegetable Pizza",
    "image": ""
  },
  {
    "id": "11",
    "name": "Original Italian Pizza",
    "image": ""
  },
  {
    "id": "12",
    "name": "Beef Strips Pasta",
    "image": ""
  },
  {
    "id": "13",
    "name": "Chicken Pasta",
    "image": ""
  },
  {
    "id": "14",
    "name": "Meat Balls Pasta",
    "image": "http://cloud.granddubai.com/broccoli/uploads/Meat Lovers.png"
  },
  {
    "id": "15",
    "name": "Sausage Pasta",
    "image": "http://cloud.granddubai.com/broccoli/uploads/Sausage.png"
  },
  {
    "id": "16",
    "name": "Shrimp Pasta",
    "image": "http://cloud.granddubai.com/broccoli/uploads/Shrimp.png"
  },
  {
    "id": "17",
    "name": "Vegetable Pasta",
    "image": "http://cloud.granddubai.com/broccoli/uploads/Vegetable.png"
  },
  {
    "id": "18",
    "name": "Pesto Pasta",
    "image": "http://cloud.granddubai.com/broccoli/uploads/Pesto.png"
  },
  {
    "id": "19",
    "name": "Chicken Lasagna",
    "image": ""
  },
  {
    "id": "20",
    "name": "Meat Lasagna",
    "image": ""
  },
  {
    "id": "21",
    "name": "Vegetable Lasagna",
    "image": ""
  },
  {
    "id": "22",
    "name": "Caesar Salad",
    "image": "http://cloud.granddubai.com/broccoli/uploads/Caesar.png"
  },
  {
    "id": "23",
    "name": "Chicken Caesar Salad",
    "image": "http://cloud.granddubai.com/broccoli/uploads/Chicken Caesar.png"
  },
  {
    "id": "24",
    "name": "Garden Salad",
    "image": "http://cloud.granddubai.com/broccoli/uploads/Garden.png"
  },
  {
    "id": "25",
    "name": "Greek Salad",
    "image": ""
  },
  {
    "id": "26",
    "name": "Pasta Salad",
    "image": "http://cloud.granddubai.com/broccoli/uploads/Pasta Salad.png"
  },
  {
    "id": "27",
    "name": "Sunny Side up ",
    "image": ""
  },
  {
    "id": "28",
    "name": "Omelette ",
    "image": ""
  },
  {
    "id": "29",
    "name": "Scrambled Eggs",
    "image": ""
  },
  {
    "id": "30",
    "name": "Scrambled Egg with toppings",
    "image": ""
  },
  {
    "id": "31",
    "name": "Coffee",
    "image": ""
  },
  {
    "id": "32",
    "name": "Fresh Juice",
    "image": ""
  },
  {
    "id": "36",
    "name": "Water 500ml",
    "image": ""
  },
  {
    "id": "35",
    "name": "Pepsi Can",
    "image": ""
  },
  {
    "id": "37",
    "name": "Soup",
    "image": ""
  },
  {
    "id": "38",
    "name": "Special Offer Family Pack",
    "image": ""
  }
]

here is my logcat:

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.zeba.broccoli, PID: 23142
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.zeba.broccoli/com.example.zeba.broccoli.SubMenu}: java.lang.NullPointerException: Attempt to invoke virtual method 'com.android.volley.toolbox.ImageLoader com.example.zeba.broccoli.AppController.getImageLoader()' on a null object reference
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3190)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3300)
                      at android.app.ActivityThread.access$1000(ActivityThread.java:211)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1705)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:145)
                      at android.app.ActivityThread.main(ActivityThread.java:6946)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:372)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'com.android.volley.toolbox.ImageLoader com.example.zeba.broccoli.AppController.getImageLoader()' on a null object reference
                      at com.example.zeba.broccoli.CustomListAdapter.<init>(CustomListAdapter.java:23)
                      at com.example.zeba.broccoli.SubMenu.onCreate(SubMenu.java:83)
                      at android.app.Activity.performCreate(Activity.java:6575)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3143)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3300) 
                      at android.app.ActivityThread.access$1000(ActivityThread.java:211) 
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1705) 
                      at android.os.Handler.dispatchMessage(Handler.java:102) 
                      at android.os.Looper.loop(Looper.java:145) 
                      at android.app.ActivityThread.main(ActivityThread.java:6946) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at java.lang.reflect.Method.invoke(Method.java:372) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) 

here is my Manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.zeba.broccoli">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/logo"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".RegistrationForm"
            android:label="@string/title_activity_registration_form"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".Login"
            android:label="@string/title_activity_login"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".Home"
            android:label="@string/title_activity_home"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".Menu_Detail"
            android:label="@string/title_activity_menu__detail"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".TypeMenu"
            android:label="Menu"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".SubMenu"
            android:label="@string/title_activity_sub_menu"
            android:theme="@style/AppTheme.NoActionBar">


            <activity
                android:name="AppController"
                android:label="@string/title_activity_sub_menu"
                android:theme="@style/AppTheme.NoActionBar"></activity>
            <activity
                android:name=".Movie"
                android:label="@string/title_activity_sub_menu"
                android:theme="@style/AppTheme.NoActionBar"></activity>
            <activity
                android:name=".CustomListAdapter"
                android:label="@string/title_activity_sub_menu"
                android:theme="@style/AppTheme.NoActionBar"></activity>
            <activity
                android:name=".LruBitmapCache"
                android:label="@string/title_activity_sub_menu"
                android:theme="@style/AppTheme.NoActionBar"></activity>
        </activity>
z.al
  • 279
  • 1
  • 6
  • 21

1 Answers1

0

in the manifest add

android:name="com.example.zeba.broccoli.AppController" 

to your

to elaberate

your code doesn't know you are extending application and doesn't call the oncreate which initialize the null variable , in order to do so , you need to explicitly say so in the manifest

example:

    <application
    android:allowBackup="true"
    android:icon="@mipmap/logo"
    android:name="com.example.zeba.broccoli.AppController" 
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
yanivtwin
  • 617
  • 8
  • 32
  • still crashed..the logcat is same which i added – z.al Dec 21 '16 at 13:14
  • check the name , it should be your package and the application class – yanivtwin Dec 21 '16 at 13:14
  • i have added that after this – z.al Dec 21 '16 at 13:18
  • i have added that and i have removed this 2 line from my subMenu Activity...now no error is shown but the activity is blank :( – z.al Dec 21 '16 at 13:30
  • this line i have removed- getActionBar().setBackgroundDrawable( new ColorDrawable(Color.parseColor("#1b1b1b"))); – z.al Dec 21 '16 at 13:30
  • what does it say ? it just won't show the activity ? – yanivtwin Dec 21 '16 at 13:39
  • check if there is an answer here JsonArrayRequest movieReq = new JsonArrayRequest(url, new com.android.volley.Response.Listener() { @Override public void onResponse(JSONArray response) { Log.d(TAG, response.toString()); – yanivtwin Dec 21 '16 at 13:48
  • where to add this ..as i tried in try but others become red(error) – z.al Dec 21 '16 at 13:51
  • how to debug it...as i told u i m new..just learning...kindle help – z.al Dec 21 '16 at 13:57
  • just press on the left of the code line and there should be a red circle , after that instead of pressing play to start the app , press the debug next to it. – yanivtwin Dec 21 '16 at 14:01
  • if u have related code where images are coming from database ,can u mail me ? – z.al Dec 21 '16 at 14:01
  • my answer still fixed your bug and was satisfying , please mark as correct and post a new question with the new situation – yanivtwin Dec 21 '16 at 16:01
  • it only says .....Error running SubMenu: The activity must be exported or contain an intent-filter – z.al Dec 22 '16 at 04:33
  • in your mafinest , you have an open activity called SubMenu you need to close it like the rest of them, and remove from there the AppController activity , it's not an activity it's an aplication , please mark answer as correct – yanivtwin Dec 22 '16 at 07:37
  • i m trying other coding...u can see d link http://stackoverflow.com/questions/41277370/error-getting-jsonarray-cannot-be-converted-to-jsonobject/41277630?noredirect=1#comment69756923_41277630 – z.al Dec 22 '16 at 07:41
  • if u can solve that..kindly check ..i m stuck to it ;( – z.al Dec 22 '16 at 07:42
  • i'm pretty sure it's not your problem , did you fix your manifest ? can you show your current manifest ? – yanivtwin Dec 22 '16 at 07:44
  • its mine only..i am trying to get anser in different way..kindly give ur correct answer – z.al Dec 22 '16 at 07:47
  • that is a diffrent question , meaning my answer was correct for this problem, please mark it as correct and i will continue helping in the other question – yanivtwin Dec 22 '16 at 08:03