簡體   English   中英

如何從android數據庫sqlite讀取數據?

[英]How to read data from android database sqlite?

嘗試查看其他線程,但似乎與我對類的編碼方式不同(基於http://go.developer.ebay.com/devzone/articles/build-product-database-zxing-and-sqlite- android

希望根據字母順序從“標題”列中讀取數據庫中的數據。

或者,如果可以輸入帶有當前日期戳的數據,然后通過日期訂購當前項目?

AddProduct.java

package com.example.foodcalculator;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.example.foodcalculator.Homepage.ProductData;

public class AddItem extends Activity implements OnClickListener {
    private static final int REQUEST_BARCODE = 0;
    private static final ProductData mProductData = new ProductData();
    EditText mBarcodeEdit;
    EditText mTitleEdit;
    EditText mQuantityEdit;
    private Button mScanButton;
    private Button mAddButton;
    // private ProductDatabase mProductDb;
    ProductDatabase mProductDb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_product);

        mBarcodeEdit = (EditText) findViewById(R.id.barcodeEdit);
        mTitleEdit = (EditText) findViewById(R.id.titleEdit);
        mQuantityEdit = (EditText) findViewById(R.id.quantityEdit);
        mScanButton = (Button) findViewById(R.id.scanButton);
        mScanButton.setOnClickListener(this);
        mAddButton = (Button) findViewById(R.id.addButton);
        mAddButton.setOnClickListener(this);
        mProductDb = new ProductDatabase(this);
    }

    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.scanButton:
            Intent intent = new Intent("com.google.zxing.client.android.SCAN");
            intent.putExtra("SCAN_MODE", "PRODUCT_MODE");
            startActivityForResult(intent, REQUEST_BARCODE);
            break;

        case R.id.addButton:
            String barcode = mBarcodeEdit.getText().toString();
            String title = mTitleEdit.getText().toString();
            String quantity = mQuantityEdit.getText().toString();

            String errors = validateFields(barcode, title, quantity);
            if (errors.length() > 0) {
                showInfoDialog(this, "Please fix errors", errors);
            } else {
                mProductData.barcode = barcode;
                mProductData.title = title;
                mProductData.quantity = Double.valueOf(quantity);

                mProductDb.insert(mProductData);
                showInfoDialog(this, "Success", "Product saved successfully");
                resetForm();
            }
            break;
        }
    }

    private void showInfoDialog(Context context, String title,
            String information) {
        new AlertDialog.Builder(context).setMessage(information)
                .setTitle(title)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                }).show();
    }

    private void resetForm() {
        // TODO Auto-generated method stub
        mBarcodeEdit.getText().clear();
        mTitleEdit.getText().clear();
        mQuantityEdit.getText().clear();
    }

    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == REQUEST_BARCODE) {
            if (resultCode == RESULT_OK) {
                String barcode = intent.getStringExtra("SCAN_RESULT");
                mBarcodeEdit.setText(barcode);

            } else if (resultCode == RESULT_CANCELED) {
                finish();
            }
        }
    }

    private static String validateFields(String barcode, String title,
            String quantity) {
        StringBuilder errors = new StringBuilder();

        if (barcode.matches("^\\s*$")) {
            errors.append("Barcode required\n");
        }

        if (title.matches("^\\s*$")) {
            errors.append("Title required\n");
        }

        if (!quantity.matches("^-?\\d+(.\\d+)?$")) {
            errors.append("Need numeric quantity\n");
        }

        return errors.toString();
    }
}

ProductDatabase.java

package com.example.foodcalculator;

import com.example.foodcalculator.Homepage.ProductData;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class ProductDatabase {
    private static final String PRODUCT_TABLE = "products";
    private static final String DATABASE_NAME = "foodcalculator.db";
    private static final int DATABASE_VERSION = 1;

    private SQLiteDatabase db;

    private static class ProductDatabaseHelper extends SQLiteOpenHelper {

        private static final String TAG = null;

        public ProductDatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            // TODO Auto-generated constructor stub
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            StringBuilder sql = new StringBuilder();

            sql.append("create table ").append(PRODUCT_TABLE).append("(  ")
                    .append("   _id integer primary key,")
                    .append("   barcode text,").append("   title text,")
                    .append("   quantity number").append(")  ");

            db.execSQL(sql.toString());

            Log.d(TAG, PRODUCT_TABLE + "table created");
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("drop table if exists " + PRODUCT_TABLE);
            onCreate(db);
        }
    }

    public ProductDatabase(Context context) {
        ProductDatabaseHelper helper = new ProductDatabaseHelper(context);
        db = helper.getWritableDatabase();
    }

    public boolean insert(ProductData product) {
        ContentValues vals = new ContentValues();
        vals.put("barcode", product.barcode);
        vals.put("title", product.title);
        vals.put("quantity", product.quantity);

        return db.insert(PRODUCT_TABLE, null, vals) != -1;
    }
}

這是我當前的項目類,我想顯示所有數據項目,但是我只想顯示2列信息-標題和數量。 按標題順序。

CurrentItems.java

package com.example.foodcalculator;

import java.util.ArrayList;
import java.util.Scanner;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;

public class CurrentItems extends Activity {

    private final String DATABASE_NAME = "foodcalculator.db";
    private final String PRODUCT_TABLE = "products";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ArrayList<String> results = new ArrayList<String>();
        SQLiteDatabase foodDB = null;

        try {
            foodDB = this.openOrCreateDatabase(DATABASE_NAME, MODE_PRIVATE,
                    null);

            foodDB.execSQL("CREATE TABLE IF NOT EXISTS " + PRODUCT_TABLE
                    + " (barcode String, format String,"
                    + " title String, price Double;");

            foodDB.execSQL("INSERT INTO " + PRODUCT_TABLE
                    + " Values ('564565645665','Beans',1.5);");

            Cursor c = foodDB.rawQuery("SELECT FROM " + PRODUCT_TABLE, null);

            if (c != null) {
                if (c.moveToFirst()) {
                    do {
                        String title = c.getString(c.getColumnIndex("title"));
                        Double quantity = c.getDouble(c
                                .getColumnIndex("Quantity"));
                        results.add("" + title + ",Quantity: " + quantity);
                    } while (c.moveToNext());
                }
            }

            this.setListAdapter(new ArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_1, results));

        } catch (SQLiteException se) {
            Log.e(getClass().getSimpleName(),
                    "Could not create or open the database");
        } finally {
            if (foodDB != null)
                foodDB.execSQL("DELETE FROM " + PRODUCT_TABLE);
            foodDB.close();
        }

        super.onCreate(savedInstanceState);
        setContentView(R.layout.current_inventory);

        final Button scanButton = (Button) findViewById(R.id.addButton);
        final Button editInventoryButton = (Button) findViewById(R.id.editItemCurrent);

        scanButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(view.getContext(), Scanner.class);
                startActivity(intent);
            }
        });

        editInventoryButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(view.getContext(), EditItems.class);
                startActivity(intent);
            }
        });
    }

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

根據當前代碼,我收到以下錯誤消息:

this.setListAdapter(new ArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_1, results));

“對於類型CurrentItems CurrentItems.java,未定義方法setListAdapter(ArrayAdapter)”
/ FoodCalculator / src / com / example / foodcalculator第56行Java問題

嘗試將以下內容從“活動”更改為“ ListView”,但這產生了許多錯誤

public class CurrentItems extends Activity 
public class CurrentItems extends ListView

將不勝感激!

編輯:添加主類

package com.example.foodcalculator;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Homepage extends Activity {

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

        final Button addButton = (Button) findViewById(R.id.scanner);
        final Button editInventoryButton = (Button) findViewById(R.id.editItem);
        final Button currentInventoryButton = (Button) findViewById(R.id.currentItems);
        final Button settingsButton = (Button) findViewById(R.id.settings);

        addButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                /* startActivity(new Intent(Homepage.this, AddProduct.class)); */
                Intent intent = new Intent(view.getContext(), AddItem.class);
                startActivity(intent);
            }
        });

        /*
         * currentInventoryButton.setOnClickListener(new View.OnClickListener()
         * {
         * 
         * @Override public void onClick(View view) { // TODO Auto-generated
         * method stub Intent intent = new Intent(view.getContext(),
         * CurrentInventory.class); startActivity(intent); } });
         */

        editInventoryButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(view.getContext(), EditItems.class);
                startActivity(intent);
            }
        });

        settingsButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(view.getContext(), Settings.class);
                startActivity(intent);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);

    }

    static final class ProductData {
        String barcode;
        String title;
        Double quantity;
    }
}
public class CurrentItems extends Activity

不擴展ListActivity setListAdapterListActivity的方法。

所以改為

public class CurrentItems extends ListActivity

你也有這個

super.onCreate(savedInstanceState); // twice

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM