The mobile terminal Course Design - campus secondary trading Amoy APP

Amoy campus secondary trading APP

Each lesson is provided an opportunity to progress!

During the course set up, I learned some never before been exposed to knowledge, such as how to generate verification codes, how to use Tencent open platform to register and get APP ID and APP KEY achieve QQ Internet access, drop-down lists, and how to achieve Spinner implement its click event, how to implement SQLite database CRUD and view the db files through a graphical tool for SQLite Expert Professional explicit view the data, how to transfer Intent complex data, how to use the Log to track app running, these should be my greatest achievement this time.
Here Insert Picture Description
First, the overall design ideas

By today's large platform of the Internet, taking into account the efficiency and safety of students on campus secondary trading, the use of Android knowledge learned so far designed this APP. The main system is divided into the following modules: User login authorization module, with user registration (user name and password set), login authentication (including authentication username, password and verification code), third party authorization function; commodity classification module, will have all kinds of goods categories of functions; selling module, presented in tabular form, click on each sub-list will show the specific release of information, you can use a star rating bar to rate and comment; release of goods module, add text with function, publish specific product information; personal management module, have modified and saved personal information, change passwords, view my release, Log function; my release module, with my Ads management function, you can manually refresh and delete operations.

Second, process analysis system
Here Insert Picture Description
3. Each module function analysis and design
Here Insert Picture Description
IV detailed design and implementation

1, database design

Need to learn can refer to: add a linker script

SQLite using graphical tools SQLite Expert Professional View db file
contains three tables: the user information users list, product information iteminfo table, table Comment comments.
(1) User information users table, this table can be defined by the basic information of each user stored in the database. Use Module: User login authorization module, registration module and personal information management module. Represented by the seven fields are user userId (account), passWord (password), name (real name), subject (the profession), phone (Contact), qq (qq number) and address (address). Wherein a primary key userId, passWord, not empty, as shown:
Here Insert Picture Description
build script (Based on the SQLite database), as follows:

db.execSQL("create table if not exists users" +
        "(userId varchar(20) primary key," +
        "passWord varchar(20) not null," +
        "name varchar(20)," +
        "subject varchar(20)," +
        "phone varchar(15)," +
        "qq varchar(15)," +
        "address varchar(50))");

(2) product information iteminfo table, this table can be defined by a list of items for each product to be released basic information stored in the database. Use modules: Module hot commodity, commodity classification module, merchandise information publishing module and my release management module. Commodity information represented by eight fields are id (product number), userId (publisher ID), title (title), kind (category), info (description), price (the price), time (Time) and contact ( contact details). Wherein a primary key id, as shown in FIG:
Here Insert Picture Description
build script (Based on SQLite database), as follows:

db.execSQL("create table if not exists iteminfo(" +
        "id integer primary key  AUTOINCREMENT," +
        "userId varchar(100)," +
        "title varchar(200)," +
        "kind varchar(100)," +
        "info varchar(1000)," +
        "price varchar(100)," +
        "time DATETIME," +
        "contact varchar(50))");

(3) review the comments table information, through the basic information for each comment table stored in the database can be defined. Use modules: Module product reviews. With five field represents userId (commentators ID), itemId (list item ID), comment (comment), textView (Article scoring star rating) and time (review time) respectively. The primary key is not provided, as shown in FIG:
Here Insert Picture Description
build script (based SQLite database implementation), as follows:

db.execSQL("create table if not exists comments(" +
        "userId varchar(100)," +
        "itemId integer," +
        "comment varchar(1000)," +
        "textView varchar(100),"+
        "time DATETIME)");

2, the design and implementation of an interface (I like to do the interface hhh)

This is my little cute APP icon!
Here Insert Picture Description
<1> Welcome Screen
Here Insert Picture Description
<2> login page
Here Insert Picture Description
<3> Third-party authorization interface -QQ
Here Insert Picture Description
<4> Registration Interface
Here Insert Picture Description
<5> main interface - Home
Here Insert Picture Description
<6> Goods publish interface
Here Insert Picture Description
<7> My publish interface
Here Insert Picture Description
<8> Categories interface - Books (beauty, electronics, sporting goods empathy)
Here Insert Picture Description
<9> reviews interface
Here Insert Picture Description
<10> personal Center interface
Here Insert Picture Description
<11> personal information interface
Here Insert Picture Description
<12> Change password interface
Here Insert Picture Description
3, the main function module implementation

(As more code below to record only important function)

<1> User login authorization module
Here Insert Picture Description

//将所输入的用户名和密码与数据库中的数据进行比较判断是否能够登陆成功
private void checkUser(String user, String password) {
    dbhelper = new DBOpenHelper(this);
    db=dbhelper.getReadableDatabase();
    try{
        String sql="SELECT * FROM users WHERE userId=? and passWord=?";
        Cursor cursor=db.rawQuery(sql,new String[]{user,password});
        if(cursor.getCount()==0){
            Toast.makeText(getApplicationContext(), "用户名或密码错误!", Toast.LENGTH_SHORT).show();
        }
        else{
            Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(LoginActivity.this,MainActivity.class);
            post_userid=user;
            startActivity(intent);
        }
        cursor.close();
        db.close();
    }catch (SQLiteException e){
        Toast.makeText(getApplicationContext(), "登录失败", Toast.LENGTH_SHORT).show();
    }
}
//注册验证
    if (!TextUtils.isEmpty(user) && !TextUtils.isEmpty(password1) &&  !TextUtils.isEmpty(password2) && password1.equals(password2)&& phoneCode.equals(realCode)) {
        checkUser(user, password1);
    }else if(user==null||user.equals("")){
        Toast.makeText(getApplicationContext(), "请输入用户账号!", Toast.LENGTH_SHORT).show();
    }else if(password1==null||password1.equals("")){
        Toast.makeText(getApplicationContext(), "请输入密码!", Toast.LENGTH_SHORT).show();
    }else if(!password1.equals(password2)){
        Toast.makeText(getApplicationContext(), "两次输入的密码不一致!", Toast.LENGTH_SHORT).show();
    } else if(!phoneCode.equals(realCode)){
    Toast.makeText(RegisterActivity.this, "验证码错误", Toast.LENGTH_SHORT).show();
    mIvRegisteractivityShowcode.setImageBitmap(Code.getInstance().createBitmap());
    realCode = Code.getInstance().getCode().toLowerCase();
    Log.i(TAG,"realCode为"+realCode);
}
//检查账号是否存在
private void checkUser(String user, String password1) {
    dbhelper = new DBOpenHelper(this);
    db=dbhelper.getReadableDatabase();
    try{
        String sql="SELECT * FROM users WHERE userId=?";
        Cursor cursor=db.rawQuery(sql,new String[]{user});
        if(cursor.getCount()>0){
            Toast.makeText(getApplicationContext(), "账号已存在!", Toast.LENGTH_SHORT).show();
        }
        else{
            ContentValues values = new ContentValues();
            //开始组装第一条数据   
	 //账号userId,密码passWord,姓名name,专业subject,电话phone,QQ号qq,地址address
            values.put("userId",user);
            values.put("passWord",password1);
            db.insert("users",null,values);//插入第一条数据
            Toast.makeText(getApplicationContext(), "注册成功,请登录", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(RegisterActivity.this,LoginActivity.class);
            startActivity(intent);
        }
        cursor.close();
        db.close();
    }catch (SQLiteException e){
        Toast.makeText(getApplicationContext(), "注册失败", Toast.LENGTH_SHORT).show();
    }
}

Authorized third parties to achieve QQ login qqActivity categories:

Reference may need to learn: Android to achieve third-party QQ login

public class qqActivity extends AppCompatActivity {

    //QQ登录申请的appid
    public static final String QQ_APP_ID = "1110228647";
    //布局控件
    private Button btnLogIn;
    private ImageView headerLogo;
    private TextView tvNickName;
    private TextView openId;

    //显示获取到的头像和昵称
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {//获取昵称
                tvNickName.setText((CharSequence) msg.obj);//String实现了CharSequence接口
            } else if (msg.what == 1) {//获取头像
                headerLogo.setImageBitmap((Bitmap) msg.obj);
            }
        }
    };

    //需要腾讯提供的一个Tencent类
    private Tencent mTencent;
    //还需要一个IUiListener 的实现类(LogInListener implements IUiListener)
    private LogInListener mListener;

    //用来判断当前是否已经授权登录,若为false,点击登录button时进入授权,否则注销
    private boolean isLogIned = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qq);

        //首先需要用APP ID 获取到一个Tencent实例
        //Tencent类是SDK的主要实现类,开发者可通过Tencent类访问开放的OpenAPI
        mTencent = Tencent.createInstance(QQ_APP_ID, this.getApplicationContext());

        //初始化一个IUiListener对象,在IUiListener接口的回调方法中获取到有关授权的某些信息
        // (需要覆写onActivityResult方法,成功接收到回调)
        mListener = new LogInListener();
        //初始化各控件
        initView();
    }

    private void initView() {
        btnLogIn = (Button) findViewById(R.id.mainQQ_btn_login);
        headerLogo = (ImageView) findViewById(R.id.mainQQ_iv_user_logo);
        tvNickName = (TextView) findViewById(R.id.mainQQ_tv_user_nickname);
        openId = (TextView) findViewById(R.id.mainQQ_tv_user_openid);

        btnLogIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isLogIned) {
                    isLogIned = true;
                    //调用QQ登录,用IUiListener对象作参数
                    if (!mTencent.isSessionValid()) {
                        mTencent.login(qqActivity.this, "all", mListener);
                    }
                } else {
                    //调用QQ注销接口
                    mTencent.logout(qqActivity.this);
                    isLogIned = false;
                    Toast.makeText(qqActivity.this, "登录已注销!", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    //LogInListener是IUiListener的实现类,其中的回调方法用来接收授权后的相关信息
    private class LogInListener implements IUiListener{
        @Override
        public void onComplete(Object o) {
            Toast.makeText(qqActivity.this, "授权成功!", Toast.LENGTH_LONG).show();
            System.out.println("o.toString() ------------------------->        " + o.toString());

            JSONObject jsonObject = (JSONObject) o;

            //设置openid和token,否则获取不到下面的信息
            initOpenidAndToken(jsonObject);
            //获取QQ用户的各信息
            getUserInfo();
        }

        @Override
        public void onError(UiError uiError) {

            Toast.makeText(qqActivity.this, "授权出错!", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onCancel() {
            Toast.makeText(qqActivity.this, "授权取消!", Toast.LENGTH_LONG).show();
        }
    }

    //登录成功后调用public void onComplete(JSONObject arg0) 回传的JsonObject, 其中包含OpenId, AccessToken等重要数据
    //{
    //"ret":0,
    //"pay_token":"xxxxxxxxxxxxxxxx",
    //"pf":"openmobile_android",
    //"expires_in":"7776000",
    //"openid":"xxxxxxxxxxxxxxxxxxx",
    //"pfkey":"xxxxxxxxxxxxxxxxxxx",
    //"msg":"sucess",
    //"access_token":"xxxxxxxxxxxxxxxxxxxxx"
    //}
    //初始化OPENID和TOKEN值(为了得到用户信息)
    private void initOpenidAndToken(JSONObject jsonObject) {
        try {
            String openid = jsonObject.getString("openid");
            openId.setText(openid);
            String token = jsonObject.getString("access_token");
            String expires = jsonObject.getString("expires_in");

            if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(expires)
                    && !TextUtils.isEmpty(openid)) {
                mTencent.setAccessToken(token, expires);
                mTencent.setOpenId(openid);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    //sdk给我们提供了一个类UserInfo,这个类中封装了QQ用户的一些信息,我们可以通过这个类拿到这些信息
    //采用同步调用方式(由于同步调用直接访问网络,是延时性操作,需要放入线程中执行)
    private void getUserInfo() {
        QQToken mQQToken = mTencent.getQQToken();
        UserInfo userInfo = new UserInfo(qqActivity.this, mQQToken);
        userInfo.getUserInfo(new IUiListener() {
                                 @Override
                                 public void onComplete(final Object o) {
                                     JSONObject userInfoJson = (JSONObject) o;
                                     //                {
//                        "ret": 0,
//                        "msg": "",
//                        "is_lost": 0,
//                        "nickname": "维他命",
//                        "gender": "女",
//                        "province": "天津",
//                        "city": "滨海新区",
//                        "figureurl": "http://qzapp.qlogo.cn/qzapp/1110228647/CB74B8982DFC8EB1ABE233BAF946435B/30",
//                        "figureurl_1": "http://qzapp.qlogo.cn/qzapp/1110228647/CB74B8982DFC8EB1ABE233BAF946435B/50",
//                        "figureurl_2": "http://qzapp.qlogo.cn/qzapp/1110228647/CB74B8982DFC8EB1ABE233BAF946435B/100",
//                        "figureurl_qq_1": "http://q.qlogo.cn/qqapp/1110228647/CB74B8982DFC8EB1ABE233BAF946435B/40",
//                        "figureurl_qq_2": "http://q.qlogo.cn/qqapp/1110228647/CB74B8982DFC8EB1ABE233BAF946435B/100",
//                        "is_yellow_vip": "0",
//                        "vip": "0",
//                        "yellow_vip_level": "0",
//                        "level": "0",
//                        "is_yellow_year_vip": "0"
//                }
                                     Message msgNick = new Message();
                                     msgNick.what = 0;//昵称
                                     try {
                                         msgNick.obj = userInfoJson.getString("nickname");//直接传递一个昵称的内容过去
                                     } catch (JSONException e) {
                                         e.printStackTrace();
                                     }
                                     mHandler.sendMessage(msgNick);
                                     //子线程 获取并传递头像图片,由Handler更新
                                     new Thread(new Runnable() {
                                         @Override
                                         public void run() {
                                             Bitmap bitmapHead = null;
                                             if (((JSONObject) o).has("figureurl")) {
                                                 try {
                                                     String headUrl = ((JSONObject) o).getString("figureurl_qq_2");
                                                     bitmapHead = Util.getbitmap(headUrl);

                                                 } catch (JSONException e) {
                                                     e.printStackTrace();
                                                 }
                                                 Message msgHead = new Message();
                                                 msgHead.what = 1;
                                                 msgHead.obj = bitmapHead;
                                                 mHandler.sendMessage(msgHead);

                                             }
                                         }
                                     }).start();

                                      btnLogIn.setOnClickListener(new View.OnClickListener() {
                                          @Override
                                          public void onClick(View v) {
                                              startActivity(new Intent(qqActivity.this,MainActivity.class));
                                              finish();
                                          }
                                      });

                                 }

                                 @Override
                                 public void onError(UiError uiError) {
                                     Log.e("GET_QQ_INFO_ERROR", "获取qq用户信息错误");
                                     Toast.makeText(qqActivity.this, "获取qq用户信息错误", Toast.LENGTH_SHORT).show();
                                 }

                                 @Override
                                 public void onCancel() {
                                     Log.e("GET_QQ_INFO_CANCEL", "获取qq用户信息取消");
                                     Toast.makeText(qqActivity.this, "获取qq用户信息取消", Toast.LENGTH_SHORT).show();
                                 }
                             }
        );
    }


    //确保能接收到回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Tencent.onActivityResultData(requestCode, resultCode, data, mListener);
    }
}

Util custom classes as follows:

public class Util {
    public static String TAG="UTIL";
    public static Bitmap getbitmap(String imageUri) {
        Log.v(TAG, "getbitmap:" + imageUri);
        // 显示网络上的图片
        Bitmap bitmap = null;
        try {
            URL myFileUrl = new URL(imageUri);
            HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
            conn.setDoInput(true);
            conn.connect();

            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();

            Log.v(TAG, "image download finished." + imageUri);
        } catch (IOException e) {
            e.printStackTrace();
            Log.v(TAG, "getbitmap bmp fail---");
            return null;
        }
        return bitmap;
    }

}

<2> hot commodity module
Here Insert Picture Description

//打开数据表iteminfo查询所有数据,然后将一组数据存放在一个Map里,各组数据存放在一个ArrayList里
dbHelper = new DBOpenHelper(this);
db = dbHelper.getWritableDatabase();//打开数据库
data = new ArrayList<>(); // 列表
Cursor cursor = db.query(TABLENAME,null,null,null,null,null,null,null); // 数据库查询
if (cursor.moveToFirst()){
    while (!cursor.isAfterLast()){
        item = new HashMap<String, Object>();  // 为列表项赋值
        item.put("id",cursor.getInt(0));
        item.put("userid",cursor.getString(1));
        item.put("title",cursor.getString(2));
        item.put("kind",cursor.getString(3));
        item.put("info",cursor.getString(4));
        item.put("price",cursor.getString(5));
        cursor.moveToNext();
        data.add(item); // 加入到列表中
    }
}

// 使用MydefineAdapter布局listview
MydefineAdapter mydefineAdapter = new MydefineAdapter(this,R.layout.listitem,data);
listview.setAdapter(mydefineAdapter);
// 为列表项设置监听器
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        intent = new Intent(MainActivity.this, item_info.class);
        // 获取该列表项的key为id的键值,即商品的id,将其储存在Bundle传递给打开的页面
        intent.putExtra("id", data.get(position).get("id").toString()); 
        startActivity(intent);
    }
});

/*自定义适配器需继承BaseAdapter,并重写其四个方法*/
public class MydefineAdapter extends BaseAdapter {
    private Context context;
    private ArrayList<Map<String,Object>> data;
    private int item_layout_id;

    public MydefineAdapter(Context context,int item_layout_id,ArrayList<Map<String,Object>> data){
        this.context=context;
        this.data=data;
        this.item_layout_id=item_layout_id;
    }
    //返回适配器要包含的数据项数量
    @Override
    public int getCount() {
        return data.size();
    }
    //返回数据集中position位置的数据对象(从0开始)
    @Override
    public Object getItem(int position) {
        return data.get(position);
    }
    //返回position位置的列表项的ID
    @Override
    public long getItemId(int position) {
        return position;
    }
    //返回position位置的绑定数据后的视图组件,其中convertview表示缓冲绘制好的视图组件,parent是convertview的父视图
    //使用view参数作为缓存进行优化,减少了重绘view的次数
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder=null;//声明缓存布局中所有视图组件的对象引用
        //判断有无可重用的View,若无就重新绘制
        if(convertView==null){
            viewHolder=new ViewHolder();
            //LayoutInflater的作用是,将xml布局文件实例化为它对应的View对象
            convertView= LayoutInflater.from(context).inflate(item_layout_id,parent,false);
            viewHolder.title=(TextView) convertView.findViewById(R.id.title);
            viewHolder.kind=(TextView)convertView.findViewById(R.id.kind);
            viewHolder.info=(TextView)convertView.findViewById(R.id.info);
            viewHolder.price=(TextView)convertView.findViewById(R.id.price);
            convertView.setTag(viewHolder);//为view设置标签并把viewHolder存储在标签中
        }else{
            viewHolder=(ViewHolder)convertView.getTag();
        }
        Map<String,Object>item=(Map<String, Object>) getItem(position);
        viewHolder.title.setText((String)item.get("title"));
        viewHolder.kind.setText((String)item.get("kind"));
        viewHolder.info.setText((String)item.get("info"));
        viewHolder.price.setText((String)item.get("price"));
        return convertView;
    }
    //定义内部类ViewHolder减少调用findViewById
    private class ViewHolder{
        public TextView title;
        public TextView kind;
        public TextView info;
        public TextView price;
    }
}
//接收从上一个intent传递过来的id,把通过这个id在数据表iteminfo中查询的信息赋给相应的布局控件
dhelper = new DBOpenHelper(this);
db = dhelper.getWritableDatabase();
intent = getIntent();
initview();
Cursor cursor = db.query("iteminfo",null,"id=?",new String[]{intent.getStringExtra("id")},null,null,null,null); // 根据接收到的id进行数据库查询
Log.i("商品的id是",intent.getStringExtra("id"));
if (cursor.moveToFirst()){
    while (!cursor.isAfterLast()){
        userId.setText(cursor.getString(1));
        title.setText(cursor.getString(2));
        price.setText(cursor.getString(5));
        time.setText(cursor.getString(6));
        info.setText(cursor.getString(4));
        contact.setText(cursor.getString(7));
        cursor.moveToNext();
    }
}
//接收从上一个intent传递过来的id,通过这个id在数据库里查询到的每一组数据存储在一个Map里,然后把所有组数据存储到一个List里
data=new ArrayList<Map<String, Object>>(); // 列表
Cursor cursor_ = db.query("comments",null,"itemId=?",new String[]{intent.getStringExtra("id")},null,null,null,null); // 数据库查询
if (cursor_.moveToFirst()){
    while (!cursor_.isAfterLast()){
        item = new HashMap<String, Object>();  // 为列表项赋值
        item.put("userId",cursor_.getString(0));
        item.put("comment",cursor_.getString(2));
        item.put("textView",cursor_.getString(3));
        item.put("time",cursor_.getString(4));
        cursor_.moveToNext();
        data.add(item); // 加入到列表中
    }
}
/*创建RatingBar监听器 */
chooseRatingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
    @Override
    public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
        chooseRatingBar = (RatingBar) findViewById(R.id.ratingBar1);
        chooseRatingBar.setRating(rating);
        textView.setText("选择了" + rating + "个星星");
    }
});
//给提交评论按钮设置事件监听器
Button submit = (Button)findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        EditText comment = (EditText)findViewById(R.id.comment);
        String submit_comment = comment.getText().toString();
        TextView textView= (TextView) findViewById(R.id.textView1);
        String star_textview=textView.getText().toString();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss ");
        Date curDate = new Date(System.currentTimeMillis());
        String time = formatter.format(curDate);
        ContentValues values=new ContentValues();
        values.put("userId",post_userid);
        values.put("itemId",intent.getStringExtra("id"));
        values.put("comment",submit_comment);
        values.put("textView",star_textview);
        values.put("time",time);
        db.insert("comments",null,values);
        Log.i("1","评论成功");
        Toast.makeText(getApplicationContext(), "评论成功", Toast.LENGTH_SHORT).show();
        Intent intent_=new Intent(item_info.this,item_info.class);
        intent_.putExtra("id",intent.getStringExtra("id"));
        startActivity(intent_);
    }
});

<3> commodity classification module release +
Here Insert Picture Description

String[] ctype;
ctype = new String[]{"美妆", "书籍", "电子产品", "体育用品"};
//创建一个数组适配器
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,ctype);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); //设置下拉列表框的下拉选项样式
sp= (Spinner) super.findViewById(R.id.m1_style);
sp.setAdapter(adapter);//将适配器添加到下拉列表上
sp.setOnItemSelectedListener(this);
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    kind = (sp.getSelectedItem()).toString();
}
public void onNothingSelected(AdapterView<?> parent) {
}
//给发布按钮添加事件监听器
fabu.setOnClickListener(new View.OnClickListener() {
    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onClick(View v) {
        EditText title=(EditText)findViewById(R.id.m1_title);
        EditText price=(EditText)findViewById(R.id.m1_price);
        EditText phone=(EditText)findViewById(R.id.m1_phone);
        EditText nr=(EditText)findViewById(R.id.m1_nr);
        Date curDate = new Date(System.currentTimeMillis());
        String time = formatter.format(curDate);
        ContentValues values=new ContentValues();
        values.put("title",title.getText().toString());
        values.put("userId",post_userid);
        values.put("kind", kind);
        values.put("time",time);
        values.put("price",price.getText().toString());
        values.put("contact",phone.getText().toString());
        values.put("info",nr.getText().toString());
        db.insert("iteminfo",null,values);
        Intent intent=new Intent(AddItem.this,AddItem.class);
        Toast.makeText(getApplicationContext(), "发布成功", Toast.LENGTH_SHORT).show();
        startActivity(intent);
        finish();
    }
});
//将在数据库中查找的类别是“美妆”的每组数据组装成一个Map,再将所有数据存储在List里面(书籍类,电子产品类,体育用品类同理)
dbHelper = new DBOpenHelper(this);
db = dbHelper.getWritableDatabase();
item = new HashMap<>();
data = new ArrayList<>();
Cursor cursor = db.query(TABLENAME,null,"kind=?",new String[]{"美妆"},null,null,null,null); // 数据库查询
if (cursor.moveToFirst()){
    while (!cursor.isAfterLast()){
        item = new HashMap<String, Object>();  // 为列表项赋值
        item.put("id",cursor.getInt(0));
        item.put("userid",cursor.getString(1));
        item.put("title",cursor.getString(2));
        item.put("kind",cursor.getString(3));
        item.put("info",cursor.getString(4));
        item.put("price",cursor.getString(5));
        cursor.moveToNext();
        data.add(item); // 加入到列表中
    }
}

<4> + My personal center management release management module
Here Insert Picture Description

//获取登录时的账户账号,也就是发布者的账号,通过该账号在数据库中查询发布的商品信息
Cursor cursor = db.query(TABLENAME,null,"userId=?",new String[]{a},null,null,null,null); // 数据库查询
if (cursor.moveToFirst()){
    while (!cursor.isAfterLast()){
        item = new HashMap<String, Object>();  // 为列表项赋值
        item.put("id",cursor.getInt(0));
        item.put("userId",cursor.getString(1));
        item.put("title",cursor.getString(2));
        item.put("kind",cursor.getString(3));
        item.put("info",cursor.getString(4));
        item.put("price",cursor.getString(5));
        cursor.moveToNext();
        data.add(item); // 加入到列表中
    }
}
//长按可删除该列表项的监听器
listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        String delId = data.get(position).get("id").toString();
        if(db.delete(TABLENAME,"id=?",new String[]{delId}) > 0) {
            Toast.makeText(getApplicationContext(), "删除成功,请刷新", Toast.LENGTH_SHORT).show();
            return true;
        }
        else {
            return false;
        }
    }
});
//保存修改过后的信息,将数据库中的信息更新
private void saveValues(ContentValues values) {
    DBOpenHelper dbhelper = new DBOpenHelper(this);
    SQLiteDatabase db=dbhelper.getReadableDatabase();
    db.update("users",values,"userId=?",new String[] {id});
    db.close();
}
//验证用户旧密码是否输入正确,将新密码存入数据库
private void checkpass(String oldpass, String newpass) {
    DBOpenHelper dbhelper = new DBOpenHelper(this);
    SQLiteDatabase db=dbhelper.getReadableDatabase();
    try{
        String sql="SELECT * FROM users WHERE userId=? and passWord=?";
        Cursor cursor=db.rawQuery(sql,new String[]{user,oldpass});
        if(cursor.getCount()==0){
            Toast.makeText(getApplicationContext(), "用户旧密码错误!", Toast.LENGTH_SHORT).show();
        }
        else{
            ContentValues values=new ContentValues();
            values.put("passWord",newpass);
            db.update("users",values,"userId=?",new String[] {user});
            Toast.makeText(getApplicationContext(), "修改成功", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(changepwdActivity.this,MyselfActivity.class);
            startActivity(intent);
        }
        cursor.close();
        db.close();
    }catch (SQLiteException e){
        Toast.makeText(getApplicationContext(), "修改失败", Toast.LENGTH_SHORT).show();
    }
}

fighting together!

Source download
Here Insert Picture Description

Released four original articles · won praise 2 · Views 111

Guess you like

Origin blog.csdn.net/weixin_45145550/article/details/104802416