日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

安卓-通讯录

發(fā)布時(shí)間:2023/12/10 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 安卓-通讯录 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

一、實(shí)驗(yàn)?zāi)康?/h2>

練習(xí)掌握 Android 軟件開(kāi)發(fā)基本編程技術(shù)、Android 系統(tǒng) SQLite 數(shù)據(jù)庫(kù)的使用、通話、短信的使用等,設(shè)計(jì)制作一 Android 通訊錄軟件。

二、實(shí)驗(yàn)內(nèi)容

實(shí)現(xiàn)的通訊錄功能和界面可在實(shí)驗(yàn)開(kāi)發(fā)中由每位同學(xué)自己設(shè)計(jì),但必須使用SQLite 數(shù)據(jù)庫(kù)保存通訊錄信息。以下功能和軟件界面供參考:仿照一般手機(jī)通訊錄的使用界面和功能,主要功能可包括: (1)可以添加、刪減聯(lián)系人
(2)聯(lián)系人的信息包括:姓名、手機(jī)號(hào)碼、工作單位、群組、電子郵件、手機(jī)鈴聲
(3)選擇聯(lián)系人后,可以快速進(jìn)行操作,如:撥打電話發(fā)送短信、查看詳細(xì)、移出群組、移動(dòng)分組、刪除聯(lián)系人等。查看詳細(xì)時(shí)顯示手機(jī)號(hào)碼、群組、和設(shè)定的手機(jī)鈴聲以及同該聯(lián)系人的通話記錄。
(4)在聯(lián)系人界面,可以查看各群組。點(diǎn)擊群組,跳出對(duì)應(yīng)聯(lián)系人。
(5)有撥號(hào)鍵盤(pán),點(diǎn)擊數(shù)字將號(hào)碼顯示出來(lái),并可以對(duì)手機(jī)號(hào)碼進(jìn)行刪減
(6)可以發(fā)送信息,顯示信息記錄
(7)發(fā)送信息時(shí),可以快速選擇現(xiàn)有聯(lián)系人。

三、實(shí)驗(yàn)要求

(1)每位同學(xué)獨(dú)立設(shè)計(jì)軟件功能、完成軟件的開(kāi)發(fā)與測(cè)試。
(2)每位同學(xué)獨(dú)立完成實(shí)驗(yàn)報(bào)告(根據(jù)模板),并提交至網(wǎng)絡(luò)課堂。

四、數(shù)據(jù)代碼及運(yùn)行結(jié)果截圖

全部代碼如圖所示

//mainactivity.java 代碼太多了,所以其他文件的代碼就沒(méi)有貼上。 import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.core.app.NotificationCompat; import androidx.core.view.GravityCompat; import androidx.drawerlayout.widget.DrawerLayout; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import android.app.AlertDialog; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.content.Context; import android.content.SharedPreferences; import android.graphics.BitmapFactory; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.Toast; import com.google.android.material.navigation.NavigationView; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.pan.coursedesign.recyclerview.Person; import com.pan.coursedesign.recyclerview_logs.recording; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.params.HttpMethodParams; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.litepal.crud.DataSupport; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.List; import java.util.Map; import java.util.Set; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response;public class MainActivity extends AppCompatActivity {AlertDialog.Builder builder5;//自定義AlertDialog dialog;private int tag = 0;private int DataDownTag = 0;private DrawerLayout mDrawerLayout;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//自定義Toolbar并設(shè)置進(jìn)系統(tǒng)Toolbar toolbar = findViewById(R.id.toolbar);setSupportActionBar(toolbar);//因?yàn)榛瑒?dòng)菜單不容易被用戶知道,所以加一個(gè)折疊按鈕ActionBar actionBar = getSupportActionBar();//得到actionBar的實(shí)例(toolbar實(shí)現(xiàn)的哦,也就是toolbar對(duì)象)if (actionBar != null) { //有的話actionBar.setDisplayHomeAsUpEnabled(true); //顯示一個(gè)home按鈕,HomeAsUp這個(gè)按鈕的id永遠(yuǎn)是HomeactionBar.setHomeAsUpIndicator(R.drawable.ic_menu); //設(shè)置一個(gè)圖標(biāo)}//獲取抽屜的實(shí)例用于打開(kāi)和關(guān)閉抽屜的事件mDrawerLayout = findViewById(R.id.my_drawer);//默認(rèn)加載的碎片,text1replaceFragment(new Contacts_Fragment());//啟動(dòng)彈窗//從文件讀取tag數(shù)據(jù)SharedPreferences preferences = getSharedPreferences("statata", MODE_PRIVATE);tag = preferences.getInt("tag", 0);if (tag == 0) { //tag沒(méi)被修改,顯示彈窗l(fā)oding();}//設(shè)置側(cè)面munu的點(diǎn)擊事件NavigationView navigationView = (NavigationView) findViewById(R.id.my_nav_view);navigationView.setCheckedItem(R.id.nav_text1);navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {@Overridepublic boolean onNavigationItemSelected(MenuItem item) {//詳細(xì)設(shè)計(jì)抽屜菜單的點(diǎn)擊事件switch (item.getItemId()) {case R.id.nav_text1:replaceFragment(new Contacts_Fragment());mDrawerLayout.closeDrawer(navigationView);break;case R.id.nav_text2:replaceFragment(new Call_Fragment());mDrawerLayout.closeDrawer(navigationView);break;case R.id.nav_text3:replaceFragment(new Call_logs_Fragment());mDrawerLayout.closeDrawer(navigationView);break;case R.id.nav_text4:replaceFragment(new Help_Fragment());mDrawerLayout.closeDrawer(navigationView);break;case R.id.nav_text5:replaceFragment(new About_Fragment());mDrawerLayout.closeDrawer(navigationView);break;default:break;}return true;}});}//動(dòng)態(tài)替換碎片private void replaceFragment(Fragment fragment) {FragmentManager fragmentManager = getSupportFragmentManager();FragmentTransaction transaction = fragmentManager.beginTransaction();transaction.replace(R.id.DTFragment, fragment);transaction.commit();}// ----toolbar邏輯----//傳統(tǒng)的方法實(shí)現(xiàn)菜單的植入(command + O快捷鍵)@Overridepublic boolean onCreateOptionsMenu(Menu menu) {//設(shè)置一個(gè)menugetMenuInflater().inflate(R.menu.toolbar, menu);return true;}//tab按鍵事件@Overridepublic boolean onOptionsItemSelected(MenuItem item) {//設(shè)置menu的選項(xiàng)點(diǎn)擊事件switch (item.getItemId()) {case android.R.id.home://這是內(nèi)置的哦mDrawerLayout.openDrawer(GravityCompat.START);//將滑動(dòng)菜單顯示出來(lái),打開(kāi)抽屜 參數(shù)是方式和xml設(shè)置的保持一致break;case R.id.DataDown:DataDown();//阿帕奇服務(wù)器上下載json數(shù)據(jù)break;case R.id.DataUp:try {UpData(GetJsonString());//先把數(shù)據(jù)導(dǎo)出成json文本在作為數(shù)據(jù)上傳到服務(wù)器} catch (JSONException e) {e.printStackTrace();} // Toast.makeText(this,"此功能開(kāi)發(fā)中...",Toast.LENGTH_LONG).show();break;case R.id.settings:try {ExportData();Toast.makeText(this, "導(dǎo)出成功: 內(nèi)部目錄file文件夾下", Toast.LENGTH_LONG).show();} catch (JSONException e) {e.printStackTrace();}break;case R.id.settings_1:if (Import().isEmpty()) {Toast.makeText(this, "導(dǎo)入失敗,沒(méi)有數(shù)據(jù)", Toast.LENGTH_LONG).show();} else {ImportData();Toast.makeText(this, "導(dǎo)入成功", Toast.LENGTH_LONG).show();}break;case R.id.settings_2:delall();break;default:}return true;}//1.下載時(shí)提示框public void DataDown() {//啟動(dòng)彈窗//從文件讀取tag數(shù)據(jù)SharedPreferences preferences = getSharedPreferences("DataDown", MODE_PRIVATE);DataDownTag = preferences.getInt("DataDownTag", 0);if (DataDownTag == 0) { //tag沒(méi)被修改,顯示彈窗//inflate方法返回的是一個(gè)view(自定義那個(gè)),View loginview = LayoutInflater.from(this).inflate(R.layout.datadown_dialog_info, null);//loginview里的控件聲明一下CheckBox checkBox = loginview.findViewById(R.id.info_2);Button btnLogin = loginview.findViewById(R.id.datadown);btnLogin.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {//把狀態(tài)計(jì)入文件供下次讀取if (checkBox.isChecked()) {//如果被選中SharedPreferences.Editor editor = getSharedPreferences("DataDown", MODE_MULTI_PROCESS).edit();editor.putInt("DataDownTag", 1);editor.apply();}dialog.dismiss();DownData();}});//設(shè)置Dialog和Viewbuilder5 = new AlertDialog.Builder(this);dialog = builder5.setTitle("重要提示").setView(loginview).setCancelable(false).show();} else {DownData();}}//從服務(wù)器下載json數(shù)據(jù)public void DownData() {new Thread(new Runnable() {@Overridepublic void run() {try {OkHttpClient client = new OkHttpClient();Request request = new Request.Builder()// 指定訪問(wèn)的服務(wù)器地址是電腦本機(jī).url("http://172.20.10.5:8081/pro").build();Response response = client.newCall(request).execute();String responseData = response.body().string();parseJSONWithGSON(responseData);//下載json數(shù)據(jù)導(dǎo)入解析} catch (Exception e) {e.printStackTrace();}}}).start();}//導(dǎo)入json進(jìn)行解析的方法private void parseJSONWithGSON(String jsonData) {//Log.d("aaaaa---", jsonData);Contacts_Fragment contacts_fragment = (Contacts_Fragment) getSupportFragmentManager().findFragmentById(R.id.DTFragment);Gson gson = new Gson();List<Person> appList = gson.fromJson(jsonData, new TypeToken<List<Person>>() {}.getType());//c=appList;int tag = 0;//遍歷并先把數(shù)據(jù)存入數(shù)據(jù)庫(kù)for (Person person : appList) {person.setTel(formatInviteCode(person.getTel()));//獲取的數(shù)據(jù)同樣要處理if (RemoveRepetition(person.getName())) { //只有數(shù)據(jù)庫(kù)沒(méi)有時(shí)才更新contacts_fragment.Persons.add(person);person.save();tag = 1;}}if (tag == 1) {//只要有一個(gè)變就刷新//這個(gè)方法是在任務(wù)線程執(zhí)行的,需要去主線程更新ui//加個(gè)下載成功的通知DataNotification();MainActivity.this.runOnUiThread(new Runnable() {public void run() {contacts_fragment.load();}});} else {DataFailNotification();//找不到服務(wù)器/導(dǎo)入的數(shù)據(jù)都有}}public Boolean RemoveRepetition(String name) {List<Person> Persons = DataSupport.select("name", "Tel", "Email").where("name like ?", "%" + name + "%").find(Person.class);if (Persons.size() != 0) {return false;//如果數(shù)據(jù)庫(kù)有,不更新}return true;}//下載成功的通知public void DataNotification() {NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);Notification notification = new NotificationCompat.Builder(this, "5996773").setContentTitle("文件下載的通知")//標(biāo)題內(nèi)容.setContentText("導(dǎo)入數(shù)據(jù)成功!")//正文內(nèi)容.setWhen(System.currentTimeMillis())//指定通知被創(chuàng)建的時(shí)間.setSmallIcon(R.mipmap.ic_launcher)//設(shè)置通知小圖標(biāo).setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))//設(shè)置通知大圖標(biāo).setVibrate(new long[]{0, 1000, 1000, 1000})//通知到了讓手機(jī)震動(dòng).setLights(Color.GREEN, 1000, 1000)//設(shè)置手機(jī)前置LED燈的顯示效果.setPriority(NotificationCompat.PRIORITY_MAX)//設(shè)置通知的重要程度.build();//build完算是構(gòu)建完成notification對(duì)象if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {NotificationChannel channel = new NotificationChannel("5996773", "安卓10的通知哦", NotificationManager.IMPORTANCE_HIGH);channel.enableLights(true);//是否在桌面icon右上角展示小紅點(diǎn)channel.setLightColor(Color.GREEN);//小紅點(diǎn)顏色channel.setShowBadge(false); //是否在久按桌面圖標(biāo)時(shí)顯示此渠道的通知manager.createNotificationChannel(channel);//將channel設(shè)置進(jìn)manager}//id唯一即可manager.notify(1, notification);}//下載失敗的通知public void DataFailNotification() {NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);Notification notification = new NotificationCompat.Builder(this, "5996774").setContentTitle("文件下載的通知")//標(biāo)題內(nèi)容.setContentText("文件下載成功,但您不需要導(dǎo)入!")//正文內(nèi)容.setWhen(System.currentTimeMillis())//指定通知被創(chuàng)建的時(shí)間.setSmallIcon(R.mipmap.ic_launcher)//設(shè)置通知小圖標(biāo).setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))//設(shè)置通知大圖標(biāo).setVibrate(new long[]{0, 1000, 1000, 1000})//通知到了讓手機(jī)震動(dòng).setLights(Color.GREEN, 1000, 1000)//設(shè)置手機(jī)前置LED燈的顯示效果.setPriority(NotificationCompat.PRIORITY_MAX)//設(shè)置通知的重要程度.build();//build完算是構(gòu)建完成notification對(duì)象if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {NotificationChannel channel = new NotificationChannel("5996774", "安卓10的通知哦", NotificationManager.IMPORTANCE_HIGH);channel.enableLights(true);//是否在桌面icon右上角展示小紅點(diǎn)channel.setLightColor(Color.GREEN);//小紅點(diǎn)顏色channel.setShowBadge(false); //是否在久按桌面圖標(biāo)時(shí)顯示此渠道的通知manager.createNotificationChannel(channel);//將channel設(shè)置進(jìn)manager}//id唯一即可manager.notify(2, notification);}//2.上傳json到服務(wù)器public void UpData(String body){new Thread(new Runnable(){@Overridepublic void run(){String url="http://172.20.10.5:8081/air";//你要訪問(wèn)的地址String mesg = null;//定義服務(wù)器返回的結(jié)果HttpClient httpClient = new HttpClient();//構(gòu)建HttpClient實(shí)例httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(60000); //設(shè)置請(qǐng)求超時(shí)時(shí)間httpClient.getHttpConnectionManager().getParams().setSoTimeout(60000);//設(shè)置響應(yīng)超時(shí)時(shí)間PostMethod postMethod=new PostMethod(url);//構(gòu)造PostMethod的實(shí)例postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");String jsonString="{'data':" + body + "}";//com.alibaba.fastjson.JSONObject意思是導(dǎo)入阿里的parseObject,parseObject第一個(gè)參數(shù)是json對(duì)象Map<String,Object> map = com.alibaba.fastjson.JSONObject.parseObject(jsonString,Map.class);Set<String> set = map.keySet();for(String s : set){postMethod.addParameter(s,map.get(s).toString());}try {httpClient.executeMethod(postMethod);//執(zhí)行post請(qǐng)求mesg = postMethod.getResponseBodyAsString();//可以對(duì)響應(yīng)回來(lái)的報(bào)文進(jìn)行處理//Log.d("aaaa--", mesg);//獲取成功!!!!} catch (HttpException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally{if(mesg!=null){//有數(shù)據(jù)DataupNotification();//文件上傳成功的通知}//關(guān)閉連接釋放資源的方法postMethod.releaseConnection();httpClient.getHttpConnectionManager().closeIdleConnections(0);}}}).start();}//上傳成功的通知public void DataupNotification() {NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);Notification notification = new NotificationCompat.Builder(this, "599111").setContentTitle("文件上傳的通知")//標(biāo)題內(nèi)容.setContentText("上傳數(shù)據(jù)成功!")//正文內(nèi)容.setWhen(System.currentTimeMillis())//指定通知被創(chuàng)建的時(shí)間.setSmallIcon(R.mipmap.ic_launcher)//設(shè)置通知小圖標(biāo).setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))//設(shè)置通知大圖標(biāo).setVibrate(new long[]{0, 1000, 1000, 1000})//通知到了讓手機(jī)震動(dòng).setLights(Color.GREEN, 1000, 1000)//設(shè)置手機(jī)前置LED燈的顯示效果.setPriority(NotificationCompat.PRIORITY_MAX)//設(shè)置通知的重要程度.build();//build完算是構(gòu)建完成notification對(duì)象if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {NotificationChannel channel = new NotificationChannel("599111", "安卓10的通知哦", NotificationManager.IMPORTANCE_HIGH);channel.enableLights(true);//是否在桌面icon右上角展示小紅點(diǎn)channel.setLightColor(Color.GREEN);//小紅點(diǎn)顏色channel.setShowBadge(false); //是否在久按桌面圖標(biāo)時(shí)顯示此渠道的通知manager.createNotificationChannel(channel);//將channel設(shè)置進(jìn)manager}//id唯一即可manager.notify(3, notification);}//3.導(dǎo)出json到文件public void ExportData() throws JSONException {String str = GetJsonString();save(str);}//導(dǎo)出json文本public String GetJsonString() throws JSONException {//獲取碎片實(shí)例以調(diào)用碎片中的方法Contacts_Fragment contacts_fragment = (Contacts_Fragment) getSupportFragmentManager().findFragmentById(R.id.DTFragment);List<Person> Persons = contacts_fragment.Persons;//轉(zhuǎn)換list為jsonJSONArray jsonArray = new JSONArray();JSONObject jsonObject = new JSONObject();//這個(gè)巨坑,注意包JSONObject tmpObj = null;int count = Persons.size();for (int i = 0; i < count; i++) {tmpObj = new JSONObject();tmpObj.put("name", Persons.get(i).getName());tmpObj.put("Email", Persons.get(i).getEmail());tmpObj.put("Tel", Persons.get(i).getTel());jsonArray.put(tmpObj);tmpObj = null;}String personInfos = jsonArray.toString(); // 將JSONArray轉(zhuǎn)換得到String//Log.d("DDDDD",personInfos);return personInfos;}//將一段json文本保存到文件中去public void save(String inputText) {FileOutputStream out = null;BufferedWriter writer = null;//command + alt + t 快速生成try {File file = new File(getCacheDir().getPath(), "data.json");if (file != null) {file.delete();} else {file.createNewFile();}out = openFileOutput("data.json", Context.MODE_PRIVATE); // out = new FileOutputStream(file);// OutputStreamWriter是從字符流到字節(jié)流的橋接:字節(jié)流搞成了字符流傳遞給緩沖流writer = new BufferedWriter(new OutputStreamWriter(out));// 寫(xiě)入writer.write(inputText);} catch (IOException e) {e.printStackTrace();} finally {try {if (writer != null) {writer.close();//關(guān)閉上層流(緩沖流),下層數(shù)據(jù)流就自動(dòng)關(guān)了}} catch (IOException e) {e.printStackTrace();}}}//4.從文件導(dǎo)入jsonpublic void ImportData() {String str1 = Import();parseJSONWithGSON(str1);//顯示}//從文件中讀取json文件public String Import() {//準(zhǔn)備從文件讀數(shù)據(jù)FileInputStream in = null;//緩沖流,輸入BufferedReader reader = null;StringBuilder content = new StringBuilder();try {in = openFileInput("data.json");reader = new BufferedReader(new InputStreamReader(in));String line = "";//reader.readLine()是讀取一行while ((line = reader.readLine()) != null) {content.append(line);}} catch (IOException e) {e.printStackTrace();} finally {if (reader != null) {try {reader.close();} catch (IOException e) {e.printStackTrace();}}}return content.toString();}//初始化加載private void loding() {//inflate方法返回的是一個(gè)view(自定義那個(gè)),View loginview = LayoutInflater.from(this).inflate(R.layout.ui_dialog_info, null);//loginview里的控件聲明一下CheckBox checkBox = loginview.findViewById(R.id.info_2);Button btnLogin = loginview.findViewById(R.id.info_3);btnLogin.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) { // 把狀態(tài)計(jì)入文件供下次讀取if (checkBox.isChecked()) {//如果被選中SharedPreferences.Editor editor = getSharedPreferences("statata", MODE_MULTI_PROCESS).edit();editor.putInt("tag", 1);editor.apply();}dialog.dismiss();}});//設(shè)置Dialog和Viewbuilder5 = new AlertDialog.Builder(this);dialog = builder5.setTitle("重要信息").setView(loginview).setCancelable(false).show();}//5.一鍵刪除public void delall() {DataSupport.deleteAll(Person.class);DataSupport.deleteAll(recording.class);Toast.makeText(this, "刪除全部數(shù)據(jù)成功!", Toast.LENGTH_SHORT).show();}//處理一下系統(tǒng)獲取聯(lián)系人時(shí)字符串的-/空格public String formatInviteCode(String str1) {String str2 = "";for (int i = 0; i < str1.length(); i++) {if (Character.isDigit(str1.charAt(i))) {//判斷被索引處的字符是不是數(shù)字str2 += str1.charAt(i);}}return str2;} }

五、錯(cuò)誤總結(jié)

1、錯(cuò)誤:

no such column: userName

解決:格式錯(cuò)誤,類型TEXT前面必須有一個(gè)空格!

UserInfoEntry.COLUMN_USER_NAME + " TEXT NOT NULL, "

2、類型前面全部都添加了空格,仍舊報(bào)錯(cuò):

no such column: userName

解決:數(shù)據(jù)庫(kù)沒(méi)有更新,更新版本號(hào)。在生產(chǎn)應(yīng)用程序中,可能會(huì)修改此方法以更改表格,而不是刪除它,以便不刪除現(xiàn)有數(shù)據(jù)。
新手學(xué)習(xí)中,尚不知道如何修改。
//如果更改數(shù)據(jù)庫(kù)架構(gòu),則必須增加數(shù)據(jù)庫(kù)版本

private static final int DATABASE_VERSION = 4; @Overridepublic void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) { // //在onUpgrade中,刪除表(如果存在)sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + UserInfoEntry.TABLE_NAME); // //調(diào)用onCreate并傳入SQLiteDatabase(傳入onUpgrade)記得更新版本號(hào)onCreate(sqLiteDatabase);}

3、錯(cuò)誤:

android.database.CursorIndexOutOfBoundsException: Index -1 requested,
with a size of 1

解決:下標(biāo)越界,cursor下標(biāo)從-1開(kāi)始,而不是0,需要移動(dòng),添加if語(yǔ)句。其實(shí)還是不太明白,為什么移動(dòng)到第一個(gè)就可以了。

if (cursor.moveToFirst()){ queryPassword=cursor.getString(cursor.getColumnIndex(UserInfoContract.UserInfoEntry.COLUMN_USER_PASSWORD)); }

4、錯(cuò)誤:

android.database.sqlite.SQLiteException: no such column:

錯(cuò)誤例子:

return mDb.update(DATABASE_TABLE, args, KEY_SSID + "=" + ssid , null) > 0;

原因:
在執(zhí)行數(shù)據(jù)庫(kù)的增刪改查操作時(shí),如:update、query等方法,傳入的參數(shù)是字符串類型。
其實(shí)這些方法會(huì)將參數(shù)拼接成sql語(yǔ)句,而字符串類型需要用引號(hào)引上
所以上方錯(cuò)誤的代碼應(yīng)改為:

return mDb.update(DATABASE_TABLE, args, KEY_SSID + "='" + ssid + "'", null) > 0;

六、個(gè)人心得體會(huì)

SQLite的基本數(shù)據(jù)類型:Byte,Long,Short,Integer,Float,Double,String,Boolean,byte[]
理論存儲(chǔ)容量為140TB
SQLiteOpenHelper
既然是數(shù)據(jù)庫(kù)的增刪改查,我們首先需要一個(gè)數(shù)據(jù)庫(kù),而數(shù)據(jù)庫(kù)要通過(guò)SQLiteOpenHelper的子類生成,所以首先需要建一個(gè)類來(lái)繼承SQLiteOpenHelper。由于這個(gè)類是一個(gè)抽象類,我們需要實(shí)現(xiàn)他的構(gòu)造方法和抽象方法。所以:

public class DBHelper extends SQLiteOpenHelper {// 數(shù)據(jù)庫(kù)默認(rèn)名字public static final String db_name = "test.db";public DBHelper(Context context, int version) {super(context, db_name, null, version);}@Overridepublic void onCreate(SQLiteDatabase db) {}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {} }

需要重載的方法
onCreate:創(chuàng)建表和一些基本屬性。
onUpgrade:數(shù)據(jù)庫(kù)需要更新的時(shí)候使用,前提是已經(jīng)存在了一個(gè)相同的數(shù)據(jù)庫(kù),需要新加表,或者原來(lái)的表字段要修改。
舉例:現(xiàn)在創(chuàng)建一個(gè)名為table1的表:直接執(zhí)行SQL語(yǔ)句

public class DBHelper extends SQLiteOpenHelper {public static final String db_name = "test.db";public DBHelper(Context context, int version) {super(context, db_name, null, version);}@Overridepublic void onCreate(SQLiteDatabase db) {db.execSQL("create table table1 (" +" _byte byte," +" _long long," +" _text text," +" _short short," +" _int int," +" _float float," +" _double double," +" _boolean boolean," +" _blob blob" +")");}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {} }

表的增刪改查

public class DBManger {private Context context;private static DBManger instance;// 操作表的對(duì)象,進(jìn)行增刪改查private SQLiteDatabase writableDatabase;private DBManger(Context context) {this.context = context;DBHelper dbHelper = new DBHelper(context, 1); //通過(guò)DBHelper的getWritableDatabase方法得到SQLiteDatabase對(duì)象,SQLiteDatabase可以對(duì)數(shù)據(jù)庫(kù)表進(jìn)行操作writableDatabase = dbHelper.getWritableDatabase();}public static DBManger getInstance(Context context) {if (instance == null) {synchronized (DBManger.class) {if (instance == null) {instance = new DBManger(context);}}}return instance;} }

增加:

public void add() {ContentValues contentValues = new ContentValues();byte _byte = Byte.MAX_VALUE;contentValues.put("_byte", _byte);long _long = Long.MAX_VALUE;contentValues.put("_long", _long);String _text = "字符串";contentValues.put("_text", _text);short _short = Short.MAX_VALUE;contentValues.put("_short", _short);int _int = Integer.MAX_VALUE;contentValues.put("_int", _int);float _float = Float.MAX_VALUE;contentValues.put("_float", _float);double _double = Double.MAX_VALUE;contentValues.put("_double", _double);boolean _boolean = true;contentValues.put("_boolean", _boolean);byte[] _byteArr = {Byte.MIN_VALUE, Byte.MAX_VALUE};contentValues.put("_blob", _byteArr);writableDatabase.insert("table1", null, contentValues);}

刪:刪除_int = Integer.MAX_VALUE的值

public void del() {writableDatabase.delete("table1", "_int = ?", new String[]{Integer.MAX_VALUE + ""}); }

改:調(diào)用update方法,參數(shù)依次:表名、包裹、條件、條件的值

public void update() {ContentValues contentValues = new ContentValues();contentValues.put("_text", "修改后的字符串");writableDatabase.update("table1", contentValues, "_text = ?", new String[]{"字符串"});}

查:首先query方法返回了一個(gè)Cursor對(duì)象,用來(lái)定位。
Query的參數(shù):
String table:表名
String[] columns:需要被查詢的列名
String selection:代表只查多少條數(shù)據(jù),比如只查10條數(shù)據(jù),就直接傳遞一個(gè)10就行了。
String[] selectionArgs:代表只查多少條數(shù)據(jù),比如只查10條數(shù)據(jù),就直接傳遞一個(gè)10就行了。
String groupBy:將相同值劃分為一組
String having:條件判斷的參數(shù),不過(guò)這個(gè)要跟groupby這個(gè)參數(shù)同時(shí)存在,也就是要同時(shí)使用。也就是說(shuō),在groupby篩選后的數(shù)據(jù)中,再使用這個(gè)所謂的having再篩選一次。
String orderBy:代表排序,可以傳某個(gè)字段,比如_byte,這就代表按照這個(gè)字段排序,默認(rèn)是升序,也就是從小到大排序,我們可以這樣傳遞參數(shù),讓其降序排列_byte desc,如果是_byte asc就是升序,由于默認(rèn)升序,所以這個(gè)asc也就省略了。
String limit:代表只查多少條數(shù)據(jù),比如只查10條數(shù)據(jù),就直接傳遞一個(gè)10就行了。

public String select() {Cursor cursor = writableDatabase.query("table1", null, null, null, null, null, null, null);int position = cursor.getPosition();Log.e(TAG, "select: 游標(biāo)默認(rèn)位置:" + position);String result = "";while (cursor.moveToNext()) {byte _byte = (byte) cursor.getShort(cursor.getColumnIndex("_byte"));long _long = cursor.getLong(cursor.getColumnIndex("_long"));String _text = cursor.getString(cursor.getColumnIndex("_text"));short _short = cursor.getShort(cursor.getColumnIndex("_short"));int _int = cursor.getInt(cursor.getColumnIndex("_int"));float _float = cursor.getFloat(cursor.getColumnIndex("_float"));double _double = cursor.getDouble(cursor.getColumnIndex("_double"));boolean _boolean = cursor.getInt(cursor.getColumnIndex("_boolean")) == 1 ? true : false;byte[] _byteArr = cursor.getBlob(cursor.getColumnIndex("_blob"));result += String.format("_byte = %s, _long = %s, _text = %s, _short = %s, _int = %s, _float = %s, _double = %s, _boolean = %s, _byteArr = %s",_byte, _long, _text, _short, _int, _float, _double, _boolean, _byteArr) + "\n";}return result; }

總結(jié)

以上是生活随笔為你收集整理的安卓-通讯录的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。