Java – how to create a new activity, I can choose to add a new project from the database?
I created the database after this tutorial, and I created a button in the main activity, which takes the user to another activity, where they will add some new items. But I don't know how to use ArrayList to do this, because I want to add new items in listview. I want something like this in my application. Any help will be belittled
This is the code of the 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();
}
}
This is the code for 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);
}
});
}
}
This is 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>
resolvent:
In short, you need to pass the "results" of adding the project back to the main activity. Then, if the project is added, you should call the 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();
}
}
For the second activity, the activity adding the project should call setresult (result_ok) when the project is successfully added, otherwise call setresult (result_canceled)
Your code also has other functions, such as where do you populate the listview? Usually, you can get the instance through findviewbyid and set the adapter for the listview with the corresponding data
To be honest, I think you should look at these tutorials again, especially these: http://developer.android.com/training/basics/intents/result.html http://developer.android.com/guide/topics/ui/layout/listview.html