简体   繁体   中英

not getting Images from server into my Listview in android

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>

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">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM