Error when opening Database ListView

0

In my app it has activity 1 that contains editText to write nome , contagem de golos , and nome da equipa and a button to save in banco de dados in activity 2 contains ListView .

When I open the app, I put it (name, goal, goals, ..) then I click save it back to the start screen, and there is a button that opens activity 2 only when I go to open it, and close the app.

Could anyone help me?

LogCat:

   E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.allsport.miyonic.allsport, PID: 3192
              java.lang.RuntimeException: Unable to resume activity {com.allsport.miyonic.allsport/com.allsport.miyonic.allsport.ResultSimples}: 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.performResumeActivity(ActivityThread.java:3103)
                  at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3134)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2481)
                  at android.app.ActivityThread.-wrap11(ActivityThread.java)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:148)
                  at android.app.ActivityThread.main(ActivityThread.java:5417)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
               Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
                  at com.allsport.miyonic.allsport.ResultSimples.onResume(ResultSimples.java:51)
                  at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1258)
                  at android.app.Activity.performResume(Activity.java:6312)
                  at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3092)
                  at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3134) 
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2481) 
                  at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
                  at android.os.Handler.dispatchMessage(Handler.java:102) 
                  at android.os.Looper.loop(Looper.java:148) 
                  at android.app.ActivityThread.main(ActivityThread.java:5417) 
                  at java.lang.reflect.Method.invoke(Native Method) 
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

Code activity 1 :

package com.allsport.miyonic.allsport;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.text.format.DateFormat;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;


import Base.*;

public class SimplesHome extends AppCompatActivity {

    private ImageButton imgButton_play, imgButton_pause, imgButton_1, imgButton_2, vermlho, amarelo;
    public TextView valorOne;
    public TextView valorDouble;
    public int contador = 0;
    public int contador1 = 0;
    private Chronometer reloginho;
    private EditText casa, fora;
    long tempoPausado = 0;

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

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_simples);

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        imgButton_1 = (ImageButton) findViewById(R.id.imgButton_1);
        imgButton_2 = (ImageButton) findViewById(R.id.imgButton_2);
        /*vermlho = (ImageButton) findViewById(R.id.btnVermelho);
        amarelo = (ImageButton) findViewById(R.id.btnAmarelo);*/
        imgButton_play = (ImageButton) findViewById(R.id.imgButton_play);
        imgButton_pause = (ImageButton) findViewById(R.id.imgButton_pause);
        reloginho = (Chronometer) findViewById(R.id.chronometer);
        valorOne = (TextView) findViewById(R.id.txt_valor1);
        valorDouble = (TextView) findViewById(R.id.txt_valor2);
        casa = (EditText) findViewById(R.id.lbl_time1);
        fora = (EditText) findViewById(R.id.lbl_time2);



        imgButton_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                contador++;
                valorOne.setText("" + contador);

                Context alerta = getApplicationContext();
                CharSequence text = "Goooll!";
                int duracao = Toast.LENGTH_LONG;
                Toast lert = Toast.makeText(alerta, text, duracao);
                lert.show();

                DialogGol golzinho = new DialogGol();
                golzinho.show(getSupportFragmentManager(), "golzinho_tag");
            }
        });

        imgButton_2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                contador1++;
                valorDouble.setText("" + contador1);

                Context gol = getApplication();
                CharSequence texto = "Goooll!";
                int tempo = Toast.LENGTH_LONG;
                Toast apresentar = Toast.makeText(gol, texto, tempo);
                apresentar.show();

                DialogGol golzinhoTwo = new DialogGol();
                golzinhoTwo.show(getSupportFragmentManager(), "golzinhoTow_tag");
            }
        });

        imgButton_play.setEnabled(true);
        imgButton_pause.setEnabled(false);
        imgButton_1.setEnabled(false);
        imgButton_2.setEnabled(false);

        imgButton_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imgButton_play.setEnabled(false);
                imgButton_pause.setEnabled(true);
                imgButton_1.setEnabled(true);
                imgButton_2.setEnabled(true);

                reloginho.setBase(SystemClock.elapsedRealtime());
                reloginho.start();
                reloginho.setBase(SystemClock.elapsedRealtime() + tempoPausado);


                Context ini = getApplication();
                CharSequence iniciar = "Partida iniciada";
                int mostrar = Toast.LENGTH_SHORT;
                Toast ir = Toast.makeText(ini, iniciar, mostrar);
                ir.show();
            }
        });

        imgButton_pause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imgButton_play.setEnabled(true);
                imgButton_pause.setEnabled(false);
                imgButton_1.setEnabled(false);
                imgButton_2.setEnabled(false);

                tempoPausado = reloginho.getBase();
                SystemClock.elapsedRealtime();
                reloginho.stop();

                Context parar = getApplication();
                CharSequence frase = "Partida pausada";
                int rele = Toast.LENGTH_SHORT;
                Toast stop = Toast.makeText(parar, frase, rele);
                stop.show();
            }
        });

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

        if (id == R.id.salvarpartida) {

                Esporte inserir = new Esporte();

                inserir.setNomeTimeUm(casa.getText().toString());
                inserir.setNomeTimeDois(fora.getText().toString());
                inserir.setValorUm(Integer.parseInt(valorOne.getText().toString()));
                inserir.setValorDois(Integer.parseInt(valorDouble.getText().toString()));

                DbHelper dbhelp = new DbHelper(this);
                dbhelp.insertResultado(inserir);

                finish();
        }

        return super.onOptionsItemSelected(item);
    }
}

Code activity 2

package com.allsport.miyonic.allsport;

import android.content.pm.ActivityInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import java.util.List;

        import Base.DbHelper;
        import Base.Esporte;

        import static android.os.FileObserver.DELETE;

public class ResultSimples extends AppCompatActivity {

    private ListView lista;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result_simples);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        lista = (ListView) findViewById(R.id.ListaTimes);

    }

    @Override
    public void onResume(){
        super.onResume();

        DbHelper dbhe = new DbHelper(this);
        List<Esporte> listaResultPartida = dbhe.selectTodosResult();
        ArrayAdapter<Esporte> adp = new ArrayAdapter<Esporte>(this, R.layout.resultado_modificado, android.R.id.text1, listaResultPartida);

        lista.setAdapter(adp);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.resultado_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

        if (id == R.id.deletar) {
        }

        return super.onOptionsItemSelected(item);
    }
}

DbHelper:

   package Base;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;

public class DbHelper extends SQLiteOpenHelper {

    private static final String NAME_BASE = "Resultados";
    private static final int VERSION_BASE = 1;

    public DbHelper(Context context) {

        super(context, NAME_BASE, null, VERSION_BASE);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String sqlCreateTableResultado = "CREATE TABLE resultado("
                + "id INTEGER PRIMARY KEY AUTOINCREMENT,"
                + "TimeCasa TEXT,"
                + "TimeFora TEXT,"
                + "GolsCasa INTEGER,"
                + "GolsFora INTEGER"
                + "Jogadores TEXT"+ ")";

        db.execSQL(sqlCreateTableResultado);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        String sqlDropTableResultado = "DROP TABLE resultado";

        db.execSQL(sqlDropTableResultado);

        onCreate(db);

    }

    public void insertResultado(Esporte resultado){
        SQLiteDatabase db = getWritableDatabase();

        ContentValues valores = new ContentValues();
        valores.put("TimeCasa", resultado.getNomeTimeUm());
        valores.put("TimeFora", resultado.getNomeTimeDois());
        valores.put("GolsCasa", resultado.getValorUm());
        valores.put("GolsFora", resultado.getValorDois());
        valores.put("Jogadores", resultado.getjogadores());

        db.insert("resultado", null, valores);

        db.close();
    }

    public List<Esporte> selectTodosResult() {
        List<Esporte> listResult = new ArrayList<Esporte>();
        SQLiteDatabase db = getReadableDatabase();

        String sqlSelectTodosResult = "SELECT * FROM resultado";

        Cursor c = db.rawQuery(sqlSelectTodosResult, null);

        try {

            if (c != null && c.moveToFirst()) {
                c.moveToFirst();
                do {
                    Esporte onde = new Esporte();
                    onde.setId(c.getInt(0));
                    onde.setNomeTimeUm(c.getString(c.getColumnIndexOrThrow("TimeCasa")));
                    onde.setNomeTimeDois(c.getString(c.getColumnIndexOrThrow("TimeFora")));
                    onde.setValorUm(c.getInt(c.getColumnIndexOrThrow("GolsCasa")));
                    onde.setValorDois(c.getInt(c.getColumnIndexOrThrow("GolsFora")));
                    onde.setjogadores(c.getString(c.getColumnIndexOrThrow("Jogadores")));

                    listResult.add(onde);

                } while (c.moveToNext());

            }
        }catch (SQLException or){
            or.printStackTrace();
        }
        db.close();
        return listResult;
    }

    public void delete(){
        SQLiteDatabase db = getReadableDatabase();
        String sqlSelectTodosResult = "DELETE * FROM resultado";
        Cursor c = db.rawQuery(sqlSelectTodosResult, null);
    }

  }
}

Thank you ...

    
asked by anonymous 04.11.2016 / 18:55

1 answer

1

Your error is occurring because you are trying to access something that does not exist in the Cursor, try to make the following changes:

  • Implement the search within a block with exception handling.
  • Check if your cursor was created correctly and if it has records.
  • Search the column for the name instead of a literal number, otherwise you can try to access a column that does not exist.

        try {
    
         if (c != null && c.moveToFirst()) {
         c.moveToFirst();
         do {
    
         Esporte onde = new Esporte();
                onde.setId(c.getInt(0));
                onde.setNomeTimeUm(c.getString(c.getColumnIndexOrThrow("TimeCasa")));
                onde.setNomeTimeDois(c.getString(c.getColumnIndexOrThrow("TimeFora")));
                onde.setValorUm(c.getInt(c.getColumnIndexOrThrow("GolsCasa")));
                onde.setValorDois(c.getInt(c.getColumnIndexOrThrow("GolsFora")));
                onde.setjogadores(c.getString(c.getColumnIndexOrThrow("Jogadores")));
    
                listResult.add(onde);
    
         } while (c.moveToNext());
    
     }catch(SQLException er){
    
          er.printStackTrace();
    }
    
04.11.2016 / 20:04