简体   繁体   English

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

[英]How would I create new activity where I would 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 . 但我不知道如何使用ArrayList执行此操作,因为我想在ListView添加新项目。 I want something like this to have in my application. 我希望在我的应用程序中有这样的东西。 Any help would be appricieated. 任何帮助都会被贬低。

Here's the code of DataBase : 这是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: 这是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://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>

In a nutshell, you need to pass the "result" of adding an item back to the main activity. 简而言之,您需要传递将项目添加回主要活动的“结果”。 Then, if there was an item added, you should call your adapter to update the adapter data. 然后,如果添加了项目,则应调用适配器以更新适配器数据。

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

Your second activity, the one that adds an item should call setResult(RESULT_OK) when the item was added successfully and setResult(RESULT_CANCELLED) otherwise. 第二个活动,添加项目的活动应该在成功添加项目时调用setResult(RESULT_OK) ,否则调用setResult(RESULT_CANCELLED)

There some other things with your code, for instance, where do you populate your ListView? 您的代码还有其他一些功能,例如,您在哪里填充ListView? Normally, you would get the instance though a findViewById and set an adapter to that ListView, with the corresponding data. 通常,您可以通过findViewById获取实例,并使用相应的数据为该ListView设置适配器。

Honestly, I think you should have a look to the tutorials again, specially these: http://developer.android.com/training/basics/intents/result.html http://developer.android.com/guide/topics/ui/layout/listview.html 老实说,我认为你应该再看看这些教程,特别是这些: http//developer.android.com/training/basics/intents/result.html http://developer.android.com/guide/topics/ UI /布局/ listview.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 从另一个选项卡添加新任务时,应在何处放置requery()以刷新列表? - Where would I place requery() in order to refresh the list when I add new task from another tab? 如何使用Java中的for循环从类创建新对象? - How would I create a new object from a class using a for loop in java? 我如何以编程方式将项目添加到activity_main_drawer.xml中的菜单中 - How would I programatically add items to my menu in in activity_main_drawer.xml 如何创建与文本文档具有相同空格和换行的字符串? - How would I create a string that has the same spaces and new lines as a text document? 我将如何为这个程序创建一个最高分计数器,我将把它放在哪里? - How would I create a Highest Score counter for this program & where would I place it? 如果一个分数不能简化,我将如何制作一个新的分数? - How would I make a new fraction if a fraction cannot be simplified? 如何将5个字母的单词转移到新的文本文件中? - How would I transfer 5-letter words into a new text file? 我该如何为此添加onClickListener? - How would I add an onClickListener to this? 我如何有一个唯一的按钮向JTable添加一行 - How Would I have a button unique add a row to a JTable 每当我添加到数据库时如何创建新文件到文件系统 - How to create new file to filesystem each time i add to database
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM