android's functional api for word translation

android's function of word translation

Train of thought:

1. Layout interface, an interface for adding new words, a main interface for inputting content to be translated, and an interface for displaying translation results.
2. java code: first, add the new words: add ﹣ activity; then add the database to store the data; finally, implement the translation function in the main ﹣ activity.

Involving knowledge points and expanding knowledge:

1. What is api
Baidu said that the API (Application Programming Interface) is some pre-defined functions, the purpose is to provide the ability of application program and developers to access a set of routines based on a certain software or hardware, without access to the source code, or understanding the details of internal working mechanism.
From a technical point of view, API refers to the application programming interface. The API is not exactly the same as the remote server - it's actually part of the server that receives requests and sends responses. API is a way to provide services for customers.
2. Life cycle of activity:
This time, onDestroy(): the destruction of Activity is used, so that the results of the previous query will not be displayed when the next query is performed.
The life cycle of an activity is a process from creation to destruction. In this process, the activity changes from creation to destruction, from visible to invisible because of the constant change of application scenarios.
The seven functions used in this process are as follows:
onCreate(): Activity creation call
onStart(): Activity start call
onRestart(): Activity starts the call again
onResume(): Activity gets focus
onPause(): Activity loses focus
onStop():Activity pauses the call
onDestroy():Activity destroy call
3.SQLiteOpenHelper

SQLiteOpenHelper class common methods:

/** 
  *  Create database
  */ 
 // 1. Create or open read / write database (operate through SQLiteDatabase object returned)
 getWritableDatabase()

 // 2. Create or open a readable database (operate through the returned SQLiteDatabase object)
 getReadableDatabase()

 // 3. It will be called when the database is created for the first time, that is, it will be called when getWritableDatabase() / getReadableDatabase() is called for the first time
 // Replicate in a subclass that inherits the SQLiteOpenHelper class
 onCreate(SQLiteDatabase db) 

 // 4. Automatic call during database upgrade
 // Replicate in a subclass that inherits the SQLiteOpenHelper class
 onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)

 // 5. Close the database
 close()

 /** 
  *  Database operation (add, delete, subtract, query)
  */ 
 // 1. Query data
 (Cursor) query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)  
 // Query the specified data table to return a data set with a cursor.
 // Description of each parameter: 
 // Table: table name 
 // colums: array of column names 
 // selection: a conditional clause, equivalent to where 
 // selectionArgs: an array of parameters for a conditional statement 
 // groupBy: Group 
 // having: grouping condition 
 // orderBy: sort class 
 // Limit: limit of paging query 
 // Cursor: return value, equivalent to ResultSet 

 (Cursor) rawQuery(String sql, String[] selectionArgs) 
 //Run a preset SQL statement and return the dataset with cursor (the biggest difference with the above statement = prevent SQL injection)

 // 2. Delete data row  
 (int) delete(String table,String whereClause,String[] whereArgs) 
 
 // 3. Add data row 
 (long) insert(String table,String nullColumnHack,ContentValues values) 
 
 // 4. Update data lines 
(int) update(String table, ContentValues values, String whereClause, String[] whereArgs) 
 
 // 5. Execute an SQL statement, which can be a select or other SQL statements 
 // That is, directly use String type to pass in sql statement & execute
 (void) execSQL(String sql) 
--------
//Copyright notice: This is the original article of CSDN blogger "Carson Ou Ho", following CC 4.0 BY-SA Copyright agreement, reprint please attach the original source link and this statement.
//Original link: https://blog.csdn.net/carson_ho/article/details/53241633

4.ArrayList
1.ArrayList: dynamic Array, in MSDN, is the complex version of Array. It provides the following benefits:
Dynamic increase and decrease of elements; implementation of ICollection and IList interface; flexible setting of array size.
2. How to use ArrayList
The simplest example:
ArrayList List = new ArrayList();
For (Int i = 0; I < 10; I + +) / / add 10 Int elements to the array
List.Add(i);
/ /... The program does some processing
List.RemoveAt(5); / / remove the 6th element
For (int i = 0; I < 3; I + +) / / add 3 more elements
List.Add(i+20);
Int32 [] values = (int32 []) list.toarray (typeof ); / / returns the array contained in ArrayList

  • The difference between Array and ArrayList:
    (1) Array type variables must be instantiated (at least initializing the size of the array) at the same time of declaration, while ArrayList can only be declared first
    (2) Array can only store homogeneous objects, while ArrayList can store heterogeneous objects.
    Isomorphic objects refer to objects of the same type. If an array is declared as int [], it can only store integer data, and string [] can only store character data, except for the array declared as object [].
    The ArrayList can store any different type of data (because it contains boxed Object objects. In fact, the inner part of ArrayList uses such a private field as "Object []" items; "to encapsulate objects)
    (3) How to store in a CLR managed pair
    Array is always in continuous storage, while ArrayList is not always in continuous storage.
    (4) Initialize size
    The initialization of an Array object must only specify the size, and the created Array size is fixed. The size of an ArrayList can be specified dynamically. Its size can be specified during initialization or not. That is to say, the space of the object can be arbitrarily increased.
    (5) Array cannot add and delete items at will, while ArrayList can insert and delete items anywhere.

  • Similarities between Array and ArrayList
    #1 has index, that is, any item can be obtained and modified directly through index.
    #2 the objects they create are all placed in the managed heap.
    #3 can enumerate themselves (because they all implement the IEnumerable interface).
    Note:
    In C × 2.0, we suggest that you try to use the ArrayList of the template version, that is, the List under the system.collection.genetics namespace, which not only ensures the type security, but also improves the efficiency of object processing due to the lack of the process of boxing and unboxing.
    5. Android's five clock way to store data

    6.SQLite

    7.Adapter
    Adapter: adapter. The role of the adapter is to bridge Data and views. It is an adapter interface connecting back-end Data and front-end display, and an important link between Data and UI (View). Adapters are used in common View(ListView,GridView) and other places. As shown in the figure below, the relationship among Data, adapter and View is intuitively expressed:

    SimpleAdapter: not only can you deal with the situation that the list items are all text, but also can deal with the situation when there are other controls in the list items.
    ArrayAdapter: only when the list is full of text.
    Custom Adapter: according to the style defined in the xml file, the filling of waking list items is the most applicable.
    SimpleCursorAdapter: specially used to image the data in the cursor into the list

  • Declare the Adapter object and instantiate it according to the construction method. The details are as follows:

(1) Arrayadapter < data type > adapter = new arrayadapter < data type >;
(2) SimpleAdapter adapter = new SimpleAdapter (context: generally refers to the current Activity object, data: data source variable, layout: layout of each list item, new String [] {}: key in data source, new int [] {}: control ID of data source);
(3) Custom Adapter class adapter = new custom Adapter class construction method;
Bind Adapter object to Adapter: AdapterView object. setAdapter (Adapter object);

Conclusion:

1. When the code is written, the button and edit box should be named in accordance with the logical thinking. Do not name them casually, or the later code will be more disorderly.
2. Elegant code!!! To format pay attention to the format of writing

Operation result: first of all, you need to add new words and manually input word meaning. Then start to input the query word explanation.

Project directory:

Layout file: for reference only, it's a little ugly. It's important to understand the code.
1.activity_main.xml

The code is as follows:

<?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"
    android:orientation="vertical"
    tools:context=".MainActivity">
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <Button
        android:id="@+id/transport"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="300dp"
        android:layout_marginTop="16dp"
        android:text="translate"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />


</LinearLayout>


    <EditText
        android:id="@+id/search"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="194dp"
        android:layout_marginBottom="1dp"
        android:hint="Please enter the word to query"
        android:textSize="20dp"
        android:padding="20dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"></EditText>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="20dp"
    android:padding="10dp"
    android:text="The words and explanations are as follows:"></TextView>


    <Button
        android:id="@+id/btn_add"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="300dp"
        android:text="Add new words"
        />
    <ListView
        android:id="@+id/resylt_listView"
        android:layout_width="391dp"
        android:layout_height="200dp"
        android:layout_marginStart="4dp"
        android:layout_marginLeft="4dp"
        android:layout_marginBottom="264dp"
        android:background="#27A78570"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/search" />

</LinearLayout>

Add main.xml: interface for adding words

The code is as follows:

<?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:orientation="vertical"
    android:layout_height="match_parent"
    tools:context=".addActivity">

    <EditText
        android:id="@+id/dc"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Word"
        android:padding="20dp"
        android:layout_marginTop="100dp"></EditText>

    <EditText
        android:id="@+id/fy"
        android:padding="20dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="translate">
    </EditText>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:id="@+id/bc"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="180dp"
            android:text="Preservation">
        </Button>
        <Button
            android:id="@+id/qx"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="cancel">
        </Button>
    </LinearLayout>

</LinearLayout>

result_main.xml: used to display the result of the query and then displayed on the activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:layout_marginTop="320dp"
    >

    <TextView
        android:id="@+id/result_word"
        android:layout_width="wrap_content"
        android:layout_height="73dp"
        android:textSize="30sp"
        android:text="Word" />

    <TextView
        android:id="@+id/result_interpret"
        android:layout_width="wrap_content"
        android:layout_height="73dp"
        android:text="explain"
        android:textSize="30sp" />
</LinearLayout>

java code:

  1. Add "activity" to add new words
package com.example.acer.danci;

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;
//Step one:
//Add new words
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, "db_dict", null, 1);//Instantiate the DBOpenHelper object to create a database (four parameters: MainActivity.this context object, name, cursor factory, version number)
        final EditText etWord=findViewById(R.id.dc);//Get word edit box
        final EditText etInterpret=findViewById(R.id.fy);//Get translation edit box
        Button save=findViewById(R.id.bc);//Get save button
        Button back=findViewById(R.id.qx);   //Get cancel button
        save.setOnClickListener(new View.OnClickListener() { //To store the added word explanation in the database
            @Override
            public void onClick(View v) {
    String word=etWord.getText().toString();    //Get the input word
                String interpret=etInterpret.getText().toString();    //Get the explanation filled in
                if (word.equals("")||interpret.equals("")){ //Judge whether the input word and explanation are empty
                    Toast.makeText(addActivity.this,"The entered word or explanation is empty",Toast.LENGTH_LONG).show();

                }else {
insertData(dbOpenHelper.getReadableDatabase(),word,interpret);  //Insert new words
                    Toast.makeText(addActivity.this,"Add new words successfully",Toast.LENGTH_LONG).show();

                }
            }
        });
        back.setOnClickListener(new View.OnClickListener() { //Return to query interface
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(addActivity.this,MainActivity.class);  //Jump to query page through intent
                startActivity(intent);
            }
        });
    }
    //How to insert data
    private void insertData(SQLiteDatabase sqLiteDatabase,String word,String interpret){
        ContentValues values=new ContentValues();
        values.put("word",word); //Save words
        values.put("detail",interpret); //Preservation Interpretation
        sqLiteDatabase.insert("tb_dict",null,values);   //Perform insert operation
    }
    @Override   //Close database connection
    protected void onDestroy(){
        super.onDestroy();
        if (dbOpenHelper!=null){
            dbOpenHelper.close();
        }
    };
}

  1. Create database to store data: DBOpenHelper.java
package com.example.acer.danci;

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 {
    final String CREATE_TABLE_SQL="create table tb_dict (id integer primary key autoincrement,word,detail)";//Create the SQL statement for the data table. Auto number, data type is default
    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) {   //Create data table
        db.execSQL(CREATE_TABLE_SQL);   //Create a data table for words


    }

    @Override   //Version update
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.i("Dictionary","--Version update"+"oldVersion"+"-->"+newVersion);
    }
}

3. Realize the function of translation activity ﹣ main.java

package com.example.acer.danci;

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;

//Realize translation function
public class MainActivity extends AppCompatActivity {
private DBOpenHelper dbOpenHelper;  //Declare DBOpenHelper object



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dbOpenHelper = new DBOpenHelper(MainActivity.this, "db_dict", null, 1);//Instantiate the DBOpenHelper object to create a database (four parameters: MainActivity.this context object, name, cursor factory, version number)
        final ListView listView = findViewById(R.id.resylt_listView); //Get the ListView of the displayed results
        final EditText etSearch = findViewById(R.id.search);  //Get the edit box of the query content
        final Button add = findViewById(R.id.btn_add);  //Get button to add word
        Button search = findViewById(R.id.transport); //Get query button
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, addActivity.class);
                startActivity(intent);

            }
        });
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String key = etSearch.getText().toString();   //Get query words
                Cursor cursor = dbOpenHelper.getReadableDatabase().query("tb_dict", null, "word=?", new String[]{key}, null, null, null);  //Specify the table to query, the column to query, query all without specifying, specify the query criteria to use placeholders, and specify the value of placeholders
                //Processing query results query results saved in arrayList
                ArrayList<Map<String, String>> resultList = new ArrayList<Map<String, String>>();   //The results are saved in the ArrayList object
                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) {    //Judge whether there is data in the database
                    //Display prompt message, no relevant record
                    Toast.makeText(MainActivity.this, "No record", Toast.LENGTH_LONG).show();

                } else {
                    //Otherwise, the results of the query will be displayed in the 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   //Close database connection
       protected void onDestroy(){
            super.onDestroy();
            if (dbOpenHelper!=null){
                dbOpenHelper.close();
            }
        };

}
57 original articles published, praised 5, 4695 visitors
Private letter follow

Tags: Android Database SQL xml

Posted on Mon, 13 Jan 2020 22:08:46 -0800 by JoeDaStudd