Part blog simple example: dictionaries and address book

Example one

Achieve dictionary, users enter the word can be given according to the translation of the word stored in the database, if no translation is prompted unsuccessful. Users can also add their own words and interpretation.

Code:

No layout requirements, simply call each other two of activity.

The first is the database class is created, 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 the onCreate (the SQLiteDatabase DB) { 
        db.execSQL (CREATE_TABLE_SQL); // create a data table 
    } 

    @Override 
    public  void onUpgrade (the SQLiteDatabase DB, int oldVersion, int newVersion) { 
        Log.i ( " Dictionary " , " - updated version " + oldVersion + " -> " + newVersion); 
    } 
}

Then in the main Activity, gets in translation interface user input, to find the appropriate database, if the contents of the display, without pop-up prompts.

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 file

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();//To get the query word 
                . DbOpenHelper.getReadableDatabase the Cursor = the Cursor () Query ( " dict " , null , " Word =? " , New new String [] {Key}, null , null , null ); // execute query 
                ArrayList < the Map <String, String >> = resultList new new the ArrayList <map <String, String >> ();
                 the while (cursor.moveToNext ()) { 
                    map <String, String> Map = new new the HashMap <String, String> (); 
                    Map .put ( "Word " , cursor.getString ( . 1 )); 
                    map.put ( " Interpret " , cursor.getString ( 2 )); 
                    resultList.add (Map); 
                } 
                IF (resultList == null || resultList.size () == 0 ) { // if the database has no data 
                    . Toast.makeText (MainActivity the this , " Unfortunately, no records. " , Toast.LENGTH_SHORT) .Show (); 
                } the else { // otherwise the query results to show listView list 
                    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 (); // close the connection 
        } 
    } 
}

The following is a click to add new words jump AddActivity, in which the words and add the appropriate translation, and can achieve MainActivity back in.

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 file

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 voidthe onCreate (the Bundle savedInstanceState) {
         Super .onCreate (savedInstanceState); 
        the setContentView (R.layout.activity_add); 
        dbOpenHelper = new new DBOpenHelper (. AddActivity the this , "dict.db", null ,. 1); // instantiate DBOpenHelper objects, with to create a database check 
        Final the EditText etWord = findViewById (R.id.add_word);
         Final the EditText etInterpret = findViewById (R.id.add_interpret); 
        the Button btn_Save = findViewById (R.id.save_btn); 
        the Button btn_Cancel = findViewById (R.id .cancel_btn1); 

        // save button click event
        btn_Save.setOnClickListener ( new new View.OnClickListener () { // implementation will add the word interpretation stored in the database 
            @Override
             public  void the onClick (View V) { 
                String Word = etWord.getText () toString ();. 
                String Interpret = etInterpret . .getText () toString ();
                 IF (word.equals ( "") && interpret.equals ( "" )) { 
                    Toast.makeText (AddActivity. the this , "fill word or interpreted empty" , Toast.LENGTH_SHORT). Show (); 
                } the else  {
                    The insertData (dbOpenHelper.getReadableDatabase (), Word, Interpret);// Insert words 
                    Toast.makeText (AddActivity. The this , "add words success" , Toast.LENGTH_SHORT) the .Show (); 
                } 
            } 
        }); 
        btn_Cancel.setOnClickListener ( new new View.OnClickListener () { 
            @Override 
            public  void the onClick (View V) { 
                the Intent Intent = new new the Intent (AddActivity. the this , the MainActivity. class ); 
                startActivity (Intent); 
            } 
        });

    } 
    // methods to insert data 
    Private  void The insertData (the SQLiteDatabase SQLiteDatabase, Word String, String Interpret) { 
        ContentValues values = new new ContentValues (); 
        values.put ( "Word", Word); // save the word 
        values.put ( "detail " , Interpret); 
        sqLiteDatabase.insert ( " dict ", null , values); // insertion operations 
    } 

    @Override 
    protected  void onDestroy () {
         Super .onDestroy ();
         IF ! (dbOpenHelper = null ) {
            dbOpenHelper.close (); // close the connection 
        } 
    } 
}

It can be completed, the effect is as follows.

Example Two

Read contacts to realize the function, and displays the information.

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); 
        the setContentView (R.layout.activity_main); 
        TextView TV = (TextView) the findViewById (R.id.result); // get layout file TextView assembly 
        tv.setText (getQueryData ()); // to set the data TextView 
    } 

    Private CharSequence getQueryData () { // create getQueryData () method to achieve access to directory information 
        the StringBuilder SB = new new the StringBuilder (); // for saving character 
        ContentResolver getContentResolver Resolver = (); // get ContentResolver Object
         // query record 
        the Cursor the Cursor = resolver.query (ContactsContract.Contacts.CONTENT_URI, null, Null , null , null );
         int displayNameIndex = cursor.getColumnIndex (the Columns); // get name record index value
         // iteration all records 
        for (cursor.moveToFirst ();! Cursor.isAfterLast (); cursor.moveToNext ( )) { 
            String displayName = cursor.getString (displayNameIndex); 
            sb.append (displayName + "\ n-" ); 
        } 
        cursor.close (); // Close the Cursor 
        return sb.toString (); // returns a query result 
    } 
}

Enroll permissions in AndroidManifest.xml.

Add <manifest> in <uses-permission android: name = "android.permission.READ_CONTACTS" /> to.

 

Guess you like

Origin www.cnblogs.com/dongao/p/12273269.html