Error calling listview in a fragment

1

I get the following error

  

java.lang.NullPointerException: Attempt to invoke virtual method   'android.view.View android.view.View.findViewById (int)' on a null   object reference

In the android studio Code

package com.example.lab_des_06.student;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;


public class viajes extends Fragment {

    Cursor fila;
    String concat;
    String servidor_c;
    String HttpURL;
    ListView ViajesListView;
    ProgressBar progressBar;
    String HttpUrl = "http://158.97.121.14/smobil_app/WebService/ViajesList.php";
    List<String> IdList = new ArrayList<>();

    //private String d1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        if (getArguments() != null){
          String d1 = getArguments().getString("username","0");
            }
            final String d1 = "laura";
                //  String d2 =extras.getString("pass");
                //   TextView binve = (TextView)getView().findViewById(R.id.nom2);
                //  binve.setText(d1);

        //Variable de lista
        ViajesListView =  getView().findViewById(R.id.listview2);
        progressBar = (ProgressBar)getView().findViewById(R.id.progressBar2);
        new GetHttpResponse(getActivity()).execute();
        //Al  seleccionar la lista de viajes extrae la posicion de la id
        ViajesListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id){

                //abre nueva pagina
                Intent intent = new Intent(getActivity(),ViajesDescripcion.class);
                intent.putExtra("username",d1);
                // Envio de valor al darle clic del ListView  con un intent
                intent.putExtra("ListViewValue", IdList.get(position).toString());
                try{
                    startActivity(intent);
                }
                catch (Exception e){
                    e.printStackTrace();
                }
                //Finishing current activity after open next activity.
                //
                //  finish();

            }
        });


        consulta();
        // HttpURL = "http://"+concat+servidor_c+"ViajesList.php";
        // Toast.ma

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        final String d1 = "laura";
        final TextView binve = (TextView)getView().findViewById(R.id.nom2);
        binve.setText(d1);
            /*
        //Variable de lista
        ViajesListView = (ListView)getView().findViewById(R.id.listview2);
        progressBar = (ProgressBar)getView().findViewById(R.id.progressBar2);
//        new GetHttpResponse(viajes.this).execute();
        //Al  seleccionar la lista de viajes extrae la posicion de la id
        ViajesListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                //abre nueva pagina
                Intent intent = new Intent(getActivity(),ViajesDescripcion.class);
                intent.putExtra("username",d1);
                // Envio de valor al darle clic del ListView  con un intent
                intent.putExtra("ListViewValue", IdList.get(position).toString());
                try{
                    startActivity(intent);
                }
                catch (Exception e){
                    e.printStackTrace();
                }
                //Finishing current activity after open next activity.
                //
                //  finish();

          }
        });
        */
        consulta();

        /// Toast.makeText(getContext(),   "Envio"+d1, Toast.LENGTH_LONG).show();

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_listas, container, false);

        }
        private void consulta() {
        DB consulta = new DB(getActivity().getApplicationContext(), null, null, 1);
        SQLiteDatabase db = consulta.getWritableDatabase();
        fila = db.rawQuery("SELECT ID, servidor,ip FROM datos WHERE id = (SELECT max(ID) FROM datos)", null);
        if (fila.moveToFirst()) {
            String id = fila.getString(0);
            String servidor = fila.getString(1);
            String ip = fila.getString(2);
            concat =ip;
            servidor_c =servidor;
             }
        }
        private class GetHttpResponse extends AsyncTask<Void, Void, Void>{

        public Context context;

        String JSonResult;

        List<Viaje> viajeList;

        GetHttpResponse(Context context)
        {
            this.context = context;
        }

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... arg0)
        {
            consulta();
            // Passing HTTP URL to HttpServicesClass Class.
            HttpServicesClass httpServicesClass = new HttpServicesClass("http://"+concat+"/"+servidor_c+"ViajesList.php");
            //HttpServicesClass httpServicesClass = new HttpServicesClass(HttpUrl);
            try
            {
                httpServicesClass.ExecutePostRequest();

                if(httpServicesClass.getResponseCode() == 200)
                {
                    JSonResult = httpServicesClass.getResponse();

                    if(JSonResult != null)
                    {
                        JSONArray jsonArray = null;

                        try {
                            jsonArray = new JSONArray(JSonResult);

                            JSONObject jsonObject;

                            Viaje viaje;

                            viajeList = new ArrayList<Viaje>();

                            for(int i=0; i<jsonArray.length(); i++)
                                 {
                                viaje = new Viaje();

                                jsonObject = jsonArray.getJSONObject(i);

                                // Adding Student Id TO IdList Array.
                                IdList.add(jsonObject.getString("id").toString());

                                //Adding Student Name.
                                viaje.StudentName = jsonObject.getString("fecha_salida").toString();
                                viaje.Status = jsonObject.getString("status").toString();
                                viaje.Clave = jsonObject.getString("codigo").toString();

                                viajeList.add(viaje);
                            }
                        }
                        catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
                else
                {
                    Toast.makeText(context, httpServicesClass.getErrorMessage(), Toast.LENGTH_SHORT).show();
                }
            }
            catch (Exception e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }
        @Override
        protected void onPostExecute(Void result)
        {
            progressBar.setVisibility(View.GONE);

            ViajesListView.setVisibility(View.VISIBLE);

            ListAdapterClass adapter = new ListAdapterClass(viajeList, context);

            ViajesListView.setAdapter(adapter);
        }
    }}
    
asked by Francisco Romero Murillo 23.08.2018 в 18:02
source

2 answers

2

You can initialize your views in onCreateView

Event OnCreate

 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        if (getArguments() != null){
          String d1 = getArguments().getString("username","0");
            }
            final String d1 = "laura";
 }

Event OnCreateView

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {


    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_listas, container, false);

    final String d1 = "laura";
    final TextView binve = (TextView)view.findViewById(R.id.nom2);
    binve.setText(d1);


     //Variable de lista
        ViajesListView =  view.findViewById(R.id.listview2);
        progressBar = (ProgressBar)view.findViewById(R.id.progressBar2);
        new GetHttpResponse(getActivity()).execute();
        //Al  seleccionar la lista de viajes extrae la posicion de la id
        ViajesListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id){

            //abre nueva pagina
            Intent intent = new Intent(getActivity(),ViajesDescripcion.class);
            intent.putExtra("username",d1);
            // Envio de valor al darle clic del ListView  con un intent
            intent.putExtra("ListViewValue", IdList.get(position).toString());
            try{
                startActivity(intent);
            }
            catch (Exception e){
                e.printStackTrace();
            }
            //Finishing current activity after open next activity.
            //
            //  finish();

        }
    });
    consulta();

    /// Toast.makeText(getContext(),   "Envio"+d1,Toast.LENGTH_LONG).show();

    return view;

    }

Explanation

What I did was inflate the view in a variable called view and from the variable view I was initializing the views and return the variable view (the visual)

    
answered by 23.08.2018 / 19:36
source
-1

almost never uses onCreate since it only serves to instantiate most things. I recommend using it on the onViewCreated since once the view is built, load the data

would be something like this:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}




@Override
public void onViewCreated() {


    if (getArguments() != null){
      String d1 = getArguments().getString("username","0");
        }
        final String d1 = "laura";
            //  String d2 =extras.getString("pass");
            //   TextView binve = (TextView)getView().findViewById(R.id.nom2);
            //  binve.setText(d1);

    //Variable de lista
    ViajesListView =  getView().findViewById(R.id.listview2);
    progressBar = (ProgressBar)getView().findViewById(R.id.progressBar2);
    new GetHttpResponse(getActivity()).execute();
    //Al  seleccionar la lista de viajes extrae la posicion de la id
    ViajesListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
    {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id){

            //abre nueva pagina
            Intent intent = new Intent(getActivity(),ViajesDescripcion.class);
            intent.putExtra("username",d1);
            // Envio de valor al darle clic del ListView  con un intent
            intent.putExtra("ListViewValue", IdList.get(position).toString());
            try{
                startActivity(intent);
            }
            catch (Exception e){
                e.printStackTrace();
            }
            //Finishing current activity after open next activity.
            //
            //  finish();

        }
    });


    consulta();
    // HttpURL = "http://"+concat+servidor_c+"ViajesList.php";
    // Toast.ma

}
    
answered by 23.08.2018 в 19:31