使用列表视图从表中删除特定行

时间:2013-01-02 18:47:24

标签: android sql sqlite

我有一张桌子&item 39; itemsDataTable'当我删除一行:

public void deleteExpense(long idToDelete){ // Delete Expense
    Log.d(TAG, "Expense deleted with id: " + idToDelete);
    db.delete(TABLE, COLUMN_ID + " = " + idToDelete, null);
}

搞得一团糟。 我从列表视图中选择一个项目,在新屏幕中我可以选择删除该行。 行的_id仍在表中,但行中的所有详细信息都是空的。 列表视图的位置没有用,因为如果我多次删除,则位置不正确。

结果是这样的:

_id  some_title
1    blabla
2    blabla
3
4    blabla
5
6    blabla

任何想法如何解决所有这些混乱?

我的列表视图:

ListView lvItemsHistory=(ListView)findViewById(R.id.listView1);
        final ArrayList<Expense>expensesList=new ArrayList<Expense>();
        Cursor sortCurser=MainActivity.itemsDataBase.query();

        while (sortCurser.moveToNext()) {
            expensesList.add( new Expense(
                    sortCurser.getString(sortCurser.getColumnIndex(ItemsDataBase.COLUMN_DESCRIPTION)),
                    sortCurser.getInt(sortCurser.getColumnIndex(ItemsDataBase.COLUMN_PRICE)),
                    sortCurser.getString(sortCurser.getColumnIndex(ItemsDataBase.COLUMN_PAYMENT_OPTION)),
                    sortCurser.getString(sortCurser.getColumnIndex(ItemsDataBase.COLUMN_ITEM_CATEGORY)),
                    sortCurser.getString(sortCurser.getColumnIndex(ItemsDataBase.COLUMN_PHOTO_URL)),
                    sortCurser.getString(sortCurser.getColumnIndex(ItemsDataBase.COLUMN_LOCATION)),
                    sortCurser.getString(sortCurser.getColumnIndex(ItemsDataBase.COLUMN_DATE)),
                    sortCurser.getString(sortCurser.getColumnIndex(ItemsDataBase.COLUMN_TIME)),
                    sortCurser.getString(sortCurser.getColumnIndex(ItemsDataBase.COLUMN_VOICE_RECORD_URL))));
        }

        ArrayAdapter<Expense>itemsAdapter=new ArrayAdapter<Expense>(this, android.R.layout.simple_list_item_1, expensesList);
        lvItemsHistory.setAdapter(itemsAdapter);
        lvItemsHistory.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
                Log.d(ItemsDataBase.TAG, "Position = " + (position + 1));
                Expense item=expensesList.get(position);
                Intent intent=new Intent(HistoryExpense.this, ShowExpense.class);
                intent.putExtra("itemName", item);
                intent.putExtra("positionExpense", position + 1);
                finish();
                startActivity(intent);
            }

        });

ShowExpense:

public class ShowExpense extends Activity {

    protected int expenseID;

    private boolean isPlay;
    private MediaPlayer mediaPlayer;
    Facebook facebook;

    private TextView tvDescription, tvPrice, tvPaymentOption, tvCategory, tvLocation, tvDate, tvTime, tvIsAudioNote;
    private ImageButton btnPlayRecordedNote, shareButton, btnShareToTwitter;
    private Button btnDeleteItem, btnExportToPDF;
    private ImageView ivItemPhoto;


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

        isPlay = true; // Reset so we can play the audio

        tvDescription = (TextView)findViewById(R.id.textView2);
        tvPrice = (TextView)findViewById(R.id.textView4);
        tvPaymentOption = (TextView)findViewById(R.id.textView6);
        tvCategory=(TextView)findViewById(R.id.textView8);
        tvLocation=(TextView)findViewById(R.id.textView10);
        tvDate=(TextView)findViewById(R.id.textView12);
        tvTime=(TextView)findViewById(R.id.textView14);
        ivItemPhoto=(ImageView)findViewById(R.id.imageView1);
        btnDeleteItem=(Button)findViewById(R.id.button1);
        btnExportToPDF=(Button)findViewById(R.id.button3);
        btnPlayRecordedNote=(ImageButton)findViewById(R.id.imageButton1);
        tvIsAudioNote=(TextView)findViewById(R.id.textView15);
        shareButton = (ImageButton)findViewById(R.id.imageButton2);
        btnShareToTwitter = (ImageButton) findViewById(R.id.imageButtonTwitter);

        Bundle bundle=getIntent().getExtras();
        final Expense item=(Expense)bundle.getSerializable("itemName");

        Bundle positionExpenseBundle = getIntent().getExtras();
        final int expensePosition = positionExpenseBundle.getInt("positionExpense");

        if (item.isAudioNote.equals("null") || item.isAudioNote.isEmpty()) {
            tvIsAudioNote.setText("No recorded audio note.");
        }
        else {
            tvIsAudioNote.setText("Recorded audio note saved to " + item.isAudioNote);
        }

        tvDescription.setText(item.strDescription);
        tvPrice.setText(item.strPrice+"");
        tvPaymentOption.setText(item.paymentOption);
        tvCategory.setText(item.productCategory);
        tvLocation.setText(item.isLocation);
        tvDate.setText(item.isDate);
        tvTime.setText(item.isTime);

        final String PHOTO_URL=item.photoURL+"";
        Log.i(ItemsDataBase.TAG, PHOTO_URL+"");

        if (PHOTO_URL.isEmpty() || PHOTO_URL.equals("null") || PHOTO_URL.equals(null)) {
            Log.d(ItemsDataBase.TAG, "There is no photo. Default photo will be presented.");
            int defaultImageID=R.drawable.default_item_photo;
            ivItemPhoto.setImageResource(defaultImageID);
        }
        else {

            File file=new File(PHOTO_URL);
            Log.i(ItemsDataBase.TAG, file.toString());
            if (file.exists()) {
                Log.d(ItemsDataBase.TAG, "File photo url exists");
                Bitmap bmp=BitmapFactory.decodeFile(file.getAbsolutePath());
                Log.i(ItemsDataBase.TAG, "File absolute path="+file.getAbsolutePath());
                ivItemPhoto.setImageBitmap(bmp);
            }
            else {
                Log.d(ItemsDataBase.TAG, "File photo url does not exists");
            }
        }

        btnDeleteItem.setOnClickListener(new View.OnClickListener() { // Delete Income

            @Override
            public void onClick(View v) {

                MainActivity.itemsDataBase.deleteExpense(expensePosition);
                runOnUiThread(new Runnable() {

                    public void run() {

                        AlertDialog.Builder builder=new AlertDialog.Builder(ShowExpense.this); //Notify user all is OK
                        AlertDialog completeOK=builder.setTitle("Information").setMessage("Expense deleted with id: " + (expensePosition)).setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Log.d(ItemsDataBase.TAG, "Expense deleted with id: " + expensePosition);

                                finish();
                            }
                        }).create();
                        completeOK.show();
                    }
                });
            }
        });

        btnExportToPDF.setOnClickListener(new View.OnClickListener() { // Export to pdf

            @Override
            public void onClick(View v) {

                idanUtils idanUtils=new idanUtils();
                final String filename="/"+"EXPENSE_"+idanUtils.getDateAndTimeStamp()+".pdf";
                String deviceStorage=Environment.getExternalStorageDirectory().getAbsolutePath().toString();
                Log.d(ItemsDataBase.TAG, deviceStorage+filename);

                File myDir = new File(deviceStorage + "/My Wallet");
                myDir.mkdirs();
                File file=new File(myDir, filename);

                Document document=new Document();

                try {
                    PdfWriter.getInstance(document, new FileOutputStream(file));
                    document.open();
                    document.add(new Paragraph("Item description: "+item.strDescription));
                    document.add(new Paragraph("Paid by: "+item.paymentOption));
                    document.add(new Paragraph("Category: "+item.productCategory));
                    document.add(new Paragraph("Price: "+item.strPrice));
                    document.add(new Paragraph("Bught at: "+item.isLocation));
                    document.add(new Paragraph("Dated: "+item.isDate));
                    document.add(new Paragraph("Time: "+item.isTime));

                    if (PHOTO_URL.isEmpty() || PHOTO_URL.equals("null")) {
                        document.add(new Paragraph("No image available"));
                        Log.i(ItemsDataBase.TAG, "No image available");
                    } else {
                        Image image=Image.getInstance(item.photoURL);
                        image.scaleAbsolute(200f, 200f);
                        document.add(image);
                    }

                } catch (Exception e) {
                    String error=(e.getMessage()==null)?"Error adding information to PDF document":e.getMessage();
                    Log.e(ItemsDataBase.TAG, error);
                }
                document.close();

                runOnUiThread(new Runnable() {

                    public void run() {

                        AlertDialog.Builder builder=new AlertDialog.Builder(ShowExpense.this); //Notify user all is OK
                        AlertDialog completeOK=builder.setTitle("Information").setMessage(filename+" saved to /My Wallet folder on your internal storage.").setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Log.d(ItemsDataBase.TAG, filename+" saved to /My Wallet folder on your internal storage.");
                            }
                        }).create();
                        completeOK.show();
                    }
                });
            }
        });

        btnPlayRecordedNote.setOnClickListener(new View.OnClickListener() { // Play recorded audio note

            @Override
            public void onClick(View v) {

                if (isPlay) { // Play
                    mediaPlayer=new MediaPlayer();
                    try {
                        mediaPlayer.setDataSource(item.isAudioNote);
                        mediaPlayer.prepare();
                        mediaPlayer.start();
                    } catch (IllegalArgumentException e) {
                        Log.e(ItemsDataBase.TAG, e.getMessage());
                    } catch (IllegalStateException e) {
                        Log.e(ItemsDataBase.TAG, e.getMessage());
                    } catch (IOException e) {
                        Log.e(ItemsDataBase.TAG, e.getMessage());
                    }
                    isPlay = false;
                } else{ // Stop
                    mediaPlayer.stop();
                    mediaPlayer.release();
                    isPlay = true;
                }

                //              MediaPlayer mediaPlayer=new MediaPlayer();
                //              try {
                //                  mediaPlayer.setDataSource(item.isAudioNote);
                //                  mediaPlayer.prepare();
                //                  mediaPlayer.start();
                //              } catch (IllegalArgumentException e) {
                //                  Log.e(ItemsDataBase.TAG, e.getMessage());
                //              } catch (IllegalStateException e) {
                //                  Log.e(ItemsDataBase.TAG, e.getMessage());
                //              } catch (IOException e) {
                //                  Log.e(ItemsDataBase.TAG, e.getMessage());
                //              }
                // TODO - On Key Press Back - STOP PLAY THE AUDIO NOTE
                //              mediaPlayer.stop();
                //              mediaPlayer.release();
            }
        });

        btnShareToTwitter.setOnClickListener(new View.OnClickListener() { // Share to Twitter

            @Override
            public void onClick(View v) {

                String tweetUrl = "https://twitter.com/intent/tweet?text=";
                String text = "Hi, just twitting from My Wallet app! I just spent " + item.strPrice + " to buy " + item.strDescription;
                Uri uri = Uri.parse(tweetUrl + text);
                startActivity(new Intent(Intent.ACTION_VIEW, uri));
            }
        });

        shareButton.setOnClickListener(new View.OnClickListener() { // Share on Facebook

            @Override
            public void onClick(View v) {
                FacebookConnect.message = "Hi! Just saying hello from My Wallet app! I just spent " + item.strPrice + "$ to buy " + item.strDescription + "!";
                FacebookConnect.postStatusUpdate();
                Intent fbIntent = new Intent(ShowExpense.this, FacebookConnect.class);
                startActivity(fbIntent);
                Log.d(ItemsDataBase.TAG, FacebookConnect.message);
            }
        });

    }

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

}

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

尝试传递这样的ID:

db.delete(TABLE, COLUMN_ID + " =?", new String[] { idToDelete });

如果idToDelete是int / Integer:

db.delete(TABLE, COLUMN_ID + " =?", new String[] { String.valueOf( idToDelete ) } );