2014-03-16 4 views
-2

Привет, у меня есть небольшая проблема, я применил код базы данных sql и код моей активности ... Теперь приложение падает, когда я пытаюсь запустить действие (1). Я также даю вам код базы данных sql (2). И текст из logcat (3).Не удается найти ошибку в коде

(1):

package com.peky.smartornot; 

import android.os.Bundle; 
import android.app.Activity; 
import android.view.Menu; 
import android.view.View; 
import android.widget.Button; 
import android.widget.TabHost; 
import android.widget.Toast; 
import android.widget.TabHost.TabSpec; 
import android.widget.TextView; 

public class POV1 extends Activity { 
    Sql ulaz = new Sql(this); 
    TextView joke4text; 
    TextView joke3text; 
    TextView joke2text; 
    TextView joke1text; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_pov1); 
     sve(); 
    } 

    public void sve() { 
     // TODO Auto-generated method stub 
     ulaz.open(); 
     int joker1 = ulaz.procitaj(), joker2 = ulaz.procitaj2(), joker3 = ulaz 
       .procitaj3(), joker4 = ulaz.procitaj4(); 
     ulaz.close(); 
     TabHost joker = (TabHost) findViewById(R.id.tabhost); 
     joker.setup(); 
     TabSpec izgled = joker.newTabSpec("tag1"); 
     izgled.setContent(R.id.tab1); 
     izgled.setIndicator("Joker 1"); 
     joker.addTab(izgled); 
     izgled = joker.newTabSpec("tag2"); 
     izgled.setContent(R.id.tab2); 
     izgled.setIndicator("Joker 2"); 
     joker.addTab(izgled); 
     izgled = joker.newTabSpec("tag3"); 
     izgled.setContent(R.id.tab3); 
     izgled.setIndicator("Joker 3"); 
     joker.addTab(izgled); 
     izgled = joker.newTabSpec("tag4"); 
     izgled.setContent(R.id.tab4); 
     izgled.setIndicator("Joker 4"); 
     joker.addTab(izgled); 
     joke1text = (TextView) findViewById(R.id.joker1text); 
     joke1text.setText("You have " + joker1 + " jokers !"); 
     joke2text = (TextView) findViewById(R.id.joker2text); 
     joke2text.setText("You have " + joker2 + " jokers !"); 
     joke3text = (TextView) findViewById(R.id.joker3text); 
     joke3text.setText("You have " + joker3 + " jokers !"); 
     joke4text = (TextView) findViewById(R.id.joker4text); 
     joke4text.setText("You have " + joker4 + " jokers !"); 
    } 

    public void joker1(View view) { 
     Button netocan = (Button) findViewById(R.id.button5); 
     Button netocan2 = (Button) findViewById(R.id.button4); 
     Button netocan3 = (Button) findViewById(R.id.button2); 
     ulaz.open(); 
     int joker1=ulaz.procitaj(),joker2,joker3,joker4; 
     ulaz.close(); 
     if (joker1 != 0) { 
      if(netocan.getVisibility()==View.VISIBLE){ 
       netocan.setVisibility(View.INVISIBLE); 
       ulaz.open(); 
       joker1=joker1-1; 
       joker2=ulaz.procitaj2(); 
       joker3=ulaz.procitaj3(); 
       joker4=ulaz.procitaj4(); 
       ulaz.spremijoker(joker1, joker2, joker3, joker4); 
       ulaz.close(); 
       joke1text = (TextView) findViewById(R.id.joker1text); 
       joke1text.setText("You have " + joker1 + " jokers !"); 
      }else if(netocan2.getVisibility()==View.VISIBLE){ 
       netocan2.setVisibility(View.INVISIBLE); 
       ulaz.open(); 
       joker1=joker1-1; 
       joker2=ulaz.procitaj2(); 
       joker3=ulaz.procitaj3(); 
       joker4=ulaz.procitaj4(); 
       ulaz.spremijoker(joker1, joker2, joker3, joker4); 
       ulaz.close(); 
       joke1text = (TextView) findViewById(R.id.joker1text); 
       joke1text.setText("You have " + joker1 + " jokers !"); 
      }else if(netocan3.getVisibility()==View.VISIBLE){ 
       netocan3.setVisibility(View.INVISIBLE); 
       ulaz.open(); 
       joker1=joker1-1; 
       joker2=ulaz.procitaj2(); 
       joker3=ulaz.procitaj3(); 
       joker4=ulaz.procitaj4(); 
       ulaz.spremijoker(joker1, joker2, joker3, joker4); 
       ulaz.close(); 
       joke1text = (TextView) findViewById(R.id.joker1text); 
       joke1text.setText("You have " + joker1 + " jokers !"); 
      }else{ 
       Toast imasodgovor=Toast.makeText(getApplicationContext(), "You can not use more JOKERS1 on this question !", Toast.LENGTH_SHORT); 
       imasodgovor.show(); 
      } 

     }else{ 
      Toast nemasjokera=Toast.makeText(getApplicationContext(), "You dont have enought JOKERS1 !", Toast.LENGTH_SHORT); 
      nemasjokera.show(); 
     } 

    } 

    public void joker4(View view) { 
     ulaz.open(); 
     int joker1,joker2,joker3,joker4=ulaz.procitaj4(); 
     ulaz.close(); 
     Button netocan = (Button) findViewById(R.id.button5); 
     Button netocan2 = (Button) findViewById(R.id.button4); 
     Button netocan3 = (Button) findViewById(R.id.button2); 
     if (joker4 != 0) { 
      if(netocan.getVisibility()==View.VISIBLE || netocan2.getVisibility()==View.VISIBLE || netocan3.getVisibility()==View.VISIBLE){ 
      netocan.setVisibility(View.INVISIBLE); 
      netocan2.setVisibility(View.INVISIBLE); 
      netocan3.setVisibility(View.INVISIBLE); 
      ulaz.open(); 
      joker1=ulaz.procitaj(); 
      joker2=ulaz.procitaj2(); 
      joker3=ulaz.procitaj3(); 
      joker4=joker4 - 1;; 
      ulaz.spremijoker(joker1, joker2, joker3, joker4); 
      ulaz.close(); 
      joke4text = (TextView) findViewById(R.id.joker4text); 
      joke4text.setText("You have " + joker4 + " jokers !");}else{ 
       Toast imasodgovor=Toast.makeText(getApplicationContext(), "You can not use more JOKERS4 on this question !", Toast.LENGTH_SHORT); 
       imasodgovor.show(); 
      } 
     } else { 
      Toast jokertext = Toast.makeText(getApplicationContext(), 
        "Not enought JOKERS4", Toast.LENGTH_SHORT); 
      jokertext.show(); 

     } 
    } 

    public void joker2(View view){ 

    } 
    public void tocan(View view){ 
    } 
    public void netocanodgovor(View view) { 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.pov1, menu); 
     return false; 
    } 

} 

(2):

package com.peky.smartornot; 

import android.content.ContentValues; 
import android.content.Context; 
import android.database.Cursor; 
import android.database.sqlite.SQLiteDatabase; 
import android.database.sqlite.SQLiteOpenHelper; 

public class Sql { 
    public static final String KEY_ROWID = "_id"; 
    public static final String KEY_JOKER1 = "joker"; 
    public static final String KEY_JOKER2 = "joker2"; 
    public static final String KEY_JOKER3 = "joker3"; 
    public static final String KEY_JOKER4 = "joker4"; 

    private static final String DATABASE_NAME = "SQL"; 
    private static final String DATABASE_TABLE = "peoples_table"; 
    private static final int DATABASE_VERSION = 1; 

    private DbHelper ourHelper; 
    private final Context ourContext; 
    private SQLiteDatabase ourDatabase; 

    private static class DbHelper extends SQLiteOpenHelper { 

     public DbHelper(Context context) { 
      super(context, DATABASE_NAME, null, DATABASE_VERSION); 
      // TODO Auto-generated constructor stub 
     } 

     @Override 
     public void onCreate(SQLiteDatabase db) { 
      // TODO Auto-generated method stub 
      db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID 
        + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_JOKER1 
        + " INTEGER, " + KEY_JOKER2 + " INTEGER, " + KEY_JOKER3 
        + " INTEGER, " + KEY_JOKER4 + " INTEGER);"); 
     } 

     @Override 
     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
      // TODO Auto-generated method stub 
      db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE); 
      onCreate(db); 
     } 

    } 

    public Sql(Context c) { 
     ourContext = c; 
    } 

    public Sql open() { 
     ourHelper = new DbHelper(ourContext); 
     ourDatabase = ourHelper.getWritableDatabase(); 
     return this; 
    } 

    public void close() { 
     ourHelper.close(); 
    } 

    public long spremijoker(int joker1, int joker2, int joker3, int joker4) { 
     // TODO Auto-generated method stub 
     ContentValues cv = new ContentValues(); 

     cv.put(KEY_JOKER1, joker1); 

     cv.put(KEY_JOKER2, joker2); 

     cv.put(KEY_JOKER3, joker3); 

     cv.put(KEY_JOKER4, joker4); 

     return ourDatabase.insert(DATABASE_TABLE, null, cv); 

    } 

    public int procitaj() { 
     // TODO Auto-generated method stub 
     String[] columns = new String[] { KEY_ROWID, KEY_JOKER1 }; 
     Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, 
       null, null); 
     int citac = 0; 
     int iJokerammount = c.getColumnIndex(KEY_JOKER1); 
     c.moveToLast(); 
     citac = c.getInt(iJokerammount); 

     return citac; 

    } 

    public int procitaj2() { 
     // TODO Auto-generated method stub 
     // TODO Auto-generated method stub 
     String[] columns = new String[] { KEY_ROWID, KEY_JOKER2 }; 
     Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, 
       null, null); 
     int citac = 0; 
     int iJoker2 = c.getColumnIndex(KEY_JOKER2); 
     c.moveToLast(); 
     citac = c.getInt(iJoker2); 

     return citac; 

    } 

    public int procitaj3() { 
     // TODO Auto-generated method stub 
     // TODO Auto-generated method stub 
     String[] columns = new String[] { KEY_ROWID, KEY_JOKER3 }; 
     Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, 
       null, null); 
     int citac = 0; 
     int iJoker3 = c.getColumnIndex(KEY_JOKER3); 
     c.moveToLast(); 
     citac = c.getInt(iJoker3); 

     return citac; 

    } 

    public int procitaj4() { 
     // TODO Auto-generated method stub 
     // TODO Auto-generated method stub 
     String[] columns = new String[] { KEY_ROWID, KEY_JOKER4 }; 
     Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, 
       null, null); 
     int citac = 0; 
     int iJoker4 = c.getColumnIndex(KEY_JOKER4); 
     c.moveToLast(); 
     citac = c.getInt(iJoker4); 

     return citac; 

    } 

} 

(3):

03-16 19:32:11.580: E/AndroidRuntime(26569): FATAL EXCEPTION: main 
03-16 19:32:11.580: E/AndroidRuntime(26569): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.peky.smartornot/com.peky.smartornot.POV1}: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 0 
03-16 19:32:11.580: E/AndroidRuntime(26569): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1970) 
+1

Вы уверены, что это полный журнал? Кроме того, какие попытки вы предприняли до сих пор при попытке выявить проблему? Также проверьте http://stackoverflow.com/help/how-to-ask –

ответ

1

Ваша ошибка говорит все:

CursorIndexOutOfBoundsException: Индекс -1 просил, с размером 0

Вы пытаетесь получить доступ к пустой список из что-то с индексом элемента из -1. -1 никогда не является допустимым индексом массива в Java, так что у вас есть две проблемы:

  1. Почему список пуст, если это действительно не хотели?
  2. Что вызывает неправильное значение индекса -1?

С android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1970) где проблема возникает, вот где вам нужно искать. Что в вашем коде называется? Поскольку performLaunchActivity нигде в вашем размещенном коде (и не является вашей функцией main), и поскольку ваша трассировка стека не является более тщательной, нам потребуется дополнительная информация, прежде чем мы сможем вам помочь.

+0

Я не просмотрел ваш код, но если вы переходите с других языков, где -1 - действительный индекс, вам придется его изменить на 'List.getLength() - 1' или аналогичный. – Yos233

+0

Изменено "никогда" на "никогда не на Java". – aliteralmind

+0

Так что, если я добавлю на код создания значение содержимого, чтобы положить 0 в него, он должен исправить мою проблему? И никакое минимальное значение не должно быть 0, список пуст, я думаю. Я это попробую. – user3402198

0

Я нашел исправление этой проблемы я установил в методе procitaj:

for(c.moveToFirst;!c.isAfterLast;c.moveToNext){ 
citac = c.getInt(iJoker4); 
} 

вместо:

c.moveToLast; 

Спасибо в любом случае!

Смежные вопросы