简体   繁体   中英

how I can get the data from the selected item in the listView from my database and view it on alertdialog?

I am having trouble with a ListView I created:

I have a food database but how I can get the data from the selected item in the listView from my database and view it on alertdialog?

I can view the data but when I click any of it, my application will stop working.

My code for this looks like:

public class MainActivity extends AppCompatActivity {
    ListView listView;
    EditText editText;
    private DatabaseHelperList dbHelper;
    Adapter adapter;
    ArrayList<Item> arrayList = new ArrayList<Item>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //loadDatabase
        dbHelper = new DatabaseHelperList(this);
        try {
            dbHelper.checkAndCopyDatabase();
            dbHelper.openDatabase();
        } catch (SQLException e) {

        }
        try {
            Cursor cursor = dbHelper.QueryData("select *from menulist");
            if (cursor != null) {
                if (cursor.moveToFirst()) {
                    do {
                        Item item = new Item();
                        item.setId(cursor.getString(0));
                        item.setFood(cursor.getString(1));
                        item.setCalories(cursor.getString(2));
                        arrayList.add(item);
                    } while (cursor.moveToNext());
                }
            }
        } catch (SQLException e) {
        }
        adapter = new Adapter(this, R.layout.custom_list_item, arrayList);
        listView = (ListView) findViewById(R.id.list_item);


        listView.setAdapter(adapter);
        adapter.notifyDataSetChanged();

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View v, int position, long id)
            {
                Cursor res = dbHelper.getAllData("select " + position + " from menulist");
                StringBuffer buffer = new StringBuffer();
                while (res.moveToNext()) {
                    buffer.append("Weight: " + res.getString(1) + " kg \n");
                    buffer.append("BMI: " + res.getString(2) + "\n");
                }

                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setCancelable(true);
                builder.setTitle("Confirmation:");
                builder.setMessage(res.getInt(res.getColumnIndex("id")));
                builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        Intent startNewActivity = new Intent(MainActivity.this, SQLiteDemoActivity.class);
                        startActivity(startNewActivity);
                    }
                }).setNegativeButton("NO", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                    }
                });
                builder.show();
            }
        }

        );

    }
}

This the log:

12-31 23:50:27.734 15775-15775/com.example.hidir.mnutrihealth E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.hidir.mnutrihealth, PID: 15775
android.database.CursorIndexOutOfBoundsException: Index 5 requested, with a size of 5
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:426)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
at android.database.AbstractWindowedCursor.getInt(AbstractWindowedCursor.java:68)
at com.example.hidir.mnutrihealth.MainActivity$1.onItemClick(MainActivity.java:76)
at android.widget.AdapterView.performItemClick(AdapterView.java:299)
at android.widget.AbsListView.performItemClick(AbsListView.java:1162)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:2953)
at android.widget.AbsListView$3.run(AbsListView.java:3708)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:149)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
at dalvik.system.NativeStart.main(Native Method)

My first advice :

Create a class DAO for all the resquet into a database. Here, it will become unreadable if you add more than one call.

Second :

Are you sure that :

while (res.moveToNext()) {
     buffer.append("Weight: " + res.getString(1) + " kg \n");
     buffer.append("BMI: " + res.getString(2) + "\n");

}

Weight is a String and BMI a String too ?

If Weight is a int or a double, i think you have to use res.getInt(1) or res.getDouble(1). Check the real method, i don't remember is you have to specify the "column name"

Edit : I think i found the issue :

while (res.moveToNext()) {
                buffer.append("Weight: " + res.getString(1) + " kg \n");
                buffer.append("BMI: " + res.getString(2) + "\n");
            }

            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setCancelable(true);
            builder.setTitle("Confirmation:");
            builder.setMessage(res.getInt(res.getColumnIndex("id")));

look at the last line. You would like to have the integer of something, but the cursor is now a the end of the list of item that were asking before.

You do :

A while loop for putting all the element on a StringBuffer, and when it finish, you ask a another time to access to a element that doesn't exist anymore.

Answer is in the Log. It says, CursorIndexOutOfBoundsException: Index 5 requested, with a size of 5 at com.example.hidir.mnutrihealth.MainActivity$1.onItemClick(MainActivity.java:76) .

The problem is here,

builder.setMessage(res.getInt(res.getColumnIndex("id")));

At the time when you call the method res.getInt() , size of cursor is 5 (means index values from 0 to 4) but it is pointing at index 5. That's why it is throwing CursorIndexOutOfBoundsException .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM