0

我有一个表'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);
            }

        });

显示费用:

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;
    }

}
4

2 回答 2

0

尝试像这样传递 ID:

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

如果 idToDelete 是一个 int/Integer:

db.delete(TABLE, COLUMN_ID + " =?", new String[] { String.valueOf( idToDelete ) } );
于 2013-01-02T19:00:23.017 回答
0

给定一列值删除数据库表中的行 - 这是一个字符串

于 2013-01-02T18:55:01.827 回答