AndroidStudio创建SQLite存储商品信息 AS第5章实验 - 小浣熊博客

AndroidStudio创建SQLite存储商品信息 AS第5章实验

发布者: 小浣熊

全网最全的网络资源分享网站

手机扫码查看

特别声明:文章多为网络转载,资源使用一般不提供任何帮助,特殊资源除外,如有侵权请联系!

这篇文章总字数为:13515 字,有 0 张图存于本站服务器

导语:

“该教程初次发布于4.26,最初版本没有标题栏,4.27搞出来标题栏发布了最终版,还算完美”

首先这是一个作业,也可以当作AS创建SQLite教程。

这次实验是创建SQLite数据库存储商品信息数据,通过手机客户端的操作,实现对创建的数据表进行增加商品,查询商品,修改商品信息和删除商品的功能。

修改商品数据

删除商品数据

增加商品数据(点击右上角三个点呼出)

查询商品数据点击右上角三个点呼出)

Tips:本次实验不是自己打的代码,是从某种途径获取到的王莉同学作业,起初因为sdk版本和gradle版本不匹配种种原因运行频频报错,经过自己一番学习,弄明白了这个实验并成功运行,这里表示感谢大佬王莉同学的源代码。

我整理了一下这个实验,只要按照下面步骤做就不会掉我掉过的坑。

必要文件:

首先了解一下这12个必要的java和xml文件,等会不要漏项。

如果你懒得分步看下面源代码的话,直接看这个视频教程吧,把实验先拿到手再学习精髓!

Tips:看视频前请先到文章底部下载项目源代码包,解压到桌面,再把项目拷贝到你AndroidStudio项目目录,按视频操作即可。

视频教程:(5分19秒)

 

想自己一步一步琢磨的来看下面分解动作!

记得把所有包名换成自己的否则编译失败!如果你不知道哪个是包名,请看上一个AS实验“AndroidStudio之xml解析天气预报

分解源代码:

需要注意下面文件路径提到的“第一个包名”是指MainActivity所在的包,新建项目默认自动创建了,如图所示

MainActivity.java文件:(路径:app/java/第一个包名/)

package com.open_open.pingshuai17180074;
import android.app.AlertDialog.Builder;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.SimpleAdapter;
import com.open_open.pingshuai17180074.database.SQLHelper;
import java.util.HashMap;
public class MainActivity extends ListActivity {
    SQLHelper mydb = new SQLHelper(this);
    ;
    Context context = this;
    private int MenuId1 = Menu.FIRST;
    private int MenuId2 = Menu.FIRST + 1;
    String pid;
    View editView;
    View searchView;
    View addView;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        showList("select * from info1");
        getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
            public boolean onItemLongClick(AdapterView<?> views, View view,
                                           int p, long arg3) {
                HashMap<String, Object> hm = (HashMap<String, Object>) views.getItemAtPosition(p);
                pid = hm.get("pid").toString();
                return false;
            }
        });
        registerForContextMenu(getListView());

    }

    public void showList(String sql) {
        SimpleAdapter adp = new SimpleAdapter(context, mydb.show(sql, new String[]{}),
                R.layout.list, new String[]{"pid", "name", "price"}, new int[]{R.id.data_id, R.id.phone_name, R.id.price});
        getListView().setAdapter(adp);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        if (item.getItemId() == MenuId1) {
            String sql = "delete from info1 where pid=?";
            mydb.executeSql(sql, new String[]{pid});
            showList("select * from info1");
        } else if (item.getItemId() == MenuId2) {
            Builder builder = new Builder(context);
            LayoutInflater inf = getLayoutInflater();
            editView = inf.inflate(R.layout.activity_edit, (ViewGroup) findViewById(R.id.activity_edit));
            builder.setView(editView);
            Cursor cur = mydb.getReadableDatabase().rawQuery("select * from info1 where pid=?", new String[]{pid});
            cur.moveToNext();
            String name = cur.getString(1);
            String pprice = cur.getString(2);
            EditText et1 = (EditText) editView.findViewById(R.id.updpnamet);
            EditText et2 = (EditText) editView.findViewById(R.id.updpriceet);
            et1.setText(name);
            et2.setText(pprice);
            builder.setPositiveButton("修改", new OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    EditText et1 = (EditText) editView.findViewById(R.id.updpnamet);
                    EditText et2 = (EditText) editView.findViewById(R.id.updpriceet);
                    String name = et1.getText().toString();
                    String pprice = et2.getText().toString();
                    String sql = "update info1 set name=?,price=? where pid=?";
                    mydb.executeSql(sql, new String[]{name, pprice, pid});
                    showList("select * from info1");
                }
            });
            builder.setNegativeButton("取消", new OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                }
            });
            builder.create().show();
        }
        return super.onContextItemSelected(item);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenuInfo menuInfo) {
        menu.add(1, MenuId1, 1, "删除");
        menu.add(1, MenuId2, 2, "修改");
        super.onCreateContextMenu(menu, v, menuInfo);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(1, 99, 1, "增加");
        menu.add(1, 98, 2, "查询");
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        if (item.getItemId() == 99) {
            Builder builder = new Builder(context);
            LayoutInflater inf = getLayoutInflater();
            addView = inf.inflate(R.layout.add, (ViewGroup) findViewById(R.id.addayout));
            builder.setView(addView);
            builder.setPositiveButton("增加", new OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    EditText et1 = (EditText) addView.findViewById(R.id.addpnamet);
                    EditText et2 = (EditText) addView.findViewById(R.id.addpriceet);
                    String pn = et1.getText().toString();
                    String pr = et2.getText().toString();
                    String sql = "insert into info1(name,price) values(?,?)";
                    mydb.executeSql(sql, new String[]{pn, pr});
                    showList("select * from info1");
                }
            });
            builder.setNegativeButton("取消", new OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                }
            });
            builder.create().show();
        } else if (item.getItemId() == 98) {
            Builder builder = new Builder(context);
            LayoutInflater inf = getLayoutInflater();
            searchView = inf.inflate(R.layout.search, (ViewGroup) findViewById(R.id.searchlayout));
            builder.setView(searchView);
            builder.setPositiveButton("查询", new OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    EditText et = (EditText) searchView.findViewById(R.id.unet_search);
                    String pn = et.getText().toString();
                    String sql = "select * from info1 where name ='" + pn + "'";
                    showList(sql);
                }
            });
            builder.setNegativeButton("取消", new OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    finish();

                }
            });
            builder.create().show();
        }
        return super.onMenuItemSelected(featureId, item);
    }

}

SQLHelper.java文件 :(路径:app/java/第一个包名/database/)

package com.open_open.pingshuai17180074.database;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.HashMap;
public class SQLHelper extends SQLiteOpenHelper {

    public SQLHelper(Context context) {
        super(context,"info1.db",null,1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table info1(pid integer primary key,name varchar(20),price double)");
        db.execSQL("insert into info1(name,price) values('iphone',3000)");
        db.execSQL("insert into info1(name,price) values('htc',3500)");
        db.execSQL("insert into info1(name,price) values('moto',4000)");
        db.execSQL("insert into info1(name,price) values('sangsung',4500)");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

    public void executeSql(String sql,String[] ps)
    {
        this.getWritableDatabase().execSQL(sql, ps);
    }
    public  ArrayList<HashMap<String, Object>> show(String sql,String[] ps)
    {
        ArrayList<HashMap<String, Object>> alist=new ArrayList<HashMap<String,Object>>();
        Cursor cur=this.getReadableDatabase().rawQuery(sql, ps);
        while(cur.moveToNext())
        {
            HashMap<String, Object> hm=new HashMap<String, Object>();
            hm.put("pid", cur.getString(0));
            hm.put("name", cur.getString(1));
            hm.put("price", cur.getString(2));
            alist.add(hm);
        }
        return alist;

    }
}

UpdatedActivity.java文件 :(路径:app/java/第一个包名/aesu/)

package com.open_open.pingshuai17180074.aesu;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
import com.open_open.pingshuai17180074.*;
import com.open_open.pingshuai17180074.R;
import com.open_open.pingshuai17180074.database.SQLHelper;

public class UpdatedActivity extends AppCompatActivity {

EditText et1;
EditText et2;
Button btn1;
Context context=this;
SQLHelper mydb;
String pid;
private void show()
{
Intent in=getIntent();
pid=in.getStringExtra("pid");
Cursor cur=mydb.getReadableDatabase().rawQuery("select * from info1 where pid=?", new String[]{pid});
cur.moveToNext();
String name=cur.getString(1);
String pprice=cur.getString(2);
et1=(EditText)findViewById(R.id.updpnamet);
et2=(EditText)findViewById(R.id.updpriceet);
et1.setText(name);
et2.setText(pprice);
}
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_edit);
super.onCreate(savedInstanceState);
mydb=new SQLHelper(context);
show();
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
et1=(EditText)findViewById(R.id.updpnamet);
et2=(EditText)findViewById(R.id.updpriceet);
String name=et1.getText().toString();
String pprice=et2.getText().toString();
String sql="insert into info1(name,price) values(?,?)";
mydb.executeSql(sql, new String[]{name,pprice});
Intent in1=new Intent();
in1.setClass(context, MainActivity.class);
startActivity(in1);
}
});
}
}

activity_edit.xml文件:(路径:app/res/layout/)

<?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_edit"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    >
    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:id="@+id/updpnamet"
        android:inputType="text"
        />
    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/updpriceet"
        android:layout_weight="1"
        android:inputType="number"
        />
</LinearLayout>

add.xml文件:(路径:app/res/layout/)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:id="@+id/addayout"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    >
    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:id="@+id/addpnamet"
        android:inputType="text"
        />
    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/addpriceet"
        android:layout_weight="1"
        android:inputType="number"
        />
</LinearLayout>

list.xml文件:(路径:app/res/layout/)

<?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="fill_parent"
    android:layout_height="fill_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    >
    <TextView
        android:id="@+id/data_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="30dp"
        android:textSize="18sp"
        android:textColor="#006699"
        />
    <TextView
        android:id="@+id/phone_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="40dp"
        android:textSize="18sp"
        android:textColor="#006699"
        />
    <TextView
        android:id="@+id/price"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:textColor="#006699"
        />
</LinearLayout>

list_item.xml文件:(路径:app/res/layout/)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
</LinearLayout>

search.xml文件:(路径:app/res/layout/)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/searchlayout"
    >
    <EditText
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:id="@+id/unet_search"
        android:inputType="text"
        />
</LinearLayout>

colors.xml文件:(路径:app/res/values/)

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
</resources>

dimens.xml文件:(路径:app/res/values/)

<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
</resources>

strings.xml文件:(路径:app/res/values/)记得改下面的学号姓名!!!

<resources>
    <string name="app_name">17180074pingshaui</string>
    <string name="jian">jian</string>
    <string name="add">add</string>
</resources>

styles.xml文件:(路径:app/res/values/)

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:windowActionBar">true</item>
        <item name="android:windowNoTitle">false</item>
    </style>
</resources>

一定要记得把包名换成自己的,还有记得检查app/Mainfests/目录下的AndroidManifest.xml文件有没有声明项目类MainActivity,因为我用的默认的MainActivity没改,所以我上面没给MainActivity.xml的代码,一般不会出问题。如果哪里有问题,点击右下角QQ通道,我帮你看看。

项目打包下载:

只输入QQ号,再输入评语就可以,不用输入其他项,系统自动获取其他信息。

本文最后更新于2020-4-26,已超过 1 年没有更新,如果文章内容或图片资源失效,请留言反馈,我们会及时处理,谢谢!
分享到:
打赏
-版权声明-

阅读时间:  发布于:2020-4-26
文章标题:《AndroidStudio创建SQLite存储商品信息 AS第5章实验》
本文链接:https://www.mua222.cn/post-74.html
本文编辑: 小浣熊,转载请注明超链接和出处小浣熊博客
收录状态:[百度已收录][360已收录][搜狗已收录]

评论

     快速回复: 支持 感谢 学习 不错 高兴 给力 加油 惊喜
  1. #23
    450游客 Lv.1  

  2. #22
    450游客 Lv.1  

  3. #21
    ah游客 Lv.1  

  4. #20
    6621游客 Lv.1  

  5. #19
    6621游客 Lv.1  

  6. #18
    6621游客 Lv.1  

  7. #17
    6621游客 Lv.1  

  8. #16
    4551游客 Lv.1  

  9. #15
    4551游客 Lv.1  

  10. #14
    +q游客 Lv.1  

切换注册

登录

忘记密码?

您也可以使用第三方帐号快捷登录

切换登录

注册

AndroidStudio创建SQLite存储商品信息 AS第5章实验

长按图片转发给朋友

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏