错误java.lang.IndexOutOfBoundsException,获取索引数据库SQLite时

时间:2014-03-15 19:21:49

标签: android sqlite

任何人Pliss帮助,我想从数据库中显示数据,但是当我运行它时说错误Outofboundsexception,任何人都可以帮助我吗?错误登录

public ArrayList<Sma> getPoint(String name)
{
 ArrayList <Sma> point = new ArrayList<Sma>(); 

String selectQuery = "SELECT latitude_sma, longtitude_sma FROM sma WHERE nama_sma ='" + name + "'"; >> FROM HERE I JUST WANT TO SHOW latitude_sma, and longtitude_sma IN A TEXTVIEW
open();
Cursor c = database.rawQuery(selectQuery, null);

if (c.moveToFirst()) {
    do {
        Sma sekolah = new Sma();
        sekolah.setLatitude(c.getString(c.getColumnIndex(latitude_sma)));
        sekolah.setLongitude(c.getString(c.getColumnIndex(longtitude_sma)));
        point.add(sekolah);
    } 
    while (c.moveToNext());
}
    return point;
}

这是我的活动

 private void handleIntent(Intent intent) 
 {
        if (Intent.ACTION_SEARCH.equals(intent.getAction())) 
        {

            dataSource.open();
            String query = intent.getStringExtra(SearchManager.QUERY);
            DBDataSource dataSource = new DBDataSource(this);
            ArrayList<Sma> list = dataSource.getPoint(query);
            TextView tv = (TextView) findViewById(R.id.txtQuery);
                    //WHEN I RUN THIS CODE BELOW, THE ERROR HAPPEND > IndexOutOfBounds
            tv.setText(list.get(0).getLongitude().toString());
            tv.setText(list.get(1).getLatitude().toString());
            }
      }

任何人都可以帮助我,拜托,谢谢B4:D

2 个答案:

答案 0 :(得分:0)

您根本不确定列表中是否有两个元素。 在尝试list.get(0)list.get(1)之前尝试检查。

 ArrayList<Sma> list = dataSource.getPoint(query);
if(list.size()>2){

            TextView tv = (TextView) findViewById(R.id.txtQuery);
                    //WHEN I RUN THIS CODE BELOW, THE ERROR HAPPEND > IndexOutOfBounds
            tv.setText(list.get(0).getLongitude().toString());
            tv.setText(list.get(1).getLatitude().toString());


}

你也可以考虑将你的sql语句更改为......

Cursor c = db.rawQuery("SELECT latitude_sma, longtitude_sma FROM sma WHERE nama_sma = ?", new String[] {name});

检查sqlite db中的数据,请关注

# Switch to the data directory
cd /data/data
# Our application
cd de.vogella.android.todos
# Switch to the database dir
cd databases
# Check the content
ls
# Assuming that there is a todotable file
# connect to this table
sqlite3 yourDBName.db 

答案 1 :(得分:0)

问题在于您处理光标的方式。您最终将尝试读取光标最后一行之外的列数据。请改用以下习语。 (你也没有关闭光标,这个问题也是一个单独的问题。)

ArrayList <Sma> point = new ArrayList<Sma>();
Cursor cursor = null;
try {
    cursor = database.rawQuery(...);
    for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
        Sma sekolah = new Sma();
        sekolah.setLatitude(cursor.getString(cursor.getColumnIndex(latitude_sma)));
        sekolah.setLongitude(cursor.getString(cursor.getColumnIndex(longtitude_sma)));
        points.add(sekolah);
    }
} finally { 
    if (cursor != null) {
        cursor.close();
    }
}
return points;
相关问题