0

Have tried to look at other threads but seems different to how I seem to have coded my classes (based on http://go.developer.ebay.com/devzone/articles/build-product-database-zxing-and-sqlite-android)

Would like to read the data from the database based on the 'Title' column in alphabetical order.

Or if there is a way to enter data with the current date stamp then order current items via date?

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

This is my current items class which I want to show all my data items, but I only want to show 2 columns of information - Title and Quantity. In order of titles.

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

Based on the current code i am getting an error on:

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

"The method setListAdapter(ArrayAdapter) is undefined for the type CurrentItems CurrentItems.java"
/FoodCalculator/src/com/example/foodcalculator line 56 Java Problem

Tried to make the following changes from Activity to ListView but that gave a number of errors

public class CurrentItems extends Activity 
public class CurrentItems extends ListView

Would appreciate any help!

EDIT: Main class added

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;
    }
}
2
  • Can you post the code for foodcalculator? There error doesn't seem to be related to inserting or sorting items in the db. Commented Jan 14, 2014 at 18:01
  • have added to main post as requested Commented Jan 14, 2014 at 18:03

1 Answer 1

1
public class CurrentItems extends Activity

Does not extend ListActivity. setListAdapter is a method of ListActivity.

So change to

public class CurrentItems extends ListActivity

Also you have this

super.onCreate(savedInstanceState); // twice
Sign up to request clarification or add additional context in comments.

2 Comments

Does this need to be removed then? super.onCreate(savedInstanceState); // twice
@tagz2712 why twice remove the duplicate

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.