Error Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById (int)' on a null object reference

1

I have this error and I can not solve it, it gives every time I run the app.

LogCat:

01-15 16:09:03.380    2473-2473/com.prjctt.allan.financeiro
E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.prjctt.allan.financeiro, PID: 2473
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.prjctt.allan.financeiro/com.prjctt.allan.financeiro.ListDespesasActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method
android.view.View android.view.Window.findViewById(int) on a null
object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            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:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method android.view.View
android.view.Window.findViewById(int) on a null object reference
            at android.app.Activity.findViewById(Activity.java:2071)
            at com.prjctt.allan.financeiro.ListDespesasActivity.<init>(ListDespesasActivity.java:20)
            at java.lang.reflect.Constructor.newInstance(Native Method)
            at java.lang.Class.newInstance(Class.java:1572)
            at android.app.Instrumentation.newActivity(Instrumentation.java:1065)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2199)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            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:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

Class where error occurs:

public class ListDespesasActivity extends ListActivity {



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



    DespesaDAO despesa = new DespesaDAO(this);
    List<Despesa> list = despesa.getLista();
    setListAdapter(new DespesaAdapter(this,list));

}

@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_list_despesas, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()){
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
            return true;
        case R.id.action_add_despesa:
            Intent intent = new Intent(this, EditaDespesaActivity.class);
            startActivity(intent);
            return true;
    }

    return super.onOptionsItemSelected(item);
}

Class DespesaDAO :

public class DespesaDAO extends SQLiteOpenHelper {
private static final String NOME_BD = "mobfin";
private static final String TABELA = "Despesa";
private static final String[] COLUNAS = {"_id", "valor", "data", "descricao", "pago", "idgrupo", "idsubgrupo", "idusuario", "incluidoem", "sincronizado"};
private static final int VERSION = 1;

public DespesaDAO(Context context) {
    super(context, TABELA, null, VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    String sql = "CREATE TABLE " + TABELA + "( _id INTEGER PRIMARY KEY AUTOINCREMENT," +
            " valor DOUBLE NOT NULL," +
            "data DATETIME NOT NULL," +
            " descricao TEXT NOT NULL," +
            " pago SMALLINT NOT NULL," +
            " idgrupo INT," +
            " idsubgrupo INT," +
            " idusuario INT," +
            " incluidoem DATETIME NOT NULL," +
            " sincronizado SMALLINT NOT NULL);";
    db.execSQL(sql);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + DespesaDAO.TABELA);
    this.onCreate(db);
}

public void inserir(Despesa despesa) {
    ContentValues valores = new ContentValues();
    valores.put("valor", despesa.getValor());
    valores.put("data", despesa.getData().toString());
    valores.put("descricao", despesa.getDescricao());
    valores.put("pago", despesa.isPago());
    valores.put("idgrupo", despesa.getIdGrupo());
    valores.put("idsubgrupo", despesa.getIdSubgrupo());
    valores.put("incluidoem", despesa.getIncluidoEm().toString());
    valores.put("sincronizado", despesa.isSincronizado());

    getWritableDatabase().insert(TABELA, null, valores);
}

public void atualizar(Despesa despesa) {
    ContentValues valores = new ContentValues();
    valores.put("valor", despesa.getValor());
    valores.put("data", despesa.getData());
    valores.put("descricao", despesa.getDescricao());
    valores.put("pago", despesa.isPago());
    valores.put("idgrupo", despesa.getIdGrupo());
    valores.put("idsubgrupo", despesa.getIdSubgrupo());
    valores.put("idusuario", despesa.getIdUsuario());
    valores.put("sincronizado", despesa.isSincronizado());

    this.getWritableDatabase().update("despesa", valores, "_id = ?", new String[]{"" + despesa.getId()});
}

public void deletar (Despesa despesa){
    this.getWritableDatabase().delete("despesa", "_id = " + despesa.getId(), null);
}


public List<Despesa> getLista() {
    Cursor c = getWritableDatabase().query(TABELA, COLUNAS, null, null, null, null, null);
    List<Despesa> lista = new ArrayList<>();

    while (c.moveToNext()) {
        Despesa despesa = new Despesa();
        despesa.setId(c.getInt(0));
        despesa.setValor(c.getString(1));
        //despesa.setData(2);
        despesa.setDescricao(c.getString(3));
        despesa.setPago(c.getString(4).equalsIgnoreCase("TRUE"));
        despesa.setIdGrupo(c.getInt(5));
        despesa.setIdSubgrupo(c.getInt(6));
     //   despesa.setIncluidoEm(c.getString(7));
        despesa.setSincronizado(c.getString(8).equalsIgnoreCase("TRUE"));

        lista.add(despesa);
    }
    c.close();

    return lista;
}

}

Adapter

public class DespesaAdapter extends BaseAdapter {
private Context context;
private List<Despesa> lista;
ListView listView;

public DespesaAdapter(Context context, List<Despesa> lista) {
    this.context = context;
    this.lista = lista;
}


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

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

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

@Override
public View getView(int position, View view, ViewGroup viewGroup) {
    final int auxPosition = position;


    LayoutInflater inflater = (LayoutInflater)
            context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    final LinearLayout layout = (LinearLayout)
            inflater.inflate(R.layout.despesas, null);


    TextView tvNome = (TextView)
            layout.findViewById(R.id.tvDesp);
    tvNome.setText(lista.get(position).getDescricao());


    TextView tvValor = (TextView)
            layout.findViewById(R.id.tvVal);
    tvValor.setText(lista.get(position).getValor());

    ImageButton btEditar = (ImageButton)
            layout.findViewById(R.id.btEdit);
    btEditar.setOnClickListener(new ImageButton.OnClickListener() {

        @Override
        public void onClick(View view) {
            Intent intent = new Intent(context, EditaDespesaActivity.class);
            intent.putExtra("valor", lista.get(auxPosition).getValor());
            intent.putExtra("data", lista.get(auxPosition).getData());
            intent.putExtra("descricao", lista.get(auxPosition).getDescricao());
            context.startActivity(intent);
        }
    });

    ImageButton btDelete = (ImageButton)
            layout.findViewById(R.id.btDelete);
    btDelete.setOnClickListener(new ImageButton.OnClickListener() {
        @Override
        public void onClick(View view) {
            DespesaDAO despesa = new DespesaDAO(context);
            despesa.deletar(lista.get(auxPosition));

            layout.setVisibility(View.GONE);
        }
    });


    return layout;
}
}
    
asked by anonymous 15.01.2015 / 19:29

1 answer

2

Your ListDespesasActivity must handle the setListAdapter correctly. He must be called before anything. See an example:

public class MyListAdapter extends ListActivity {

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

    // Vamos definir um layout de tela personalizada aqui, mas
         // Normalmente , você pode simplesmente usar o layout ListActivity padrão.
         setContentView(R.layout.custom_list_activity_view);

         // Query for all people contacts using the Contacts.People convenience class.
         // Put a managed wrapper around the retrieved cursor so we don't have to worry about
         // requerying or closing it as the activity changes state.
         mCursor = this.getContentResolver().query(People.CONTENT_URI, null, null, null, null);
         startManagingCursor(mCursor);

         // Agora criar um novo adaptador vinculado ao cursor.
     // SimpleListAdapter é projetado para ligar a um Cursor.
         ListAdapter adapter = new SimpleCursorAdapter(
                 this, // Context.
                 android.R.layout.two_line_list_item,  // Specify the row template to use (here, two columns bound to the two retrieved cursor
 rows).
                 mCursor,                                              // Pass in the cursor to bind to.
                 new String[] {People.NAME, People.COMPANY},           // Array of cursor columns to bind to.
                 new int[] {android.R.id.text1, android.R.id.text2});  // Parallel array of which template objects to bind to those columns.

         // Bind to our new adapter.
         setListAdapter(adapter);
     }
 }

See more about ListActivity at: link

    
15.01.2015 / 21:55