Android-商品展示案例
1.创建程序
创建一个名为“商品展示”的应用程序,将包名修改为cn.edu.bzu。
2.用户交互界面
(1)“商品展示”程序对应的布局文件(activity_main.xml)
线性布局下包含一个水平显示的线性布局和一个ListView控件垂直显示;在水平显示的线性布局(LinearLayout)下建两个文本控件(EditText)“商品名称”、“金额”和一个显示图片控件。文本属性Android:inputType其中使用到了ImageView的属性Android:src来指定ImageView要显示的图片,但是只显示图片原图大小;如果使用Android:src属性,图片的大小会根据ImageView的大小进行拉伸。此外,ListView控件以列表的形式展示具体数据的内容,并且能够根据数据的长度自适应屏幕的显示。例:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_margin="8dp"
tools:context="cn.edu.bzu.showproduct.MainActivity">
<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="商品名称"
android:inputType="textPersonName"/>
<EditText
android:id="@+id/balanceET"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="金额"
android:inputType="number"/>
<ImageView
android:onClick="add"
android:layout_width="30dp"
android:layout_height="32dp"
android:src="@drawable/input" />
</LinearLayout>
<ListView
android:id="@+id/accoutLV"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/addLL">
</ListView>
</LinearLayout>
(2)ListView Item 布局(item.xml)
用到了ListView布局,故要编写一个ListView itemd的布局。在res/layout目录下建一个item.xml文件,该文件有三个TextView文本控件,分别用于显示数据库中的某条数据的id、商品名称、金额和三个ImageView图片控件用于增加、减少金额,删除数据。例:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp">
<TextView
android:id="@+id/idTV"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="1"
android:textColor="@color/colorAccent"
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="@color/colorAccent"
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="@color/colorAccent"
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="18dp"
android:layout_height="18dp"
android:layout_marginBottom="2dp"
android:src="@drawable/up"/>
<ImageView
android:id="@+id/downIV"
android:layout_width="18dp"
android:layout_height="18dp"
android:src="@drawable/down"/>
</LinearLayout>
<ImageView
android:id="@+id/deleteIV"
android:layout_width="28dp"
android:layout_height="40dp"
android:src="@drawable/delete"/>
</LinearLayout>
3.创建数据库
数据库操作,在cn.itcast.product的包下创建一个名为dao 的包并在其下定义一个MyHelp类继承自SQLiteOpenHelper,代码如下:
public class MyHelper extends SQLiteOpenHelper {
public MyHelper(Context context){
super (context,"itcast.db",null ,2);
}
public void onCreate(SQLiteDatabase db){
System.out.println("onCreate");
db.execSQL("CREATE TABLE account(_id INTEGER PRIMARY KEY AUTOINCREMENT,name VARCHAR(20),BALANCE INTEGER)");
}
public void onUpgrade(SQLiteDatabase db,int oldVersion,int newViersion){
System.out.println("onUpgrade");
}
}
4.Account类
该类主要是创建JavaBean对象,用来存放操作数据库时的数据。在cn.itcast.product创建一个bean包存放JavaBean类,然后在cn.itcast.product.bean包下定义一个类Accout,代码如下:
package cn.edu.bzu.showproduct.bean;
/**
* Created by Administrator on 2017/5/4.
*/
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 ();
}
public String toString(){
return "[序号:"+id+",商品名称:"+name+",余额:"+balance+"]";
}
}
5.创建数据操作逻辑类
在cn.itcast.product.dao包下建AccountDao类用于对数据进行增、删、改、查操作方法。
insert()方法中调用了db.insert()方法,这个方法第二个参数如果传入null,是无法插入一条空数据的,如果想插入一条空数据,第二个参数必须写一个列名,用来拼接SQL语句。
代码如下:
package cn.edu.bzu.showproduct.dao;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
import cn.edu.bzu.showproduct.bean.Account;
/**
* Created by Administrator on 2017/5/4.
*/
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();
}
public int delete(long id) {
SQLiteDatabase db = helper.getWritableDatabase();
int count = db.delete("account", "_id=?", new String[]{id + ""});
db.close();
return count;
}
public int update(Account account){
SQLiteDatabase db=helper.getWritableDatabase();
ContentValues valuse=new ContentValues();
valuse.put("name",account.getName());
valuse.put("balance",account.getBalance());
int count=db.update("account",valuse,"_id=?",new String[]{account.getId()+""});
db.close();
return count;
}
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;
}
}
6.编写界面交互代码
数据库的操作完成之后需要界面与数据库进行交互,用于实现将数据库中的数据以ListView的形式展示在界面上,代码如下:
package cn.edu.bzu.showproduct;
import android.content.DialogInterface;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.AdapterView;
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.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import org.w3c.dom.Text;
import java.util.List;
import cn.edu.bzu.showproduct.R;
import cn.edu.bzu.showproduct.bean.Account;
import cn.edu.bzu.showproduct.dao.AccountDao;
import cn.edu.bzu.showproduct.dao.MyHelper;
public class MainActivity extends AppCompatActivity {
private List<Account> list;
private AccountDao dao;
private EditText nameET;
private EditText balanceET;
private MyAdapter adapter;
private ListView accountLV;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
dao = new AccountDao(this );
list = dao.queryAll();
adapter = new MyAdapter();
accountLV.setAdapter(adapter);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this ).addApi(AppIndex.API).build();
}
private void initView() {
accountLV = (ListView) findViewById(R.id.accoutLV);
nameET = (EditText) findViewById(R.id.nameET);
balanceET = (EditText) findViewById(R.id.balanceET);
accountLV.setOnItemClickListener((AdapterView.OnItemClickListener) new MyOnItemClickListener());
}
public void add(View v) {
String name = nameET.getText().toString().trim();
String balance = balanceET.getText().toString().trim();
Account a = new Account(name, balance.equals("") ? 0 : Integer.parseInt(balance));
dao.insert(a);
list.add(a);
adapter.notifyDataSetChanged();
accountLV.setSelection(accountLV.getCount() - 1);
nameET.setText("");
balanceET.setText("");
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Main Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
@Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
@Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
private class MyAdapter extends BaseAdapter {
public int getCount() {
return list.size();
}
public Object getItem(int position) {
return list.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View item = convertView != null ? convertView : View.inflate(getApplicationContext(), R.layout.item, null );
TextView idTV = (TextView) item.findViewById(R.id.idTV);
TextView nameTV = (TextView) item.findViewById(R.id.nameTV);
TextView balanceTV = (TextView) item.findViewById(R.id.balanceTV);
final Account a = list.get(position);
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);
upIV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
a.setBalance(a.getBalance() + 1);
notifyDataSetChanged();
dao.update(a);
}
});
downIV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
a.setBalance(a.getBalance() - 1);
notifyDataSetChanged();
dao.update(a);
}
});
deleteIV.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
list.remove(a);
dao.delete(a.getId());
notifyDataSetChanged();
}
};
Builder builder = new Builder(MainActivity.this);
builder.setTitle("确定要删除吗?");
builder.setPositiveButton("确定", listener);
builder.setNegativeButton("取消", null );
builder.show();
}
});
return item;
}
}
private class MyOnItemClickListener implements DialogInterface.OnClickListener {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Account a = (Account) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), a.toString(), Toast.LENGTH_SHORT).show();
}
}
}
7.运行程序
(1)“商品展示”界面;
(2)在提示“商品名称”和“金额”上的文本框中输入姓名和金额后单击“添加”按钮,添加数据至数据库并显示适配器到ListView中;
(3)单击条目的向上按钮,对应的金额将会增加,单击向下按钮,金额会减少;
(4)单击删除按钮,会弹出一个对话框,单击对话框的确认按钮就将第二条数据删除了;
(5)单击条目会弹出一个Toast,要实现该功能需要给ListView的item设置条目点击监听事件。
————————————————
版权声明:本文为CSDN博主「huilang_ai」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/huilang_ai/article/details/71158485
程序猿的技术大观园:www.javathinker.net
网站系统异常
系统异常信息
Request URL:
http://www.javathinker.net/WEB-INF/lybbs/jsp/topic.jsp?postID=1427&pages=9
java.lang.NullPointerException
如果你不知道错误发生的原因,请把上面完整的信息提交给本站管理人员 。