FATAL EXCEPTION: main Process:-When I opened the application give ANDROID error

Asked

Viewed 749 times

0

every time I try to open an error query, I’m using php along with java follows the error below:

 E/AndroidRuntime: FATAL EXCEPTION: main
    Process: br.com.alencardeveloper.escola.sisescolar, PID: 11602
    java.lang.RuntimeException: Unable to start activity ComponentInfo{br.com.alencardeveloper.escola.sisescolar/br.com.alencardeveloper.escola.sisescolar.alunos}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5443)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
        at br.com.alencardeveloper.escola.sisescolar.alunos.onCreate(alunos.java:45)
        at android.app.Activity.performCreate(Activity.java:6245)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490) 
        at android.app.ActivityThread.-wrap11(ActivityThread.java) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:148) 
        at android.app.ActivityThread.main(ActivityThread.java:5443) 

my code on Veralunosadapter.java is

    package br.com.alencardeveloper.escola.sisescolar;

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 org.w3c.dom.Text;

import java.util.List;

public class VerAlunosAdapter extends BaseAdapter {

    private Context ctx;
    private List<VerAlunos>lista;

    public VerAlunosAdapter(Context ctx2, List<VerAlunos> lista2){
        ctx = ctx2;
        lista = lista2;
    }

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

    @Override
    public VerAlunos getItem(int position) {
        return lista.get(position);
    }

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = null;
        if(convertView == null){
            LayoutInflater inflater = ((Activity)ctx).getLayoutInflater();
            v = inflater.inflate(R.layout.item_lista, null);
        } else {
            v = convertView;
        }

        VerAlunos c = getItem(position);

        TextView itemNome = (TextView) v.findViewById(R.id.ItemNome);
        TextView itemIdade = (TextView) v.findViewById(R.id.ItemIdade);
        TextView itemTelefone = (TextView) v.findViewById(R.id.ItemTelefone);
        TextView itemCelular = (TextView) v.findViewById(R.id.ItemCelular);
        TextView itemTurma = (TextView) v.findViewById(R.id.ItemTurma);
        TextView itemTurno = (TextView) v.findViewById(R.id.ItemTurno);
        //TextView itemProgress = (TextView) v.findViewById(R.id.ItemProgresso);

        itemNome.setText(c.getNome());
        itemIdade.setText(c.getTelefone());
        itemTelefone.setText(c.getTelefone());
        itemCelular.setText(c.getCelular());
        itemTurma.setText(c.getTurma());
        itemTurno.setText(c.getTurno());



        return v;
    }
}

the code in students.java is:

package br.com.alencardeveloper.escola.sisescolar;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.koushikdutta.async.future.FutureCallback;
import com.koushikdutta.ion.Ion;

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

public class alunos extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    ListView listViewAlunos;

    private String HOST = "http://sis.colegioaplic.com.br/android";

    VerAlunosAdapter verAlunosAdapter;
    List<VerAlunos> lista;

    @Override
    protected void onCreate(Bundle savedInstanceState) {


        listViewAlunos = (ListView) findViewById(R.id.listViewAlunos);

        lista = new ArrayList<VerAlunos>();
        verAlunosAdapter = new VerAlunosAdapter(alunos.this, lista);

        listViewAlunos.setAdapter(verAlunosAdapter);

        listaAlunos();

        super.onCreate(savedInstanceState);
        setContentView(R.layout.alunos);
        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();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.tela_principal, 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);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_principal) {
            // Handle the camera action
            Intent abreTelaPrincipal = new Intent (this, TelaPrincipal.class);
            startActivity(abreTelaPrincipal);
        } else if (id == R.id.nav_aluno) {
            Intent abreTelaAlun = new Intent (this, alunos.class);
            startActivity(abreTelaAlun);
        } else if (id == R.id.nav_notas) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
    private void listaAlunos(){
        String url = HOST + "/alunos.php";

        Ion.with(getBaseContext())
                .load(url)
                .asJsonArray()
                .setCallback(new FutureCallback<JsonArray>() {
                    @Override
                    public void onCompleted(Exception e, JsonArray result) {
                        for(int i = 0; i < result.size(); i++){
                            JsonObject obj = result.get(i).getAsJsonObject();

                            VerAlunos c = new VerAlunos();

                            c.setId(obj.get("id").getAsInt());
                            c.setNome(obj.get("nome").getAsString());
                            c.setIdade(obj.get("idade").getAsString());
                            c.setTelefone(obj.get("telefone").getAsString());
                            c.setCelular(obj.get("celular").getAsString());
                            c.setTurma(obj.get("turma").getAsString());
                            c.setTurno(obj.get("turno").getAsString());
                            c.setMedia(obj.get("media").getAsString());

                            lista.add(c);
                        }
                        verAlunosAdapter.notifyDataSetChanged();
                    }
                });
    }
}

the Activity is below:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_alunos"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_tela_principal"
        app:menu="@menu/tela_principal_drawer" />

</android.support.v4.widget.DrawerLayout>

Below is the app_bar_alunos.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".alunos">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include
        android:id="@+id/listViewAlunos"
        layout="@layout/content_alunos" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        app:srcCompat="@android:drawable/ic_dialog_email" />

</android.support.design.widget.CoordinatorLayout>

below content_alunos.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context=".alunos"
tools:showIn="@layout/app_bar_alunos">


    <ListView
        android:id="@+id/listViewAlunos"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout >

1 answer

1


Hi, Daniel!

Try it this way

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.alunos);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        listViewAlunos = (ListView) findViewById(R.id.listViewAlunos);

        lista = new ArrayList<VerAlunos>();
        verAlunosAdapter = new VerAlunosAdapter(alunos.this, lista);

        listViewAlunos.setAdapter(verAlunosAdapter);

        listaAlunos();


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

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

Your app gave crash due to a NullPointerException which indicates that you are trying to reference a View that does not exist in the layout current.

In your case, the View even exists, in theory, but you try to access it even before the layout be annexed to Activity. That method setContentView(R.layout.alunos); must be the first to be called, before any reference to any View within the Activity.

After done the above procedure, replace that include

<include
   android:id="@+id/listViewAlunos"
   layout="@layout/content_alunos" />

For that

<include layout="@layout/content_alunos" />

I hope this helps!

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.