samedi 18 juillet 2015

How would i create new activity where would i have option to add new items from database?

I have created database following this tutorial, and i have created one button in main activity which will take users to another activity where they would add some new items. But i don't know how would i do this with ArrayList because i want to add new items in listView. I want something like this to have in my application. Any help would be appricieated.

Here's the code of DataBase:

    public class DatabaseHandler extends SQLiteOpenHelper {

    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "itemManager";

    // Contacts table name
    private static final String TABLE_ITEMS = "items";

    // Contacts Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_TITLE = "title";
    private static final String KEY_PRICE = "price";

    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_ITEMS_TABLE = "CREATE TABLE " + TABLE_ITEMS + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_TITLE + " TEXT,"
                + KEY_PRICE + " TEXT" + ")";
        db.execSQL(CREATE_ITEMS_TABLE);
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_ITEMS);

        // Create tables again
        onCreate(db);
    }
    /**
     * All CRUD(Create, Read, Update, Delete) Operations
     */

    // Adding new item
    void addItem(Item item) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_TITLE, item.getTitle()); // Title Name
        values.put(KEY_PRICE, item.getPrice()); // Price

        // Inserting Row
        db.insert(TABLE_ITEMS, null, values);
        db.close(); // Closing database connection
    }

    // Getting item
    Item getItem(int id) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_ITEMS, new String[] { KEY_ID,
                KEY_TITLE, KEY_PRICE }, KEY_ID + "=?",
                new String[] { String.valueOf(id) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        Item item = new Item(Integer.parseInt(cursor.getString(0)),
                cursor.getString(1), cursor.getString(2));
        // return item
        return item;
    }

    // Getting All Items
    public List<Item> getAllItems() {
        List<Item> itemsList = new ArrayList<Item>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_ITEMS;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Item item = new Item();
                item.setID(Integer.parseInt(cursor.getString(0)));
                item.setTitle(cursor.getString(1));
                item.setPrice(cursor.getString(2));
                // Adding contact to list
                itemsList.add(item);
            } while (cursor.moveToNext());
        }

        // return items list
        return itemsList;
    }

    // Updating single item
    public int updateItem(Item item) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_TITLE, item.getTitle());
        values.put(KEY_PRICE, item.getPrice());

        // updating row
        return db.update(TABLE_ITEMS, values, KEY_ID + " = ?",
                new String[] { String.valueOf(item.getID()) });
    }

    // Deleting single item
    public void deleteItem(Item item) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_ITEMS, KEY_ID + " = ?",
                new String[] { String.valueOf(item.getID()) });
        db.close();
    }

    // Getting items Count
    public int getItemsCount() {
        String countQuery = "SELECT  * FROM " + TABLE_ITEMS;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();

        // return count
        return cursor.getCount();
    }

}    

and here is the code of MainActivity:

    public class MainActivity extends BaseActivity {

    Button addItem;
    private Toolbar toolbar;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        FrameLayout frameLayout = (FrameLayout)findViewById(R.id.frame_container);

         // inflate the custom activity layout
        LayoutInflater layoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View activityView = layoutInflater.inflate(R.layout.activity_main, null,false);

        frameLayout.addView(activityView);

        // Setting toolbar
        toolbar = (Toolbar) findViewById(R.id.app_bar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

        DatabaseHandler db = new DatabaseHandler(this);

        addItem = (Button) findViewById(R.id.button1);
        addItem.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, AddActivity.class);
                startActivity(intent);

            }
        });
    }
}

Here's my Main Activity layout:

    <RelativeLayout xmlns:android="http://ift.tt/nIICcg"
    android:id="@+id/mainContent"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <include
        android:id="@+id/app_bar"
        layout="@layout/app_bar" />

    <Button
        android:id="@+id/button1"
        style="@style/MyCustomButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="@string/button" />

    <ListView
        android:id="@+id/list"
        android:layout_margin="5dp"
        android:layout_below="@+id/relativeLayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/button1"
        android:layout_centerHorizontal="true"
        android:divider="@color/list_divider_row"
        android:dividerHeight="10.0sp"
        android:listSelector="@drawable/list_row_selector" >
    </ListView>

    <RelativeLayout
        android:id="@+id/relativeLayout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/listView1"
        android:layout_alignRight="@+id/listView1"
        android:layout_below="@+id/app_bar"
        android:padding="10dp" >

        <TextView
            android:id="@+id/item_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="4dp"
            android:text="Items"
            android:textColor="#474747"
            android:textSize="16sp" />

        <TextView
            android:id="@+id/item_count"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_marginLeft="5dp"
            android:layout_marginTop="4dp"
            android:layout_toRightOf="@+id/item_text"
            android:text="(2)"
            android:textColor="#474747"
            android:textSize="14sp" />

        <TextView
            android:id="@+id/total_amount"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:text="Rs. 5700"
            android:textColor="#000000"
            android:textSize="20dp" />

    </RelativeLayout>

</RelativeLayout>

Aucun commentaire:

Enregistrer un commentaire