1. activity_main.xml
Add the LinearLayout of the horizontal layout in the LinearLayout of the vertical layout, and then add EditText product name, EditText amount, ImageView add button
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:id="@+id/addLL" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <EditText android:id="@+id/nameET" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:hint="Trade name" android:inputType="textPersonName" /> <EditText android:id="@+id/balaceET" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:hint="Amount of money" android:inputType="number" /> <ImageView android:onClick="add" android:id="@+id/addIV" android:layout_width="wrap_content" android:layout_height="wrap_content" app:srcCompat="@android:drawable/ic_input_add" /> </LinearLayout> <ListView android:id="@+id/accountLV" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/addLL"/> </LinearLayout>
2. Create ListView Item layout
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:padding="10dp"> <TextView android:id="@+id/idTV" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="13" android:textColor="#000000" android:textSize="20sp"/> <TextView android:id="@+id/nameTV" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="2" android:text="PQ" android:textColor="#000000" android:textSize="20sp"/> <TextView android:id="@+id/balanceTV" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="2" android:text="12345" android:textColor="#000000" android:textSize="20sp"/> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical"> <ImageView android:id="@+id/upIV" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="2dp" app:srcCompat="@android:drawable/arrow_up_float" /> <ImageView android:id="@+id/downIV" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" app:srcCompat="@android:drawable/arrow_down_float" /> </LinearLayout> <ImageView android:id="@+id/deleteIV" android:layout_width="25dp" android:layout_height="25dp" app:srcCompat="@android:drawable/ic_menu_delete" /> </LinearLayout>
Three textviews are added to display the id, commodity name, and amount of a piece of data in the database. Three imageviews are used to increase, decrease, and delete data.
3. Create a database, create a package named dao under the package, and define a MyHelper class under the package to inherit from SQLiteOpenHelper,
public class MyHelper extends SQLiteOpenHelper { public MyHelper(Context context){ super(context, "itcast.db", null, 2); } @Override public void onCreate(SQLiteDatabase db) { System.out.println("onCreate"); db.execSQL("CREATE TABLE account(_id INTEGER PRIMARY KEY AUTOINCREMENT, name, VARCHAR(30), balance INTEGER)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { System.out.println("onUpgrade"); } }
4. Create the Account class,
It is convenient to store the data in a JavaBean object when operating the database. Therefore, it is necessary to build a bean package to store JavaBean classes, and then define a class Account under the package. The code is as follows:
package com.example.product.bean; public class Account { private Long id; private String name; private Integer balance; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getBalance() { return balance; } public void setBalance(Integer balance) { this.balance = balance; } public Account(Long id, String name, Integer balance) { super(); this.id = id; this.name = name; this.balance = balance; } public Account(String name, Integer balance) { super(); this.name = name; this.balance = balance; } public Account(){ super(); } @Override public String toString() { return "[Serial number:" + id + ",Commodity name:" + name + ",Balance:" + balance + "]"; } }
5. Create database operation logic class
Create an AccountDao class under dao to operate data. The code is as follows
public class AccountDao { private MyHelper helper; public AccountDao(Context context) { helper = new MyHelper(context); } public void insert(Account account){ SQLiteDatabase db = helper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("name", account.getName()); values.put("balance", account.getBalance()); long id = db.insert("account", null, values); account.setId(id); db.close(); } // Delete data by id public int delete(long id){ SQLiteDatabase db = helper.getWritableDatabase(); int count = db.delete("account", "_id=?", new String[]{id+""}); db.close(); return count; } // Update data public int update(Account account){ SQLiteDatabase db = helper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("name", account.getName()); values.put("balance", account.getBalance()); int count = db.update("account", values, "_id=?", new String[] {account.getId()+""}); db.close(); return count; } //Query all data in reverse order public List<Account> queryAll(){ SQLiteDatabase db = helper.getReadableDatabase(); Cursor c = db.query("account", null, null, null, null, null, "balance DESC"); List<Account> list = new ArrayList<Account>(); while(c.moveToNext()){ long id = c.getLong(c.getColumnIndex("_id")); String name = c.getString(1); int balance = c.getInt(2); list.add(new Account(id, name, balance)); } c.close(); db.close(); return list; } }
The above code is the logical class AccountDao of the operation database class, which creates methods for adding, deleting, modifying and querying data.
6. MainActivity.java
package com.example.product; import java.util.List; import android.app.Activity; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.example.product.bean.Account; import com.example.product.dao.AccountDao; public class MainActivity extends Activity { // Data set to be adapted private List<Account> list; // Database addition, deletion, modification and query operation class private AccountDao dao; // Enter EditText for name private EditText nameET; // EditText of the input amount private EditText balanceET; // Adapter private MyAdapter adapter; // ListView private ListView accountLV; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Initialize control initView(); dao = new AccountDao(this); // Query all data from database list = dao.queryAll(); adapter = new MyAdapter(); accountLV.setAdapter(adapter);// Add adapter to ListView (automatically generate entries from data) } // Initialize control private void initView() { accountLV = (ListView) findViewById(R.id.accountLV); nameET = (EditText) findViewById(R.id.nameET); balanceET = (EditText) findViewById(R.id.balanceET); // Add listener to listen for item click event accountLV.setOnItemClickListener(new MyOnItemClickListener()); } //activity_mian.xml corresponds to the method triggered by click event of ImageView public void add(View v) { String name = nameET.getText().toString().trim(); String balance = balanceET.getText().toString().trim(); //balance.equals("") is equal to 0 //Type conversion if balance is not an empty string Account a = new Account(name, balance.equals("") ? 0 : Integer.parseInt(balance)); dao.insert(a); // insert database list.add(a); // Insert set adapter.notifyDataSetChanged(); // Refresh interface // Select the last accountLV.setSelection(accountLV.getCount() - 1); nameET.setText(""); balanceET.setText(""); } // Customize an adapter (tool for loading data into ListView) private class MyAdapter extends BaseAdapter { public int getCount() { // Get the total number of entries return list.size(); } public Object getItem(int position) { // Get objects by location return list.get(position); } public long getItemId(int position) { // Get id based on location return position; } // Get an item view public View getView(int position, View convertView, ViewGroup parent) { // Reuse convertView View item = convertView != null ? convertView : View.inflate( getApplicationContext(), R.layout.item, null); // Get TextView in this view TextView idTV = (TextView) item.findViewById(R.id.idTV); TextView nameTV = (TextView) item.findViewById(R.id.nameTV); TextView balanceTV = (TextView) item.findViewById(R.id.balanceTV); // Get Account object based on current location final Account a = list.get(position); // Put the data in the Account object into TextView idTV.setText(a.getId() + ""); nameTV.setText(a.getName()); balanceTV.setText(a.getBalance() + ""); ImageView upIV = (ImageView) item.findViewById(R.id.upIV); ImageView downIV = (ImageView) item.findViewById(R.id.downIV); ImageView deleteIV = (ImageView) item.findViewById(R.id.deleteIV); //Click event triggered method of up arrow upIV.setOnClickListener(new OnClickListener() { public void onClick(View v) { a.setBalance(a.getBalance() + 1); // Modified value notifyDataSetChanged(); // Refresh interface dao.update(a); // Update database } }); //The method to trigger the click event of the down arrow downIV.setOnClickListener(new OnClickListener() { public void onClick(View v) { a.setBalance(a.getBalance() - 1); notifyDataSetChanged(); dao.update(a); } }); //How to delete the click event trigger of pictures deleteIV.setOnClickListener(new OnClickListener() { public void onClick(View v) { //Pop up a dialog box before deleting data android.content.DialogInterface.OnClickListener listener = new android.content.DialogInterface. OnClickListener() { public void onClick(DialogInterface dialog, int which) { list.remove(a); // Remove from collection dao.delete(a.getId()); // Remove from database notifyDataSetChanged();// Refresh interface } }; Builder builder = new Builder(MainActivity.this); // create a dialog box builder.setTitle("Are you sure you want to delete?"); // Set title // Set the text of the OK button and the listener builder.setPositiveButton("Determine", listener); builder.setNegativeButton("cancel", null); // Set cancel button builder.show(); // display a dialog box } }); return item; } } //Item click event of ListView private class MyOnItemClickListener implements OnItemClickListener { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Get the data on the click location Account a = (Account) parent.getItemAtPosition(position); Toast.makeText(getApplicationContext(), a.toString(), Toast.LENGTH_SHORT).show(); } } }