android apk的增删改查,以及下载进度控制

 

 1.安装下载下来的apk

String fileName = "/sdcard/TestB.apk";    
  Intent intent = new Intent(Intent.ACTION_VIEW); 
  intent.setDataAndType(Uri.parse("file://" +new File(fileName)),"application/vnd.android.package-archive"); 
  startActivity(intent);  

2、卸载apk
 private void startUninstall(final String pkg) {
  if (!InstallUtils.isApkInstalled(mContext, pkg)) {
   Toast.makeText(mContext, "程序未安装,无需卸载!", Toast.LENGTH_SHORT).show();
   return;
  } else {
   Uri packageURI = Uri.parse("package:" + pkg);
   Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
   startActivity(uninstallIntent);
  }
 }

3.更新apk
1. 准备知识
在AndroidManifest.xml里定义了每个Android apk的版本标识:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"

      package="com.myapp"

      android:versionCode="1"

      android:versionName="1.0.0">

<application></application>

</manifest>
复制代码
其中,android:versionCode和android:versionName两个字段分别表示版本代码,版本名称。versionCode是整型数字,versionName是字符串。由于version是给用户看的,不太容易比较大小,升级检查时,可以以检查versionCode为主,方便比较出版本的前后大小。
那么,在应用中如何读取AndroidManifest.xml中的versionCode和versionName呢?可以使用PackageManager的API,参考以下代码:
public static int getVerCode(Context context) {

        int verCode = -1;

        try {

            verCode = context.getPackageManager().getPackageInfo(

                    "com.myapp", 0).versionCode;

        } catch (NameNotFoundException e) {

            Log.e(TAG, e.getMessage());

        }

        return verCode;

    }

   

    public static String getVerName(Context context) {

        String verName = "";

        try {

            verName = context.getPackageManager().getPackageInfo(

                    "com.myapp", 0).versionName;

        } catch (NameNotFoundException e) {

            Log.e(TAG, e.getMessage());

        }

        return verName;   

}
复制代码或者在AndroidManifest中将android:versionName="1.2.0"写成android:versionName="@string/app_versionName",然后在values/strings.xml中添加对应字符串,这样实现之后,就可以使用如下代码获得版本名称:
public static String getVerName(Context context) {

        String verName = context.getResources()

        .getText(R.string.app_versionName).toString();

        return verName;

}
复制代码同理,apk的应用名称可以这样获得:
public static String getAppName(Context context) {

        String verName = context.getResources()

        .getText(R.string.app_name).toString();

        return verName;

}
复制代码2. 流程框架
165013oos7tlgx9uqshblb.gif

2012-1-8 01:56:27 上传
下载附件(11.16 KB)


3. 版本检查
在服务端放置最新版本的apk文件,如:http://localhost/myapp/myapp.apk
同时,在服务端放置对应此apk的版本信息调用接口或者文件,如:http://localhost/myapp/ver.json
ver.json中的内容为:
[{"appname":"jtapp12","apkname":"jtapp-12-updateapksamples.apk","verName":1.0.1,"verCode":2}]
复制代码
然后,在手机客户端上进行版本读取和检查:
private boolean getServerVer () {

        try {

            String verjson = NetworkTool.getContent(Config.UPDATE_SERVER

                    + Config.UPDATE_VERJSON);

            JSONArray array = new JSONArray(verjson);

            if (array.length() > 0) {

                JSONObject obj = array.getJSONObject(0);

                try {

                    newVerCode = Integer.parseInt(obj.getString("verCode"));

                    newVerName = obj.getString("verName");

                } catch (Exception e) {

                    newVerCode = -1;

                    newVerName = "";

                    return false;

                }

            }

        } catch (Exception e) {

            Log.e(TAG, e.getMessage());

            return false;

        }

        return true;

    }
复制代码比较服务器和客户端的版本,并进行更新操作。
   if (getServerVerCode()) {

            int vercode = Config.getVerCode(this); // 用到前面第一节写的方法

            if (newVerCode > vercode) {

                doNewVersionUpdate(); // 更新新版本

            } else {

                notNewVersionShow(); // 提示当前为最新版本

            }

        }        
复制代码详细方法:
private void notNewVersionShow() {

                int verCode = Config.getVerCode(this);

                String verName = Config.getVerName(this);

                StringBuffer sb = new StringBuffer();

                sb.append("当前版本:");

                sb.append(verName);

                sb.append(" Code:");

                sb.append(verCode);

                sb.append(",/n已是最新版,无需更新!");

                Dialog dialog = new AlertDialog.Builder(Update.this).setTitle("软件更新")

                                .setMessage(sb.toString())// 设置内容

                                .setPositiveButton("确定",// 设置确定按钮

                                                new DialogInterface.OnClickListener() {

                                                        @Override

                                                        public void onClick(DialogInterface dialog,

                                                                        int which) {

                                                                finish();

                                                        }

                                                }).create();// 创建

                // 显示对话框

                dialog.show();

        }

        private void doNewVersionUpdate() {

                int verCode = Config.getVerCode(this);

                String verName = Config.getVerName(this);

                StringBuffer sb = new StringBuffer();

                sb.append("当前版本:");

                sb.append(verName);

                sb.append(" Code:");

                sb.append(verCode);

                sb.append(", 发现新版本:");

                sb.append(newVerName);

                sb.append(" Code:");

                sb.append(newVerCode);

                sb.append(", 是否更新?");

                Dialog dialog = new AlertDialog.Builder(Update.this)

                                .setTitle("软件更新")

                                .setMessage(sb.toString())

                                // 设置内容

                                .setPositiveButton("更新",// 设置确定按钮

                                                new DialogInterface.OnClickListener() {

                                                        @Override

                                                        public void onClick(DialogInterface dialog,

                                                                        int which) {

                                                                pBar = new ProgressDialog(Update.this);

                                                                pBar.setTitle("正在下载");

                                                                pBar.setMessage("请稍候...");

                                                                pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);

                                                                downFile(Config.UPDATE_SERVER + Config.UPDATE_APKNAME);

                                                        }

                                                })

                                .setNegativeButton("暂不更新",

                                                new DialogInterface.OnClickListener() {

                                                        public void onClick(DialogInterface dialog,

                                                                        int whichButton) {

                                                                // 点击"取消"按钮之后退出程序

                                                                finish();

                                                        }

                                                }).create();// 创建

                // 显示对话框

                dialog.show();

        }
复制代码4. 下载模块

    void downFile(final String url) {

        pBar.show();

        new Thread() {

            public void run() {

                HttpClient client = new DefaultHttpClient();

                HttpGet get = new HttpGet(url);

                HttpResponse response;

                try {

                    response = client.execute(get);

                    HttpEntity entity = response.getEntity();

                    long length = entity.getContentLength();

                    InputStream is = entity.getContent();

                    FileOutputStream fileOutputStream = null;

                    if (is != null) {

                        File file = new File(

                                Environment.getExternalStorageDirectory(),

                                Config.UPDATE_SAVENAME);

                        fileOutputStream = new FileOutputStream(file);

                        byte[] buf = new byte[1024];

                        int ch = -1;

                        int count = 0;

                        while ((ch = is.read(buf)) != -1) {

                            fileOutputStream.write(buf, 0, ch);

                            count += ch;

                            if (length > 0) {

                            }

                        }

                    }

                    fileOutputStream.flush();

                    if (fileOutputStream != null) {

                        fileOutputStream.close();

                    }

                    down();

                } catch (ClientProtocolException e) {

                    e.printStackTrace();

                } catch (IOException e) {

                    e.printStackTrace();

                }

            }

        }.start();

    }
复制代码
下载完成,通过handler通知主ui线程将下载对话框取消。
void down() {

        handler.post(new Runnable() {

            public void run() {

                pBar.cancel();

                update();

            }

        });

}
复制代码5. 安装应用
    void update() {

        Intent intent = new Intent(Intent.ACTION_VIEW);

        intent.setDataAndType(Uri.fromFile(new File(Environment

                .getExternalStorageDirectory(), Config.UPDATE_SAVENAME)),

                "application/vnd.android.package-archive");

        startActivity(intent);

    }

4.下载apk

下载:String url="http://apk包的路径";
      Intent intent = new Intent(Intent.ACTION_VIEW);
      intent.setData(Uri.parse(url));
      startActivity(intent);
安装:Intent i = new Intent(Intent.ACTION_VIEW);  
      String filePath = "/sdcard/*.apk";  
      i.setDataAndType(Uri.parse("file://" + filePath),"application/vnd.android.package-archive");  
      startActivity(i);

5,检查apk是否安装

 public static boolean isApkInstalled(Context context, final String pkgName) {
 try {
   context.getPackageManager().getPackageInfo(pkgName, 0);
   return true;
  } catch (NameNotFoundException e) {
   //e.printStackTrace();
  }
  return false;


 

 

  1. package com.autoupdate;

  2. import java.io.File;
  3. import java.io.FileOutputStream;
  4. import java.io.InputStream;
  5. import java.net.URL;
  6. import java.net.URLConnection;
  7. import android.app.Activity;
  8. import android.app.AlertDialog;
  9. import android.app.ProgressDialog;
  10. import android.content.Context;
  11. import android.content.DialogInterface;
  12. import android.content.Intent;
  13. import android.content.pm.PackageInfo;
  14. import android.content.pm.PackageManager.NameNotFoundException;
  15. import android.net.ConnectivityManager;
  16. import android.net.NetworkInfo;
  17. import android.net.Uri;
  18. import android.util.Log;
  19. import android.webkit.URLUtil;
  20. import com.autoupdate.R;

  21. /**
  22. * 版本检测,自动更新
  23. *
  24. * @author shenyj-ydrh 1.通过Url检测更新 2.下载并安装更新 3.删除临时路径
  25. *
  26. */
  27. public class MyAutoUpdate {
  28.         // 调用更新的Activity
  29.         public Activity activity = null;
  30.         // 当前版本号
  31.         public int versionCode = 0;
  32.         // 当前版本名称
  33.         public String versionName = "";
  34.         // 控制台信息标识
  35.         private static final String TAG = "AutoUpdate";
  36.         // 文件当前路径
  37.         private String currentFilePath = "";
  38.         // 安装包文件临时路径
  39.         private String currentTempFilePath = "";
  40.         // 获得文件扩展名字符串
  41.         private String fileEx = "";
  42.         // 获得文件名字符串
  43.         private String fileNa = "";
  44.         // 服务器地址
  45.         private String strURL = "http://127.0.0.1:8080/ApiDemos.apk";
  46.         private ProgressDialog dialog;

  47.         /**
  48.          * 构造方法,获得当前版本信息
  49.          *
  50.          * @param activity
  51.          */
  52.         public MyAutoUpdate(Activity activity) {
  53.                 this.activity = activity;
  54.                 // 获得当前版本
  55.                 getCurrentVersion();
  56.         }

  57.         /**
  58.          * 检测更新
  59.          */
  60.         public void check() {
  61.                 // 检测网络
  62.                 if (isNetworkAvailable(this.activity) == false) {
  63.                         return;
  64.                 }
  65.                 // 如果网络可用,检测到新版本
  66.                 if (true) {
  67.                         // 弹出对话框,选择是否需要更新版本
  68.                         showUpdateDialog();
  69.                 }
  70.         }

  71.         /**
  72.          * 检测是否有可用网络
  73.          *
  74.          * @param context
  75.          * @return 网络连接状态
  76.          */
  77.         public static boolean isNetworkAvailable(Context context) {
  78.                 try {
  79.                         ConnectivityManager cm = (ConnectivityManager) context
  80.                                         .getSystemService(Context.CONNECTIVITY_SERVICE);
  81.                         // 获取网络信息
  82.                         NetworkInfo info = cm.getActiveNetworkInfo();
  83.                         // 返回检测的网络状态
  84.                         return (info != null && info.isConnected());
  85.                 } catch (Exception e) {
  86.                         e.printStackTrace();
  87.                         return false;
  88.                 }
  89.         }

  90.         /**
  91.          * 弹出对话框,选择是否需要更新版本
  92.          */
  93.         public void showUpdateDialog() {
  94.                 @SuppressWarnings("unused")
  95.                 AlertDialog alert = new AlertDialog.Builder(this.activity)
  96.                                 .setTitle("新版本").setIcon(R.drawable.ic_launcher)
  97.                                 .setMessage("是否更新?")
  98.                                 .setPositiveButton("是", new DialogInterface.OnClickListener() {
  99.                                         public void onClick(DialogInterface dialog, int which) {
  100.                                                 // 通过地址下载文件
  101.                                                 downloadTheFile(strURL);
  102.                                                 // 显示更新状态,进度条
  103.                                                 showWaitDialog();
  104.                                         }
  105.                                 })
  106.                                 .setNegativeButton("否", new DialogInterface.OnClickListener() {
  107.                                         public void onClick(DialogInterface dialog, int which) {
  108.                                                 dialog.cancel();
  109.                                         }
  110.                                 }).show();
  111.         }

  112.         /**
  113.          * 显示更新状态,进度条
  114.          */
  115.         public void showWaitDialog() {
  116.                 dialog = new ProgressDialog(activity);
  117.                 dialog.setMessage("正在更新,请稍候...");
  118.                 dialog.setIndeterminate(true);
  119.                 dialog.setCancelable(true);
  120.                 dialog.show();
  121.         }

  122.         /**
  123.          * 获得当前版本信息
  124.          */
  125.         public void getCurrentVersion() {
  126.                 try {
  127.                         // 获取应用包信息
  128.                         PackageInfo info = activity.getPackageManager().getPackageInfo(
  129.                                         activity.getPackageName(), 0);
  130.                         this.versionCode = info.versionCode;
  131.                         this.versionName = info.versionName;
  132.                 } catch (NameNotFoundException e) {
  133.                         e.printStackTrace();
  134.                 }
  135.         }

  136.         /**
  137.          * 截取文件名称并执行下载
  138.          *
  139.          * @param strPath
  140.          */
  141.         private void downloadTheFile(final String strPath) {
  142.                 // 获得文件文件扩展名字符串
  143.                 fileEx = strURL.substring(strURL.lastIndexOf(".") + 1, strURL.length())
  144.                                 .toLowerCase();
  145.                 // 获得文件文件名字符串
  146.                 fileNa = strURL.substring(strURL.lastIndexOf("/") + 1,
  147.                                 strURL.lastIndexOf("."));
  148.                 try {
  149.                         if (strPath.equals(currentFilePath)) {
  150.                                 doDownloadTheFile(strPath);
  151.                         }
  152.                         currentFilePath = strPath;
  153.                         new Thread(new Runnable() {

  154.                                 @Override
  155.                                 public void run() {
  156.                                         // TODO Auto-generated method stub
  157.                                         try {
  158.                                                 // 执行下载
  159.                                                 doDownloadTheFile(strPath);
  160.                                         } catch (Exception e) {
  161.                                                 Log.e(TAG, e.getMessage(), e);
  162.                                         }
  163.                                 }
  164.                         }).start();
  165.                 } catch (Exception e) {
  166.                         e.printStackTrace();
  167.                 }
  168.         }

  169.         /**
  170.          * 执行新版本进行下载,并安装
  171.          *
  172.          * @param strPath
  173.          * @throws Exception
  174.          */
  175.         private void doDownloadTheFile(String strPath) throws Exception {
  176.                 Log.i(TAG, "getDataSource()");
  177.                 // 判断strPath是否为网络地址
  178.                 if (!URLUtil.isNetworkUrl(strPath)) {
  179.                         Log.i(TAG, "服务器地址错误!");
  180.                 } else {
  181.                         URL myURL = new URL(strPath);
  182.                         URLConnection conn = myURL.openConnection();
  183.                         conn.connect();
  184.                         InputStream is = conn.getInputStream();
  185.                         if (is == null) {
  186.                                 throw new RuntimeException("stream is null");
  187.                         }
  188.                         //生成一个临时文件
  189.                         File myTempFile = File.createTempFile(fileNa, "." + fileEx);
  190.                         // 安装包文件临时路径
  191.                         currentTempFilePath = myTempFile.getAbsolutePath();
  192.                         FileOutputStream fos = new FileOutputStream(myTempFile);
  193.                         byte buf[] = new byte[128];
  194.                         do {
  195.                                 int numread = is.read(buf);
  196.                                 if (numread <= 0) {
  197.                                         break;
  198.                                 }
  199.                                 fos.write(buf, 0, numread);
  200.                         } while (true);
  201.                         Log.i(TAG, "getDataSource() Download  ok...");
  202.                         dialog.cancel();
  203.                         dialog.dismiss();
  204.                         // 打开文件
  205.                         openFile(myTempFile);
  206.                         try {
  207.                                 is.close();
  208.                         } catch (Exception ex) {
  209.                                 Log.e(TAG, "getDataSource() error: " + ex.getMessage(), ex);
  210.                         }
  211.                 }
  212.         }

  213.         /**
  214.          * 打开文件进行安装
  215.          *
  216.          * @param f
  217.          */
  218.         private void openFile(File f) {
  219.                 Intent intent = new Intent();
  220.                 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  221.                 intent.setAction(android.content.Intent.ACTION_VIEW);
  222.                 // 获得下载好的文件类型
  223.                 String type = getMIMEType(f);
  224.                 // 打开各种类型文件
  225.                 intent.setDataAndType(Uri.fromFile(f), type);
  226.                 // 安装
  227.                 activity.startActivity(intent);
  228.         }

  229.         /**
  230.          * 删除临时路径里的安装包
  231.          */
  232.         public void delFile() {
  233.                 Log.i(TAG, "The TempFile(" + currentTempFilePath + ") was deleted.");
  234.                 File myFile = new File(currentTempFilePath);
  235.                 if (myFile.exists()) {
  236.                         myFile.delete();
  237.                 }
  238.         }

  239.         /**
  240.          * 获得下载文件的类型
  241.          *
  242.          * @param f
  243.          *            文件名称
  244.          * @return 文件类型
  245.          */
  246.         private String getMIMEType(File f) {
  247.                 String type = "";
  248.                 // 获得文件名称
  249.                 String fName = f.getName();
  250.                 // 获得文件扩展名
  251.                 String end = fName
  252.                                 .substring(fName.lastIndexOf(".") + 1, fName.length())
  253.                                 .toLowerCase();
  254.                 if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")
  255.                                 || end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {
  256.                         type = "audio";
  257.                 } else if (end.equals("3gp") || end.equals("mp4")) {
  258.                         type = "video";
  259.                 } else if (end.equals("jpg") || end.equals("gif") || end.equals("png")
  260.                                 || end.equals("jpeg") || end.equals("bmp")) {
  261.                         type = "image";
  262.                 } else if (end.equals("apk")) {
  263.                         type = "application/vnd.android.package-archive";
  264.                 } else {
  265.                         type = "*";
  266.                 }
  267.                 if (end.equals("apk")) {
  268.                 } else {
  269.                         type += "/*";
  270.                 }
  271.                 return type;
  272.         }
  273. }

market 更新方式

  1.                             Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=pname:your.app.id"));
  2.                             startActivity(intent);


 //android下载进度控制//

private void execDownloadApk(String url) {
  // 下载文件 存放目的地
  String downloadPath = Environment.getExternalStorageDirectory()
    .getPath() + "/" +cache_data;
  File file = new File(downloadPath);
  if (!file.exists())
   file.mkdir();
  HttpGet httpGet = new HttpGet(url);
  try {
   HttpResponse httpResponse = new DefaultHttpClient()
     .execute(httpGet);
   if (httpResponse.getStatusLine().getStatusCode() == 200) {
    mTotalFileSize =(int)httpResponse.getEntity().getContentLength();
    
    /*URL downUrl = new URL(url);
    HttpURLConnection con = (HttpURLConnection) downUrl
      .openConnection();
    InputStream in = con.getInputStream();
    mTotalFileSize = con.getContentLength();*/
    
    InputStream is = httpResponse.getEntity().getContent();
    // 开始下载apk文件
    FileOutputStream fos = new FileOutputStream(downloadPath
      + "/demo.apk");
    byte[] buffer = new byte[8192];
    int count = 0;
    //if (mTotalFileSize > 0) {
     mHand.sendEmptyMessage(MSG_DOWNLOAD_SHOW_PROGRESS);
     while ((count = is.read(buffer)) != -1) {
      fos.write(buffer, 0, count);
      mDownFileSize += count;
      mHand.sendEmptyMessage(MSG_DOWNLOAD_PROGRESS);
     }
     fos.close();
     is.close();
    //} else {
    // mHand.sendEmptyMessage(MSG_DOWNLOAD_ERROR_INFO);
   // }
    // 安装 apk 文件
    installApk(downloadPath + "/demo.apk");
   } else {
    mHand.sendEmptyMessage(MSG_DOWNLOAD_ERROR_INFO);
   }
  } catch (Exception e) {
   e.printStackTrace();
   mHand.sendEmptyMessage(MSG_DOWNLOAD_ERROR_INFO);
  }
 }

 private void showDownLoadProgress() {
  mApkDLProgressDialog = CreateDialog.crateDialogByDownLoad(mContext, null,
    0);
  TextView tv = (TextView) mApkDLProgressDialog
    .findViewById(R.id.download_title);
  tv.setText(mContext.getResources().getString(
    R.string.apk_download_progress));
  mDoadloadProgress = (ProgressBar) mApkDLProgressDialog
    .findViewById(R.id.down_progress);
  mDoadloadProgress.setProgress(0);
  mDoadloadProgress.incrementProgressBy(1);
  mDoadloadProgress.setMax(mTotalFileSize);
  mApkDLProgressDialog.show();
 }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个简单的实现增删改查功能并且有五个页面的 Android Studio 代码示例,供您参考: 1. MainActivity.java ```java public class MainActivity extends AppCompatActivity { Button btnAdd, btnView; EditText editTextName, editTextAge; SQLiteDatabase db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnAdd = findViewById(R.id.btnAdd); btnView = findViewById(R.id.btnView); editTextName = findViewById(R.id.editTextName); editTextAge = findViewById(R.id.editTextAge); db = openOrCreateDatabase("MyDB", Context.MODE_PRIVATE, null); db.execSQL("CREATE TABLE IF NOT EXISTS Users (Id INTEGER PRIMARY KEY AUTOINCREMENT, Name VARCHAR, Age INT)"); btnAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String name = editTextName.getText().toString(); int age = Integer.parseInt(editTextAge.getText().toString()); db.execSQL("INSERT INTO Users (Name, Age) VALUES ('" + name + "', " + age + ")"); Toast.makeText(MainActivity.this, "User added successfully", Toast.LENGTH_SHORT).show(); } }); btnView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, ViewUsersActivity.class); startActivity(intent); } }); } } ``` 2. ViewUsersActivity.java ```java public class ViewUsersActivity extends AppCompatActivity { RecyclerView recyclerView; SQLiteDatabase db; ArrayList<User> userList; UserAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_users); recyclerView = findViewById(R.id.recyclerView); recyclerView.setLayoutManager(new LinearLayoutManager(this)); userList = new ArrayList<>(); adapter = new UserAdapter(this, userList); recyclerView.setAdapter(adapter); db = openOrCreateDatabase("MyDB", Context.MODE_PRIVATE, null); Cursor cursor = db.rawQuery("SELECT * FROM Users", null); if (cursor.moveToFirst()) { do { int id = cursor.getInt(cursor.getColumnIndex("Id")); String name = cursor.getString(cursor.getColumnIndex("Name")); int age = cursor.getInt(cursor.getColumnIndex("Age")); userList.add(new User(id, name, age)); } while (cursor.moveToNext()); } adapter.notifyDataSetChanged(); } } ``` 3. UserAdapter.java ```java public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ViewHolder> { Context context; ArrayList<User> userList; public UserAdapter(Context context, ArrayList<User> userList) { this.context = context; this.userList = userList; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.user_item, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { holder.textViewId.setText(String.valueOf(userList.get(position).getId())); holder.textViewName.setText(userList.get(position).getName()); holder.textViewAge.setText(String.valueOf(userList.get(position).getAge())); } @Override public int getItemCount() { return userList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { TextView textViewId, textViewName, textViewAge; public ViewHolder(@NonNull View itemView) { super(itemView); textViewId = itemView.findViewById(R.id.textViewId); textViewName = itemView.findViewById(R.id.textViewName); textViewAge = itemView.findViewById(R.id.textViewAge); } } } ``` 4. User.java ```java public class User { private int id, age; private String name; public User(int id, String name, int age) { this.id = id; this.name = name; this.age = age; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } ``` 5. activity_main.xml ```xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" android:padding="16dp"> <EditText android:id="@+id/editTextName" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Name" android:inputType="text" /> <EditText android:id="@+id/editTextAge" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Age" android:inputType="number" /> <Button android:id="@+id/btnAdd" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Add User" /> <Button android:id="@+id/btnView" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="View Users" /> </LinearLayout> ``` 6. activity_view_users.xml ```xml <androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="match_parent" /> ``` 7. user_item.xml ```xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="16dp"> <TextView android:id="@+id/textViewId" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Id: " android:textStyle="bold" /> <TextView android:id="@+id/textViewName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Name: " /> <TextView android:id="@+id/textViewAge" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Age: " /> </LinearLayout> ``` 以上是一个简单的实现增删改查功能并且有五个页面的 Android Studio 代码示例,具体实现过程可以根据您的需求和技术水平进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值