Android - solucionar Index:0 , Size:0

 
Vista:
sin imagen de perfil
Val: 40
Ha aumentado su posición en 2 puestos en Android (en relación al último mes)
Gráfica de Android

solucionar Index:0 , Size:0

Publicado por Hector (35 intervenciones) el 13/03/2021 22:17:20
Hola amigos del foro esperando que todos se ecnuentren muy bien de salud, soy nuevo y empezando con el android studio, estoy realizando una aplicación de operaciones básicas al ir al primer nivel no me deja entrar ya que me manda el mensaje de error, Index:0, Size:0 y averiguando que los campos están vacíos en la base de datos, y busco a través de la web pero ninguno me da solución a este problema, así que acudo a Uds. ya que anteriormente me ayudaron en otros programas y de diferente ámbito les muestro los código que se esta utilizando.
* este es la creación de la tabla de la base de datos
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package com.example.misamores;
 
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
 
public class AdminSQLiteOpenHelper extends SQLiteOpenHelper {
    public AdminSQLiteOpenHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }
 
    @Override
    public void onCreate(SQLiteDatabase BD) {
        BD.execSQL("create table puntaje (nombre text, score int)");
    }
 
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
 
    }
}

este es el código que se utiliza en el main activity es decir la pagina principal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package com.example.misamores;
 
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
 
public class MainActivity extends AppCompatActivity {
 
    private EditText et_nombre;
    private ImageView iv_personaje;
    private TextView tv_bestScore;
    private MediaPlayer mp;
    int num_aleatorio = (int) (Math.random() * 10);
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        et_nombre =(EditText)findViewById(R.id.txt_nombre);
        iv_personaje =(ImageView)findViewById(R.id.imageView_Personaje);
        tv_bestScore=(TextView)findViewById(R.id.textView_BestScore);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setIcon(R.mipmap.ic_launcher);
 
        int id;
        if (num_aleatorio == 0 || num_aleatorio == 10) {
            id = getResources().getIdentifier("mango","drawable", getPackageName());
            iv_personaje.setImageResource(id);
        } else if (num_aleatorio == 1 || num_aleatorio == 9) {
            id = getResources().getIdentifier("fresa","drawable", getPackageName());
            iv_personaje.setImageResource(id);
        } else if (num_aleatorio == 2 || num_aleatorio == 8) {
            id = getResources().getIdentifier("manzana", "drawable", getPackageName());
            iv_personaje.setImageResource(id);
        } else if (num_aleatorio == 3 || num_aleatorio == 7) {
            id = getResources().getIdentifier("sandia", "drawable", getPackageName());
            iv_personaje.setImageResource(id);
        } else if (num_aleatorio == 4 || num_aleatorio == 5 || num_aleatorio == 6) {
            id = getResources().getIdentifier("uva", "drawable", getPackageName());
            iv_personaje.setImageResource(id);
        }
 
        AdminSQLiteOpenHelper admin = new AdminSQLiteOpenHelper(this, "BD", null, 1);
        SQLiteDatabase BD = admin.getWritableDatabase();
        Cursor consulta = BD.rawQuery("select * from puntaje where score = (select max(score) from puntaje)", null);
        if (consulta.moveToFirst()){
            String temp_nombre = consulta.getString(0);
            String temp_score = consulta.getString(1);
            tv_bestScore.setText("Record de: " + temp_score + " de " + temp_nombre);
            BD.close();
        } else {
            BD.close();
        }
 
        mp = MediaPlayer.create(this, R.raw.alphabet_song);
        mp.start();
        mp.setLooping(true);
    }
 
    //Metodo para el boton jugar
    public  void Jugar (View view) {
        String nombre = et_nombre.getText().toString();
        if (!nombre.equals("")){
            mp.stop();
            mp.release();
            Intent intent = new Intent(this,MainActivity2_Nivel1.class);
            intent.putExtra("jugador", nombre);
            startActivity(intent);
            finish();
        } else {
            Toast.makeText(this, "Primero debes escribir tu nombre", Toast.LENGTH_SHORT).show();
            et_nombre.requestFocus();
            InputMethodManager imm = (InputMethodManager)getSystemService(this.INPUT_METHOD_SERVICE);
            imm.showSoftInput(et_nombre, InputMethodManager.SHOW_IMPLICIT);
        }
    }
 
    //metodo para el boron atras
    @Override
    public void onBackPressed() {
 
    }
}

y es es el código que se utiliza para la siguiente pantalla al momento de ingresar el nombre del jugador y hacer click en en botón Jugar, el cual deriva a esta pagina
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
package com.example.misamores;
 
import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import java.util.PrimitiveIterator;
 
public class MainActivity2_Nivel1 extends AppCompatActivity {
 
    private TextView tv_nombre, tv_score;
    private ImageView iv_Auno, iv_Ados, iv_vidas;
    private EditText et_respuesta;
    private MediaPlayer mp, mp_great, mp_bad;
    int score, numAleatorio_uno, numAleatorio_dos, resultado, vidas = 3;
    String nombre_jugador, string_score, string_vidas;
    String  numero [] = {"cero","uno","dos","tres","cuatro","cinco","seis","siete","ocho","nueve"};
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_activity2__nivel1);
        Toast.makeText(this,"Nivel 1 - Sumas Basicas", Toast.LENGTH_SHORT).show();
 
        tv_nombre = (TextView)findViewById(R.id.textView_nombre);
        tv_score = (TextView)findViewById(R.id.textView_score);
        iv_vidas = (ImageView)findViewById(R.id.imageView_vidas);
        iv_Auno = (ImageView)findViewById(R.id.imageView_NumUno);
        iv_Ados = (ImageView) findViewById(R.id.imageView_NumDos);
        et_respuesta = (EditText)findViewById(R.id.editText_resultado);
 
        nombre_jugador = getIntent().getStringExtra("jugador");
        tv_nombre.setText("Jugador:" + nombre_jugador);
 
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setIcon(R.mipmap.ic_launcher);
 
        mp = MediaPlayer.create(this, R.raw.goats);
        mp.start();
        mp.setLooping(true);
        mp_great = MediaPlayer.create(this,R.raw.wonderful);
        mp_bad = MediaPlayer.create(this,R.raw.bad);
        numAleatorio();
    }
 
    public void numAleatorio () {
        if (score <= 9) {
            numAleatorio_uno = (int) (Math.random() * 10);
            numAleatorio_dos = (int) (Math.random() * 10);
            resultado = numAleatorio_uno + numAleatorio_dos;
            if (resultado <= 10){
                for (int i = 0; i < numero.length; i++){
                    int id = getResources().getIdentifier(numero[i], "drawable", getPackageName());
                    if (numAleatorio_uno == i){
                        iv_Auno.setImageResource(id);
                    } if (numAleatorio_dos == i){
                        iv_Ados.setImageResource(id);
                    }
                }
            } else {
                numAleatorio();
            }
        } else {
            Intent intent = new Intent(this, MainActivity2_Nivel2.class);
            string_score = String.valueOf(score);
            string_vidas = String.valueOf(vidas);
            intent.putExtra("Jugador", nombre_jugador);
            intent.putExtra("Score", string_score);
            intent.putExtra("Vidas", string_vidas);
            startActivity(intent);
            finish();
            mp.stop();
            mp.release();
        }
    }
 
    public void Comparar (View view) {
        String respuesta = et_respuesta.getText().toString();
        if (!respuesta.equals("")){
            int respueta_jugador = Integer.parseInt(respuesta);
            if (resultado == respueta_jugador){
                mp_great.start();
                score++;
                tv_score.setText("Score: " + score);
                et_respuesta.setText("");
                BaseDeDatos();
            } else {
                mp_bad.start();
                vidas--;
                BaseDeDatos();
                switch (vidas) {
                    case 3:
                        iv_vidas.setImageResource(R.drawable.tresvidas);
                        break;
                    case 2:
                        Toast.makeText(this, "Te quedan 2 manzanas", Toast.LENGTH_SHORT).show();
                        iv_vidas.setImageResource(R.drawable.dosvidas);
                        break;
                    case 1:
                        Toast.makeText(this, "Te queda 1 manzana", Toast.LENGTH_SHORT).show();
                        iv_vidas.setImageResource(R.drawable.unavida);
                    case 0:
                        Toast.makeText(this, "Has pérdido totas tus manzanas", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(this, MainActivity.class);
                        startActivity(intent);
                        finish();
                        mp.stop();
                        mp.release();
                        break;
                }
                et_respuesta.setText("");
            }
            numAleatorio();
        } else {
            Toast.makeText(this, "Escribe tu respuesta", Toast.LENGTH_SHORT).show();
        }
    }
 
    public void BaseDeDatos (){
        AdminSQLiteOpenHelper admin = new AdminSQLiteOpenHelper(this, "BD", null, 1);
        SQLiteDatabase BD = admin.getWritableDatabase();
        Cursor consulta = BD.rawQuery("select * from puntaje where score = (select max(score) from puntaje)", null);
        if (consulta.moveToFirst()){
            String temp_nombre = consulta.getString(0);
            String temp_score = consulta.getString(1);
            int bestScore = Integer.parseInt(temp_score);
            if (score > bestScore){
                ContentValues modificacion = new ContentValues();
                modificacion.put("nombre", nombre_jugador);
                modificacion.put("score", score);
                BD.update ("puntaje", modificacion, "score" + bestScore, null);
            }
            BD.close();
        } else {
            ContentValues insertar = new ContentValues();
            insertar.put("nombre", nombre_jugador);
            insertar.put("score", score);
            BD.insert("puntaje", null, insertar);
            BD.close();
        }
    }
 
    @Override
    public void onBackPressed() {
 
    }
}

favor de ayudarme en esta encrucijada, como les mencione nuevo en android y recién aprendiendo, y desde ya muchas gracias.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
sin imagen de perfil
Val: 113
Bronce
Ha disminuido 1 puesto en Android (en relación al último mes)
Gráfica de Android

solucionar Index:0 , Size:0

Publicado por Ingeniero Cognitivo (42 intervenciones) el 02/04/2021 11:01:54
Tienes que copiar el codigo e ir poniendolo poco a poco para encontrar la linea exacta que falla.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

solucionar Index:0 , Size:0

Publicado por among (5 intervenciones) el 23/09/2021 11:43:27
Thank you so much for this wonderful website. with lots of interesting and useful information. I have gathered a lot of valuable information.
flip coin
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

solucionar Index:0 , Size:0

Publicado por Maria (2 intervenciones) el 07/12/2023 11:00:28
I'm glad to hear that you find the website valuable and informative. If you have any more questions or if there's anything else I can help you with, feel free to let me know. puppet hockey
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar