实例一
实现字典功能,用户输入单词,可以根据数据库中存的单词给出翻译,若没有则提示翻译不成功。也可以用户自己添加单词和释义。
代码:
没有布局要求,简单的两个activity的互相调用。
首先是数据库类的创建,DBOpenHelper().
package com.example.dictionary; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import androidx.annotation.Nullable; public class DBOpenHelper extends SQLiteOpenHelper { //定义创建数据表的sql语句 final String CREATE_TABLE_SQL = "create table dict (_id integer primary key autoincrement,word,detail)"; public DBOpenHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) { super(context, name, null, version); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TABLE_SQL);//创建数据表 } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.i("词典","--版本更新"+oldVersion+"-->"+newVersion); } }
然后在主Activity中,在翻译界面获取用户输入的内容,去相应数据库中查找,若有显示内容,若无弹出提示。
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:padding="25dp"> <Button android:id="@+id/search_btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:text="翻译"/> <EditText android:id="@+id/search_et" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/search_btn" android:hint="在此输入要翻译的单词" android:layout_marginTop="20dp"/> <ListView android:id="@+id/result_listView" android:layout_width="match_parent" android:layout_height="300dp" android:layout_below="@id/search_et"/> <Button android:id="@+id/btn_add" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="30dp" android:layout_alignParentRight="true" android:layout_alignParentBottom="true" android:text="添加生词"/> </RelativeLayout>
MainActivity.java文件
package com.example.dictionary; import androidx.appcompat.app.AppCompatActivity; 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 android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.Toast; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class MainActivity extends AppCompatActivity { private DBOpenHelper dbOpenHelper ;//声明DBOpenHelper对象 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); dbOpenHelper = new DBOpenHelper(MainActivity.this,"dict.db",null,1);//实例化DBOpenHelper对象,用来创建查数据库 final ListView listView = findViewById(R.id.result_listView); final EditText etSearch = findViewById(R.id.search_et); Button btnSearch = findViewById(R.id.search_btn); Button btn_add = findViewById(R.id.btn_add); btn_add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this,AddActivity.class); startActivity(intent); } }); btnSearch.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String key = etSearch.getText().toString();//获取要查询的单词 Cursor cursor = dbOpenHelper.getReadableDatabase().query("dict",null,"word=?",new String[]{key},null,null,null);//执行查询操作 ArrayList<Map<String,String>> resultList = new ArrayList<Map<String,String>>(); while (cursor.moveToNext()){ Map<String,String> map = new HashMap<String,String>(); map.put("word",cursor.getString(1)); map.put("interpret",cursor.getString(2)); resultList.add(map); } if (resultList==null||resultList.size()==0){//如果数据库没有数据 Toast.makeText(MainActivity.this,"很遗憾,没有相关记录。",Toast.LENGTH_SHORT).show(); }else {//否则将查询结果显示到listView列表中 SimpleAdapter simpleAdapter = new SimpleAdapter(MainActivity.this,resultList, R.layout.result_main,new String[]{"word","interpret"},new int[]{ R.id.result_word,R.id.result_interpret}); listView.setAdapter(simpleAdapter); } } }); } @Override protected void onDestroy() { super.onDestroy(); if (dbOpenHelper!=null){ dbOpenHelper.close();//关闭数据库连接 } } }
下面是点击添加生词跳转的AddActivity,在其中添加生词和相应翻译,并能实现回到MainActivity中。
activity_add.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".AddActivity" android:orientation="vertical" android:padding="30dp"> <EditText android:id="@+id/add_word" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="单词"/> <EditText android:id="@+id/add_interpret" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="释义"/> <Button android:id="@+id/save_btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="保存"/> <Button android:id="@+id/cancel_btn1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="返回"/> </LinearLayout>
AddAcitivy.java文件
package com.example.dictionary; import androidx.appcompat.app.AppCompatActivity; import android.content.ContentValues; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class AddActivity extends AppCompatActivity { private DBOpenHelper dbOpenHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add); dbOpenHelper = new DBOpenHelper(AddActivity.this,"dict.db",null,1);//实例化DBOpenHelper对象,用来创建查数据库 final EditText etWord = findViewById(R.id.add_word); final EditText etInterpret = findViewById(R.id.add_interpret); Button btn_Save = findViewById(R.id.save_btn); Button btn_Cancel = findViewById(R.id.cancel_btn1); //保存按钮的点击事件 btn_Save.setOnClickListener(new View.OnClickListener() {//实现将添加的单词解释保存在数据库中 @Override public void onClick(View v) { String word = etWord.getText().toString(); String interpret = etInterpret.getText().toString(); if (word.equals("")&&interpret.equals("")){ Toast.makeText(AddActivity.this,"填写的单词或解释为空",Toast.LENGTH_SHORT).show(); }else{ insertData(dbOpenHelper.getReadableDatabase(),word,interpret);//插入生词 Toast.makeText(AddActivity.this,"添加生词成功",Toast.LENGTH_SHORT).show(); } } }); btn_Cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(AddActivity.this,MainActivity.class); startActivity(intent); } }); } //插入数据的方法 private void insertData(SQLiteDatabase sqLiteDatabase,String word,String interpret){ ContentValues values = new ContentValues(); values.put("word",word);//保存单词 values.put("detail",interpret); sqLiteDatabase.insert("dict",null,values);//执行插入操作 } @Override protected void onDestroy() { super.onDestroy(); if (dbOpenHelper!=null){ dbOpenHelper.close();//关闭数据库连接 } } }
便可完成,效果如下。
实例二
实现读取通讯录功能,并显示信息。
MainActivity.java
package com.example.thecontact; import androidx.appcompat.app.AppCompatActivity; import android.content.ContentResolver; import android.database.Cursor; import android.os.Bundle; import android.provider.ContactsContract; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private String columns = ContactsContract.Contacts.DISPLAY_NAME; //希望获得姓名 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView tv = (TextView) findViewById(R.id.result); //获得布局文件中的TextView组件 tv.setText(getQueryData()); //为TextView设置数据 } private CharSequence getQueryData() { //创建getQueryData()方法,实现获取通讯录信息 StringBuilder sb = new StringBuilder(); //用于保存字符串 ContentResolver resolver = getContentResolver(); //获得ContentResolver对象 //查询记录 Cursor cursor = resolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null); int displayNameIndex = cursor.getColumnIndex(columns); //获得姓名记录的索引值 //迭代全部记录 for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { String displayName = cursor.getString(displayNameIndex); sb.append(displayName + "\n"); } cursor.close(); //关闭Cursor return sb.toString(); //返回查询结果 } }
在AndroidManifest.xml中注册权限。
在<manifest>中添加 <uses-permission android:name="android.permission.READ_CONTACTS"/> 即可。
来源:https://www.cnblogs.com/dongao/p/12273269.html