java.lang.NullPointerException

2

I have a small problem that I did not understand, it is that my application is giving me the following error after having programmed the Web Service . here I leave the code:

public class Winery {
    private static final String wineURL = "http://static.keepcoding.io/baccus/wines.json";

private static Winery sInstance = null;

private List<Wine> mWines = null;

public static Winery getInstance() {
    if (sInstance == null) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                StrictMode.setThreadPolicy(policy);
            }
            sInstance = downloadWines();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    //else
    return sInstance;
}

private static Winery downloadWines() throws IOException, JSONException {
    Winery winery = new Winery();
    winery.mWines = new LinkedList<>();

    URLConnection conn = new URL(wineURL).openConnection();
    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    StringBuilder response = new StringBuilder();
    String line = null;

    while ((line = reader.readLine()) != null) {
        response.append(line);
    }
    reader.close();


    JSONArray wines = new JSONArray(reader.toString());

    for (int wineIndex = 0; wineIndex < wines.length(); wineIndex++) {
        String name = null;
        String type = null;
        String company = null;
        String companyWeb = null;
        String notes = null;
        int rating = 0;
        String origin = null;

        JSONObject jsonWine = wines.getJSONObject(wineIndex);
        if (jsonWine.has("name")) {
            name = jsonWine.getString("name");
            type = jsonWine.getString("type");
            company = jsonWine.getString("company");
            companyWeb = jsonWine.getString("companyWeb");
            notes = jsonWine.getString("notes");
            rating = jsonWine.getInt("rating");
            origin = jsonWine.getString("origin");

            Wine wine = new Wine(name, type, R.drawable.bembibre, company, companyWeb, notes, origin, rating);
            JSONArray jsonGrapes = jsonWine.getJSONArray("grapes");
            for (int grapeIndex = 0; grapeIndex < jsonGrapes.length(); grapeIndex++) {
                wine.addGrape(jsonGrapes.getJSONObject(grapeIndex).getString("grape"));

            }
            winery.mWines.add(wine);
        }
    }

    return winery;
}


public Winery(){

        //Creating wines.
        Wine bembibre =new Wine(

                "Bembibre",
                "Tinto",
                R.drawable.bembibre,
                "Dominio de Tares",
                "http://www.dominiodetares.com/portfolio/bembibre/",
                "Este vino muestra toda la complejidad y la elegancia de la variedad Mencía. En fase visual luce un color rojo picota muy cobierto con tonalidades violáceas en el menisco. En nariz aparecen recuerdos frutales muy intensos de frutas rojas (frambuesa, cereza) y una potente ciruela negra asi como tonos florales de la gama de las rosas y violetas, vegetales muy elegantes y complementarios, hojarasca verde, tabaco y maderas aromáticas (sándalo) que le brindan un troque ciertamente perfumado",
                "El Bierzo",
                5);
        bembibre.addGrape("Mencía");

        Wine vegaval =new Wine(
                "Vegaval",
                "Tinto",
                R.drawable.vegaval,
                "Miguel de Calatayud",
                "http://www.vegaval.com/es",
                "Un vino de esmerado proceso de elaboración y larga crianza. Presenta un color rojo cereza con matices a teja y una brillante capa media alta. Nariz compleja, fina y elegante. Es excelentemente estructurado, amplio y muy sabroso. Recomendado para acompañar quesos curados, estofados y todo tipo de carnes rojas y de caza. La temperatura recomendada para servir está¡ entre los 16º C y 18º C.",
                "Valdepeñas",
                4);
        vegaval.addGrape("Tempranillo");

        Wine zarate =new Wine(
                "Zarate",
                "Blanco",
                R.drawable.zarate,
                "Miguel de Calatayud",
                "http://bodegas-zarate.com/productos/vinos/albarino-zarate/",
                "El albariño Zarate es un vino blanco monovarietal que pertenece a la Denominación de Origen Rías Baixas. Considerado por la critica especializada como uno de los grandes vinos blancos del mundo, el albariño ya es todo un mito.",
                "Rias Bajas",
                5);
        zarate.addGrape("Albariño");

        Wine champagne =new Wine(
                "Champagne",
                "Otros",
                R.drawable.champagne,
                "Champagne Taittinger",
                "http://bodegas-zarate.com/productos/vinos/albarino-zarate/",
                "ùLorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ac nunc purus. Curabitur eu velit mauris. Curabitur magna nisi, ullamcorper ac bibendum ac, laoreet et justo. Praesent vitae tortor quis diam luctus condimentum. Suspendisse potenti. In magna elit, interdum sit amet facilisis dictum, bibendum nec libero. Maecenas pellentesque posuere vehicula. Vivamus eget nisl urna, quis egestas sem. Vivamus at venenatis quam. Sed eu nulla a orci fringilla pulvinar ut eu diam. Morbi nibh nibh, bibendum at laoreet egestas, scelerisque et nisi. Donec ligula quam, semper nec bibendum in, semper eget dolor. In hac habitasse platea dictumst. Maecenas adipiscing semper rutrum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae",
                "Comtes de Champagne",
                3);
        champagne.addGrape("Chardonnay");

        //Adding Wines by an Array
        mWines = Arrays.asList(new Wine[]{bembibre, vegaval, zarate, champagne});
    }

       public Wine getWine(int index) {
           return mWines.get(index);
       }
       public int getWineCount() {
           return mWines.size();
       }

       public List <Wine> getWineList(){
           return mWines;
       }
}

The error is giving me here:

  

at jhon.casique.baccus.controller.fragment.WineListFragment.onCreateView (WineListFragment.java:41)

public class WineListFragment extends Fragment {
    private OnWineSelectedListener mOnWineSelectedListener = null;


public WineListFragment() {
    // Required empty public constructor
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View root = inflater.inflate(R.layout.fragment_wine_list, container, false);

    //Reference to ListView
    ListView listView = (ListView) root.findViewById(android.R.id.list);

    //Acceding Winery
    Winery winery = Winery.getInstance();

    //List adapter
    ArrayAdapter<Wine> adapter =  new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, winery.getWineList());

    //Saying the adapter to the listView
    listView.setAdapter(adapter);

    //What to do when the user press one item on the list.
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            if (mOnWineSelectedListener != null) {
                mOnWineSelectedListener.onWineSelected(i);
            }
        }
    });

    return root;
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    mOnWineSelectedListener= (OnWineSelectedListener) getActivity();
}

@Override
public void onDetach() {
    super.onDetach();
    mOnWineSelectedListener = null;
}

public interface OnWineSelectedListener {
    void onWineSelected(int indexWine);
}

}

Line 41 is this:

   ArrayAdapter<Wine> adapter =  new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, winery.getWineList());

If someone can help me, I appreciate it.

Thanks.

    
asked by Jhon 01.11.2016 в 20:52
source

3 answers

2

Probably your winery.getWineList () this null, initializes the winery before Adapter

Winery winery = new Winery(); 

ArrayAdapter<Wine> adapter =  new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, winery.getWineList());
    
answered by 09.01.2017 в 17:01
2

Be careful, that request http is not allowed from the% main thread . You should perform the task asynchronously, an alternative is to use an AsyncTask . For that you must create a class that inherits from AsyncTask and within the method doInBackground you make the request and return the result. Then, in the onPostExecute method you receive the answer that you returned in the previous method and there you create the adapter, and fill it with the information that the service has answered. Another option is to use a tool, such as Volley or RetroFit .

    
answered by 09.01.2017 в 20:06
1

The array that gets this method probably has a Null value, you should get an array of objects Wine :

winery.getWineList()

When calling within onCreateView() the method Winery.getInstance(); is not actually filling the List of objects Wine ( mWines ), try calling the constructor Winery() to initialize the List.

Winery winery = new Winery(); 

before initializing the Adapter.

    
answered by 01.11.2016 в 21:05