如何创建新活动,我可以选择从数据库添加新项目?

时间:2015-07-18 11:39:29

标签: java android sqlite

我在this教程之后创建了数据库,并且我在主要活动中创建了一个按钮,该按钮将用户带到另一个活动,在那里他们将添加一些新项目。但我不知道如何使用ArrayList执行此操作,因为我想在ListView中添加新项目。我希望在我的应用程序中有this之类的东西。任何帮助都会被贬低。

以下是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();
    }

}    

,这是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);

            }
        });
    }
}

这是我的主要活动布局:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    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>

1 个答案:

答案 0 :(得分:0)

简而言之,您需要传递将项目添加回主要活动的“结果”。然后,如果添加了项目,则应调用适配器以更新适配器数据。

 // Your previous code       
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);
                startActivityForResult(intent, ADD_ITEM_REQ_CODE);

            } 
        }); 

// Then handle the result
public void onActivityResult(int reqCode, int resultCode, Intent data){
  if (reqCode == ADD_ITEM_REQ_CODE && resultCode == RESULT_OK){
    // get your ListView adapter and update data
    mListAdapter.notifyDataSetChanged();
  }
}

您的第二项活动,即添加项目的活动,应在成功添加项目时调用setResult(RESULT_OK),否则调用setResult(RESULT_CANCELLED)

您的代码还有其他一些内容,例如,您在哪里填充ListView?通常,您可以通过findViewById获取实例,并使用相应的数据为该ListView设置适配器。

老实说,我认为你应该再看看这些教程,特别是这些: http://developer.android.com/training/basics/intents/result.html http://developer.android.com/guide/topics/ui/layout/listview.html