1

I've made a database that has information like this http://i170.photobucket.com/albums/u244/therealbbri06/database.jpg

and I'm trying to get the groupName from the database using this

public String readNameFromPosition(int position) {
    Cursor c;
    c = myDataBase.query("hikingGroups", new String[] { "groupName" },
            "position=\'" + position + "\'", null, null, null, null);
    if (c.moveToFirst()) {
        return c.getString(0);
    } else {
        return "" + c.getCount();
    }
}

When position = 0 the groupName is properly retrieved, but whenever the position is equal to any other valid number c.getCount() returns "0". Any help? I can post more of the code if needed, just ask. Also readNameFromPosition() is inside my DataBaseHelper class.

UPDATE: My code

package bry.Bicker.OjaiHiking;
import java.io.IOException;
import android.app.Activity;
import android.database.SQLException;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Gallery;
import android.widget.TextView;
import android.widget.Toast;

public class OjaiHikingActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    final DataBaseHelper theDb = new DataBaseHelper(getApplicationContext());
    try {

        theDb.createDataBase();

    } catch (IOException ioe) {

        throw new Error("Unable to create database");

    }

    try {

        theDb.openDataBase();

    } catch (SQLException sqle) {

        throw sqle;

    }
    final Gallery hikesGallery = (Gallery) findViewById(R.id.gallery1);
    hikesGallery.setAdapter(new ImageAdapter(this));
    hikesGallery.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1,
                int arg2, long arg3) {
            String groupName = "";
            int position = hikesGallery.getSelectedItemPosition();
            Toast.makeText(getApplicationContext(), "" + position,
                    Toast.LENGTH_SHORT).show();
            groupName = theDb.readNameFromPosition(position);
            TextView tV = (TextView) findViewById(R.id.groupName);
            Typeface font = Typeface.createFromAsset(getAssets(),
                    "arialbd.ttf");
            tV.setTypeface(font);
            tV.setText(groupName);
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
        }

    });
    hikesGallery.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView parent, View v, int position,
                long id) {

        }
    });
}
}

The code for DataBaseHelper.java

package bry.Bicker.OjaiHiking;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

public class DataBaseHelper extends SQLiteOpenHelper {

// The Android's default system path of your application database.
private static String DB_PATH = "/data/data/bry.Bicker.OjaiHiking/databases/";

private static String DB_NAME = "Ojaiker.db";

private SQLiteDatabase myDataBase;

private final Context myContext;

public DataBaseHelper(Context context) {

    super(context, DB_NAME, null, 1);
    this.myContext = context;
}

public void createDataBase() throws IOException {

    boolean dbExist = checkDataBase();

    if (dbExist) {
        // do nothing - database already exist
    } else {

        this.getReadableDatabase();

        try {

            copyDataBase();

        } catch (IOException e) {

            throw new Error("Error copying database");

        }
    }

}

/**
 * Check if the database already exist to avoid re-copying the file each
 * time you open the application.
 * 
 * @return true if it exists, false if it doesn't
 */
private boolean checkDataBase() {

    SQLiteDatabase checkDB = null;

    try {
        String myPath = DB_PATH + DB_NAME;
        checkDB = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READONLY);

    } catch (SQLiteException e) {

        // database does't exist yet.

    }

    if (checkDB != null) {

        checkDB.close();

    }

    return checkDB != null ? true : false;
}

/**
 * Copies your database from your local assets-folder to the just created
 * empty database in the system folder, from where it can be accessed and
 * handled. This is done by transfering bytestream.
 * */
private void copyDataBase() throws IOException {

    // Open your local db as the input stream
    InputStream myInput = myContext.getAssets().open(DB_NAME);

    // Path to the just created empty db
    String outFileName = DB_PATH + DB_NAME;

    // Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);

    // transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer)) > 0) {
        myOutput.write(buffer, 0, length);
    }

    // Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();

}

public void openDataBase() throws SQLException {

    // Open the database
    String myPath = DB_PATH + DB_NAME;
    myDataBase = SQLiteDatabase.openDatabase(myPath, null,
            SQLiteDatabase.OPEN_READONLY);

}

@Override
public synchronized void close() {

    if (myDataBase != null)
        myDataBase.close();

    super.close();

}

public String readNameFromPosition(int position) {
    Cursor c;
    c = myDataBase.query("hikingGroups", new String[] { "groupName" },
            "position=\'" + position + "\'", null, null, null, null);
    if (c.moveToFirst()) {
        return c.getString(0);
    } else {
        return "" + c.getCount();
    }
}

@Override
public void onCreate(SQLiteDatabase db) {

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}
2
  • are you opened the database before executing the query ? Commented May 19, 2012 at 10:02
  • I believe so. I'm going to post my entire code because it seems like nothing has helped so far. Commented May 19, 2012 at 10:15

3 Answers 3

1

Are you sure you didn't updated the database with values outside of the application(in the SQLite manager for example) and then run the app assuming that the new values will be there on the new run? Your database will not be built again with the new values as it is present on the device/emulator.

Try reinstalling the app and then installing it again(a wild guess is that you first started the database with only one value(for position 0)).

Sign up to request clarification or add additional context in comments.

5 Comments

Ah hmm. Well you're right. I did first start it with only one value. I deleted my emulator, and I made a new one. Now it is working :D Is there any other way to reinstall the app without having to delete and recreate my emulator? I though that it got reinstalled every time the program was run, but I guess I was wrong.
@BrianEcker You don't have to delete and recreate your emulator, just like with any app you'll go to the Settings->Applications ->Manage Applications->Your app and there Clear data and Uninstall. You don't have to close the emulator or something else.
Ok, that makes a lot more sense. Thanks for helping me figure this out :D
@BrianEcker I'm glad I could help. Also instead of the query you're currently using it's recommended to use something like this, instead of inserting the values in the where clause: ..., "position= ?", new String[] {"" + position}, null, null, null);.
Ok, I'll switch to that. The question mark notation thing just confused me a little at first.
0
public String readNameFromPosition(int position) {
Cursor c;
public static final String KEY_ROWID="id";
public static final String KEY_POSITION="position";
public static final String KEY_GROPUNAME="groupName";
String[] col=new String[]{KEY_ROWID,KEY_POSITION,KEY_GROPUNAME};
Cursor c=ourDatabase.query("hikingGroups", col,KEY_POSITION+"="+position, null, null, null, null);

if (c!=null) {
     c.moveToFirst();

    return c.getString(c.getColumnIndex(KEY_GROPUNAME));
} else {
    return "" + c.getCount();
}

}

try this way

3 Comments

Android crashes. Logcat: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0 So that seems to me that the query is still not retrieving the data.
@BrianEcker have replace in line of cursor where ourDatabase by ur database name definded AS in ur class SQLiteDatabase ourDatabase i have also edit my answer check and let me inform
I replaced "ourDatabase" with my own database's name. Still get the same LogCat error: "android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0"
0

I think the DB query is not returning any result. c.moveToFirst() must be returning false and hence you should not do c.getString(...)

Better handling would be

if (c.moveToFirst()) {
    return c.getString(c.getColumnIndex(KEY_GROPUNAME));
} else {
    return "" + c.getCount();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.