Android   发布时间:2022-04-28  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Android App中各种数据保存方式的使用实例总结大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

少量数据保存之SharedPreferences接口实例
SharedPreferences数据保存主要是通过键值的方式存储在xml文件
xml文件在data/此程序的包名/XX.xml。
格式:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<int name="count" value="3" />
<String name="time">写入日期:2013年10月07日,时间:11:28:09</String>
</map>

SharedPreferences读写的基本步骤:
读:
 1.通过Context的getSharedPreferences获取SharedPreferences接口的对象share:SharedPreferences share = this.getSharedPreferences("share",Context.MODE_PRIVATE);
"shre"保存的xml文件名,Context.MODE_PRIVATE 保存的类型为只被本程序访问 (还有MODE_WORLD_READABLE表示其余的程序能够读不能写,MODE
_WORLD_WRITEBLE能读写 这两个都在api17的时候被废了)
2.通过share的getXXX的方法获取指定key的值 :  share.geTint("count",0);
写:
1.通过SharedPreferences对象的edit()方法获取Edit对象:Edit   editor = share.edit();
2.通过editor对象的putXXX方法来写入值 :editor.puTint("count",1);
3.调用Editor的commit()方法提交修改值 :editor.commit();

访问其他程序的SharedPreferences
访问其他程序的SharedPreferences 的读写唯一不同的是先的获取该程序的Context接口对象:this.createPackageContext(packagename,flags)
packagename为要该目标程序的包名,flags访问类型
其余的就和上面的步骤差不多 就不再概叙

实例

<LinearLayout xmlns:android="http://scheR_952_11845@as.android.com/apk/res/android" 
 xmlns:tools="http://scheR_952_11845@as.android.com/tools" 
 android:layout_width="match_parent" 
 android:layout_height="match_parent" 
 
 android:orientation="vertical" 
 tools:context=".MainActivity" > 
 
 <Button 
  android:id="@+id/write" 
  android:layout_width="wrap_content" 
  android:layout_height="wrap_content" 
   android:layout_gravity="center_horizontal" 
  android:text="写入数据" /> 
 
 <Button 
  android:id="@+id/read" 
  android:layout_width="wrap_content" 
  android:layout_height="wrap_content" 
   android:layout_gravity="center_horizontal" 
  android:text="读入数据" /> 
 <TextView 
  android:id="@+id/txtCount" 
  android:layout_width="match_parent" 
  android:layout_height="wrap_content"/> 
 
 <TextView 
  android:id="@+id/txt1" 
  android:layout_width="match_parent" 
  android:layout_height="wrap_content" /> 
 
</LinearLayout> 

package com.android.xiong.sharepreferencestest; 
 
import java.text.SimpleDateFormat; 
import java.util.Date; 
 
import android.app.Activity; 
import android.content.Context; 
import android.content.SharedPreferences; 
import android.content.SharedPreferences.Editor; 
import android.os.bundle; 
import android.view.Menu; 
import android.view.View; 
import android.view.View.onClickListener; 
import android.widget.button; 
import android.widget.TextView; 
 
public class MainActivity extends Activity { 
 
 private Button write; 
 private Button read; 
 
 private TextView txt1; 
 private TextView countTxt; 
  
 SharedPreferences share ; 
  
 Editor editor; 
 
 int countO=0; 
 @Override 
 protected void onCreate(Bundle savedInstanceStatE) { 
  super.onCreate(savedInstanceStatE); 
  setContentView(R.layout.activity_main); 
  //获取SharedPreferences对象 
  share = this.getSharedPreferences("share",Context.MODE_PRIVATE); 
  //获取Editor对象 
  editor = share.edit(); 
  write = (Button) findViewById(R.id.writE); 
  read = (Button) findViewById(R.id.read); 
  txt1 = (TextView) findViewById(R.id.txt1); 
  countTxt=(TextView)findViewById(R.id.txtCount); 
  //获取share中key为count的值 
  countO=share.geTint("count",0); 
  countO++; 
  //修改share中key为count的值 
  editor.puTint("count",countO); 
  //提交修改 
  editor.commit(); 
  System.out.println("该应用程序使用了:"+countO+"次"); 
  countTxt.setText("该应用程序使用了:"+countO+"次"); 
   
  OnClickListener writeListener = new OnClickListener() { 
 
   @Override 
   public void onClick(View v) { 
    // TODO Auto-generated method stub 
 
    SimpleDateFormat data = new SimpleDateFormat( 
      "写入日期:yyyy年MM月dd日,时间:hh:mm:ss"); 
    editor.putString("time",data.format(new Date())); 
    editor.commit(); 
 
   } 
  }; 
  OnClickListener readListener=new OnClickListener() { 
    
   @Override 
   public void onClick(View v) { 
    // TODO Auto-generated method stub 
    if(!share.contains("share")){ 
     txt1.setText(share.getString("time",null)); 
    } 
     
   } 
  }; 
  write.setOnClickListener(writeListener); 
  read.setOnClickListener(readListener); 
 
 } 
 
 @Override 
 public Boolean onCreateOptionsMenu(Menu menu) { 
  // Inflate the menu; this adds items to the action bar if it is present. 
  getMenuInflater().inflate(R.menu.main,menu); 
  return true; 
 } 
 
} 


机身内存数据读写(Internal StoragE)
1.机身内存读取主要用个两个类文件输入流(FileInputStream)和文件输出流(FiLeoutputStream): FileInputStream fileInput = this.openFileInput("test.txt") 第一个参数为 data/此程序包名/data/test.txt 文件下 的文件名 ;
FiLeoutputStream fiLeout = this.openFiLeoutput("test.txt",this.MODE_APPEND)第一个参数表示文件名 第二个参数表示打开的方式 
2.获取文件输入输出流之后 其后的文件的读写和基本的IO操作一样
机身内存数据读写实例

<LinearLayout xmlns:android="http://scheR_952_11845@as.android.com/apk/res/android" 
 xmlns:tools="http://scheR_952_11845@as.android.com/tools" 
 android:layout_width="match_parent" 
 android:layout_height="match_parent" 
 android:layout_gravity="center_horizontal" 
 android:orientation="vertical" 
 tools:context=".MainActivity" > 
 <EditText 
  android:layout_width="match_parent" 
  android:layout_height="wrap_content" 
  android:id="@+id/ed1" 
  android:inputType="textMultiLine"/> 
 <Button 
  android:id="@+id/write" 
  android:text="写入" 
  android:layout_width="match_parent" 
  android:layout_height="wrap_content"/> 
 <Button 
  android:id="@+id/read" 
  android:layout_width="match_parent" 
  android:layout_height="wrap_content" 
  android:text="读入"/> 
 <EditText 
  android:id="@+id/ed2" 
  android:layout_width="match_parent" 
  android:layout_height="wrap_content" 
  android:inputType="textMultiLine"/> 
 <Button 
  android:id="@+id/delete" 
  android:layout_width="match_parent" 
  android:layout_height="wrap_content" 
  android:text="删除指定的文件" 
  /> 
 <EditText 
  android:id="@+id/ed3" 
  android:layout_width="match_parent" 
  android:layout_height="wrap_content" 
  /> 
 
</LinearLayout> 
package com.android.xiong.fileiotest; 
 
import java.io.bufferedReader; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FiLeoutputStream; 
import java.io.InputStreamReader; 
import java.lang.reflect.Array; 
import java.util.ArrayList; 
import java.util.Arrays; 
import java.util.List; 
 
import android.app.Activity; 
import android.os.bundle; 
import android.view.Menu; 
import android.view.View; 
import android.view.View.onClickListener; 
import android.widget.button; 
import android.widget.EditText; 
 
public class MainActivity extends Activity { 
 
 private Button read; 
 private Button write; 
 private EditText ed1; 
 private EditText ed2; 
 private EditText ed3; 
 private Button delete; 
 
 @Override 
 protected void onCreate(Bundle savedInstanceStatE) { 
  super.onCreate(savedInstanceStatE); 
  setContentView(R.layout.activity_main); 
  read = (Button) findViewById(R.id.read); 
  write = (Button) findViewById(R.id.writE); 
  delete = (Button) findViewById(R.id.Delete); 
  ed3 = (EditText) findViewById(R.id.ed3); 
  ed2 = (EditText) findViewById(R.id.ed2); 
  ed1 = (EditText) findViewById(R.id.ed1); 
  write.setOnClickListener(new OnClickListener() { 
   @Override 
   public void onClick(View v) { 
    String str = ed1.getText().toString(); 
    if (!str.equals("")) { 
     write(str); 
    } 
 
   } 
  }); 
  read.setOnClickListener(new OnClickListener() { 
 
   @Override 
   public void onClick(View v) { 
    read(); 
 
   } 
  }); 
  delete.setOnClickListener(new OnClickListener() { 
   @Override 
   public void onClick(View v) { 
    String str = ed3.getText().toString(); 
    if (!str.equals("")) { 
     deleteFiles(str); 
    } else { 
     ed3.setText(str + ":该文件输入错误或不存在!"); 
    } 
 
   } 
  }); 
 
 } 
 
 private void write(String content) { 
  try { 
   // 以追加的方式打开文件输出流 
   FiLeoutputStream fiLeout = this.openFiLeoutput("test.txt",this.MODE_APPEND); 
   // 写入数据 
   fiLeout.write(content.getBytes()); 
   // 关闭文件输出流 
   fiLeout.close(); 
 
  } catch (Exception E) { 
   e.printStackTrace(); 
  } 
 } 
 
 private void read() { 
  try { 
   ed2.setText(""); 
   // 打开文件输入流 
   FileInputStream fileInput = this.openFileInput("test.txt"); 
   BufferedReader br = new BufferedReader(new InputStreamReader( 
     fileInput)); 
   String str = null; 
   StringBuilder stb = new StringBuilder(); 
   while ((str = br.readLine()) !=null ) { 
    stb.append(str); 
   } 
   ed2.setText(stb); 
  } catch (Exception E) { 
   e.printStackTrace(); 
  } 
 
 } 
  
 //删除指定的文件 
 private void deleteFiles(String fileName) { 
  try { 
   // 获取data文件中的所有文件列表 
   List<String> name = Arrays.asList(this.fileList()); 
   if (name.contains(fileName)) { 
    this.deleteFile(fileName); 
    ed3.setText(filename + ":该文件成功删除!"); 
   } else 
    ed3.setText(filename + ":该文件输入错误或不存在!"); 
 
  } catch (Exception E) { 
   e.printStackTrace(); 
  } 
 } 
 
 @Override 
 public Boolean onCreateOptionsMenu(Menu menu) { 
  getMenuInflater().inflate(R.menu.main,menu); 
  return true; 
 } 
 
} 


SDcard(External StoragE)读写数据实例
1.SDcard数据读写需要注定的先要在Androidmainfest.xml文件注册新建删除和读写的权限 : 

<!-- 在SD卡上创建与删除权限 -->
<uses-permission Android:name="android.permission.MOUNT_FORMAT_FILESYstemS" />
<!-- 向SD卡上写入权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

2.读写的基本流程就是:
2.1 通过Environment类的getExternalStorageState()方法判断手机是否有SDcard: 

Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)

2.2 最通过getExternalStorageDirectory()方法获取文件目录:

@H_197_83@复制代码 代码如下:

File file = new File(Environment.getExternalStorageDirectory().getCanonicalPath() + "/test.txt");

读写的文件都在sdcrad文件夹中 通过File Explorer可以导出来
2.3 其后就和基本IO操作相同了
2.4还有要注意一点的是 在运行的模拟器的时候要附带虚拟的SDcard时  要在Run as->Run Configurations 中要关联一下 如下图

Android App中各种数据保存方式的使用实例总结

SDcard数据读写实例
<LinearLayout xmlns:android="http://scheR_952_11845@as.android.com/apk/res/android" 
 xmlns:tools="http://scheR_952_11845@as.android.com/tools" 
 android:layout_width="match_parent" 
 android:layout_height="match_parent" 
 android:gravity="center_horizontal" 
 android:orientation="vertical" 
 tools:context=".MainActivity" > 
 <EditText 
  android:id="@+id/ed1" 
  android:layout_width="match_parent" 
  android:layout_height="wrap_content" 
  android:inputType="textMultiLine"/> 
 <Button 
  android:id="@+id/write" 
  android:layout_width="match_parent" 
  android:layout_height="wrap_content" 
  android:text="写入SD卡中"/> 
 <Button 
  android:id="@+id/read" 
  android:layout_width="match_parent" 
  android:layout_height="wrap_content" 
  android:text="读取SD文件"/> 
 <TextView 
  android:id="@+id/txt1" 
  android:layout_width="match_parent" 
  android:layout_height="wrap_content"/> 
</LinearLayout> 


<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://scheR_952_11845@as.android.com/apk/res/android" 
 package="com.android.xiong.sdcardtest" 
 android:versionCode="1" 
 android:versionName="1.0" > 
 
 <uses-sdk 
  android:minSdkVersion="14" 
  android:targetSdkVersion="17" /> 
 <!-- 在SD卡上创建与删除权限 --> 
 <uses-permission android:name="android.permission.MOUNT_FORMAT_FILESYstemS" /> 
 <!-- 向SD卡上写入权限 --> 
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
 
 <application 
  android:allowBACkup="true" 
  android:icon="@drawable/ic_launcher" 
  android:label="@String/app_name" 
  android:theme="@style/AppTheme" > 
  <activity 
   android:name="com.android.xiong.sdcardtest.MainActivity" 
   android:label="@String/app_name" > 
   <intent-filter> 
    <action android:name="android.intent.action.MAIN" /> 
 
    <category android:name="android.intent.category.LAUNCHER" /> 
   </intent-filter> 
  </activity> 
 </application> 
 
</manifest> 
package com.android.xiong.sdcardtest; 
 
import java.io.bufferedReader; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FiLeoutputStream; 
import java.io.InputStreamReader; 
 
import android.app.Activity; 
import android.os.bundle; 
import android.os.Environment; 
import android.view.Menu; 
import android.view.View; 
import android.view.View.onClickListener; 
import android.widget.button; 
import android.widget.EditText; 
import android.widget.TextView; 
 
public class MainActivity extends Activity { 
 
 private Button write; 
 private Button read; 
 
 private EditText ed1; 
 private TextView txt1; 
 
 @Override 
 protected void onCreate(Bundle savedInstanceStatE) { 
  super.onCreate(savedInstanceStatE); 
  setContentView(R.layout.activity_main); 
  write = (Button) findViewById(R.id.writE); 
  read = (Button) findViewById(R.id.read); 
  ed1 = (EditText) findViewById(R.id.ed1); 
  txt1 = (TextView) findViewById(R.id.txt1); 
  write.setOnClickListener(new OnClickListener() { 
 
   @Override 
   public void onClick(View v) { 
    // TODO Auto-generated method stub 
    writeSDcard(ed1.getText().toString()); 
 
   } 
  }); 
  read.setOnClickListener(new OnClickListener() { 
 
   @Override 
   public void onClick(View v) { 
    // TODO Auto-generated method stub 
 
    txt1.setText(readSDcard()); 
   } 
  }); 
 } 
 
 // 把数据写入SD卡 
 
 private void writeSDcard(String str) { 
 
  try { 
   // 判断是否存在SD卡 
   if (Environment.getExternalStorageState().equals( 
     Environment.MEDIA_MOUNTED)) { 
    // 获取SD卡的目录 
    File file = Environment.getExternalStorageDirectory(); 
    FiLeoutputStream fileW = new FiLeoutputStream(file.getCanonicalPath() + "/test.txt"); 
    fileW.write(str.getBytes()); 
    fileW.close(); 
   } 
  } catch (Exception E) { 
   e.printStackTrace(); 
  } 
 
 } 
 
 // 从SD卡中读取数据 
 private String readSDcard() { 
  StringBuffer str = new StringBuffer(); 
  try { 
   // 判断是否存在SD 
   if (Environment.getExternalStorageState().equals( 
     Environment.MEDIA_MOUNTED)) { 
    File file = new File(Environment.getExternalStorageDirectory() 
      .getCanonicalPath() + "/test.txt");                 
    // 判断是否存在该文件 
    if (file.exists()) { 
     // 打开文件输入流 
     FileInputStream fileR = new FileInputStream(filE); 
     BufferedReader reads = new BufferedReader( 
       new InputStreamReader(fileR)); 
     String st = null; 
     while ((st =reads.readLine())!=null ) { 
      str.append(st); 
     } 
     fileR.close(); 
    } else { 
     txt1.setText("该目录下文件不存在"); 
    } 
   } 
 
  } catch (Exception E) { 
   e.printStackTrace(); 
  } 
  return str.toString(); 
 } 
 
 @Override 
 public Boolean onCreateOptionsMenu(Menu menu) { 
  // Inflate the menu; this adds items to the action bar if it is present. 
  getMenuInflater().inflate(R.menu.main,menu); 
  return true; 
 } 
 
} 

sqlite简介和简单的登录注册代码
1.获取sqliteDatabase对象db创建数据库或连接数据库sqliteDatabasedb = sqliteDatabase.openOrCreateDatabase(MainActivity.this.getFilesDir().toString()+ "/test.dbs",null);如果目录下有test.dbs数据库则是连接没有就是创建
2.用对象db的方法来执行sql语句:db.execsql(String sql) 此方法木有返回值 所以查询不好弄。查询一般用db.rawQuery返回一个cursor对象(相当与jdbc中的ResultSet),cursor有如下几个方法查询数据:
  2.1 move ToFirst 将记录指针跳到第一行
  2.2 moveToLast将记录指针跳到最后一行
  2.3 moveNext将记录指针移到下一行
  2.4moveToPosition( int ss)将记录指针跳到指定的ss行
  2.5moveToPrevIoUs将记录指针跳到上一行
将记录指针跳到指定的行之后就可以通过对象的getXXX方法获取数据 :如 cursor cursor = db.rawQuery("SELEct  na,pw from user where na=? and pw=?",new String []{name,pwD});
3.回收资源close
当然以sqliteDatabase对象还可以调用许多方法来操作数据库,不过俺是觉得这几个方法基本够了

简单的登录注册代码
(仅此来练习sqlite的操作  一般注册的信息都样上传到服务器而不会是存储在手机数据库

Android App中各种数据保存方式的使用实例总结

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://scheR_952_11845@as.android.com/apk/res/android" 
  package="com.android.xiong.sqlitelogin" 
  android:versionCode="1" 
  android:versionName="1.0" > 
 
  <uses-sdk 
    android:minSdkVersion="8" 
    android:targetSdkVersion="14" /> 
 
  <application 
    android:allowBACkup="true" 
    android:icon="@drawable/ic_launcher" 
    android:label="@String/app_name" 
    android:theme="@style/AppTheme" > 
    <activity 
      android:name="com.android.xiong.sqlitelogin.MainActivity" 
      android:label="@String/app_name" > 
      <intent-filter> 
        <action android:name="android.intent.action.MAIN" /> 
 
        <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
    </activity> 
    <activity 
      android:name="com.android.xiong.sqlitelogin.RegistersActivity" 
      android:label="@String/app_name" > 
    </activity> 
  </application> 
 
</manifest> 

<RelativeLayout xmlns:android="http://scheR_952_11845@as.android.com/apk/res/android" 
  xmlns:tools="http://scheR_952_11845@as.android.com/tools" 
  android:layout_width="match_parent" 
  android:layout_height="match_parent" 
  tools:context=".MainActivity" > 
 
  <TextView 
    android:id="@+id/login" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_margin="30dp" 
    android:gravity="center_horizontal" 
    android:textColor="#8a2be2" 
    android:textSize="35dp" 
    android:text="登录界面" /> 
  <TextView  
    android:id="@+id/txtname" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layouT_Below="@id/login" 
    android:layout_marginRight="5dp" 
    android:layout_marginBottom="30dp" 
    android:textSize="28dp" 
    android:text="用户帐号:"/> 
  <EditText  
    android:id="@+id/edname" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_marginBottom="30dp" 
    android:layouT_Below="@id/login" 
    android:layout_toRightOf="@id/txtname" 
    android:layout_alignParen@R_674_10296@ht="true" 
     android:hint="请输入用户帐号"/> 
    <TextView  
    android:id="@+id/txtpassword" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layouT_Below="@id/txtname" 
    android:layout_marginRight="5dp" 
    android:textSize="28dp" 
    android:text="用户密码:"/> 
  <EditText  
    android:id="@+id/edpassword" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layouT_Below="@id/edname" 
    android:layout_toRightOf="@id/txtpassword" 
    android:layout_alignParen@R_674_10296@ht="true" 
    android:inputType="textpassword" 
    android:hint="请输入用户密码"/> 
  <LinearLayout  
    android:layouT_Below="@id/edpassword" 
    android:orientation="horizontal" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_marginTop="30dp" 
    android:gravity="center_horizontal" > 
  <Button  
    android:id="@+id/btregister" 
    android:layout_height="wrap_content" 
    android:layout_width="wrap_content" 
    android:layout_marginRight="20dp" 
    android:text="用户注册"/> 
   <Button  
    android:id="@+id/btlogin" 
    android:layout_height="wrap_content" 
    android:layout_width="wrap_content" 
    android:text="用户登录"/> 
   </LinearLayout> 
 
</RelativeLayout> 


<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://scheR_952_11845@as.android.com/apk/res/android" 
  android:layout_width="match_parent" 
  android:layout_height="match_parent" > 
   
 
  <TextView 
    android:id="@+id/txt1" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layout_margin="30dp" 
    android:gravity="center_horizontal" 
    android:text="注册界面" 
    android:textColor="#8a2be2" 
    android:textSize="35dp" /> 
 
  <TextView 
    android:id="@+id/txtname1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layouT_Below="@id/txt1" 
    android:layout_marginBottom="30dp" 
    android:layout_marginRight="5dp" 
    android:text="帐号:" 
    android:textSize="28dp" /> 
 
  <EditText 
    android:id="@+id/edname1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParen@R_674_10296@ht="true" 
    android:layouT_Below="@id/txt1" 
     android:layout_toRightOf="@id/txtname1" 
    android:layout_marginBottom="30dp" /> 
 
  <TextView 
    android:id="@+id/txtpassword1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layouT_Below="@id/txtname1" 
    android:layout_marginRight="5dp" 
    android:text="密码:" 
    android:textSize="28dp" /> 
 
  <EditText 
    android:id="@+id/edpassword1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParen@R_674_10296@ht="true" 
    android:layouT_Below="@id/edname1" 
    android:layout_toRightOf="@id/txtpassword1" /> 
 
  <LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:layouT_Below="@id/edpassword1" 
    android:layout_marginTop="30dp" 
    android:gravity="center_horizontal" 
    android:orientation="horizontal" > 
 
    <Button 
      android:id="@+id/btregister1" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_marginRight="20dp" 
      android:text="提交数据" /> 
  </LinearLayout> 
</RelativeLayout> 


package com.android.xiong.sqlitelogin; 
 
import android.app.Activity; 
import android.app.AlertDialog; 
import android.content.Intent; 
import android.database.cursor; 
import android.database.sqlite.sqliteDatabase; 
import android.database.sqlite.sqliteException; 
import android.os.bundle; 
import android.view.Menu; 
import android.view.View; 
import android.view.View.onClickListener; 
import android.widget.button; 
import android.widget.EditText; 
 
public class MainActivity extends Activity { 
 
  // 帐号和密码 
  private EditText edname; 
  private EditText edpassword; 
 
  private Button btregister; 
  private Button btlogin; 
  // 创建sqlite数据库 
  public static sqliteDatabase db; 
 
  @Override 
  protected void onCreate(Bundle savedInstanceStatE) { 
    super.onCreate(savedInstanceStatE); 
    setContentView(R.layout.activity_main); 
    edname = (EditText) findViewById(R.id.edName); 
    edpassword = (EditText) findViewById(R.id.edpassword); 
    btregister = (Button) findViewById(R.id.btregister); 
    btlogin = (Button) findViewById(R.id.btlogin); 
    db = sqliteDatabase.openOrCreateDatabase(MainActivity.this.getFilesDir().toString() 
        + "/test.dbs",null); 
    // 跳转注册界面 
    btregister.setOnClickListener(new OnClickListener() { 
 
      @Override 
      public void onClick(View v) { 
        // TODO Auto-generated method stub 
        Intent intent = new Intent(); 
        intent.setClass(MainActivity.this,RegistersActivity.class); 
        startActivity(intent); 
      } 
    }); 
    btlogin.setOnClickListener(new LoginListener()); 
  } 
 
  @Override 
  protected void onDestroy() { 
    // TODO Auto-generated method stub 
    super.onDestroy(); 
    db.close(); 
  } 
 
 
  class LoginListener implements OnClickListener { 
 
    @Override 
    public void onClick(View v) { 
      // TODO Auto-generated method stub 
      String name = edname.getText().toString(); 
      String password = edpassword.getText().toString(); 
      if (name.equals("") || password.equals("")) { 
        // 弹出消息框 
        new AlertDialog.builder(MainActivity.this).settitle("错误") 
            .setmessage("帐号或密码不能空").setPositiveButton("确定",null) 
            .show(); 
      } else { 
        isUserinfo(name,password); 
      } 
    } 
 
    // 判断输入的用户是否正确 
    public Boolean isUserinfo(String name,String pwd) { 
      try{ 
        String str="SELEct * FROM tb_user where name=? and password=?"; 
        cursor cursor = db.rawQuery(str,pwD}); 
        if(cursor.getCount()<=0){ 
          new AlertDialog.builder(MainActivity.this).settitle("错误") 
          .setmessage("帐号或密码错误!").setPositiveButton("确定",null) 
          .show(); 
          return false; 
        }else{ 
          new AlertDialog.builder(MainActivity.this).settitle("正确") 
          .setmessage("成功登录").setPositiveButton("确定",null) 
          .show(); 
          return true; 
        } 
         
      }catch(sqliteException E){ 
        createdb(); 
      } 
      return false; 
    } 
   
  } 
  // 创建数据库用户表 
  public void createdb() { 
    db.execsql("create table tb_user( name varchar(30) priMary key,password varchar(30))"); 
  } 
  @Override 
  public Boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.main,menu); 
    return true; 
  } 
 
} 

package com.android.xiong.sqlitelogin; 
 
import android.app.Activity; 
import android.app.AlertDialog; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.database.sqlite.sqliteDatabase; 
import android.os.bundle; 
import android.view.View; 
import android.view.View.onClickListener; 
import android.widget.button; 
import android.widget.EditText; 
 
public class RegistersActivity extends Activity { 
 
  private EditText edname1; 
  private EditText edpassword1; 
  private Button btregister1; 
  sqliteDatabase db; 
 
  @Override 
  protected void onDestroy() { 
    // TODO Auto-generated method stub 
    super.onDestroy(); 
    db.close(); 
  } 
 
  @Override 
  protected void onCreate(Bundle savedInstanceStatE) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceStatE); 
    setContentView(R.layout.register); 
    edname1 = (EditText) findViewById(R.id.edname1); 
    edpassword1 = (EditText) findViewById(R.id.edpassword1); 
    btregister1 = (Button) findViewById(R.id.btregister1); 
    btregister1.setOnClickListener(new OnClickListener() { 
 
      @Override 
      public void onClick(View v) { 
        // TODO Auto-generated method stub 
        String name = edname1.getText().toString(); 
        String password = edpassword1.getText().toString(); 
        if (!(name.equals("") && password.equals(""))) { 
          if (addUser(name,password)) { 
            DialogInterface.onClickListener ss = new DialogInterface.onClickListener() { 
              @Override 
              public void onClick(DialogInterface dialog,int which) { 
                // TODO Auto-generated method stub 
                // 跳转登录界面 
                Intent in = new Intent(); 
                in.setClass(RegistersActivity.this,MainActivity.class); 
                startActivity(in); 
                // 销毁当前activity 
                RegistersActivity.this.onDestroy(); 
              } 
            }; 
            new AlertDialog.builder(RegistersActivity.this) 
                .settitle("注册成功").setmessage("注册成功") 
                .setPositiveButton("确定",ss).show(); 
 
          } else { 
            new AlertDialog.builder(RegistersActivity.this) 
                .settitle("注册失败").setmessage("注册失败") 
                .setPositiveButton("确定",null); 
          } 
        } else { 
          new AlertDialog.builder(RegistersActivity.this) 
              .settitle("帐号密码不能为空").setmessage("帐号密码不能为空") 
              .setPositiveButton("确定",null); 
        } 
 
      } 
    }); 
 
  } 
 
  // 添加用户 
  public Boolean addUser(String name,String password) { 
    String str = "insert into tb_user values(?,?) "; 
    MainActivity main = new MainActivity(); 
    db = sqliteDatabase.openOrCreateDatabase(this.getFilesDir().toString() 
        + "/test.dbs",null); 
    main.db = db; 
    try { 
      db.execsql(str,new String[] { name,password }); 
      return true; 
    } catch (Exception E) { 
      main.createdb(); 
    } 
    return false; 
  } 
 
} 


大佬总结

以上是大佬教程为你收集整理的Android App中各种数据保存方式的使用实例总结全部内容,希望文章能够帮你解决Android App中各种数据保存方式的使用实例总结所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:存储