Copyright: May not be reproduced without the permission of the blogger

supplement

To supplement the previous section, using ListView to display list items requires two XML files, one for the list layout and one for the layout of individual list items. For example, when we want to display all app list items in the system, we need appImage view on the left and text view on the right.

One is the list layout

all_app_list.xml

<ListView
 android:id="@android:id/app_list"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"/>
Copy the code

Layout of a single list item

list_item.xml

<ImageView
        android:id="@+id/icon_image_view"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:src="@mipmap/ic_launcher"/>
<TextView
        android:id="@+id/title_text_view"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:text="@string/app_name"
        android:textSize="24sp"/>
Copy the code

AsyncTask:

For Android AsyncTask is lighter than Handler, suitable for simple asynchronous processing. Handler and AsyncTask do not block the main thread, which is the UI thread. UI updates can only be processed in the main thread, so asynchronous processing is necessary in Android development.

AsyncTask is a background task class that Android encapsulates and inherits from the Object class. When importing the android.os.AsyncTask, it provides three generic parameters in the inheritance AsyncTask and overloads several methods.

The three generic parameter types are Params, Progress, and Result. For example, Params is the input parameter to start the task execution, Progress is the percentage of the task execution, and Result is the Result of the execution.

The following methods are then overridden

  • doInBackground(Params...): Background execution and time-consuming operations are here.
  • onPostExecute(Result): This method is executed in the main thread.
  • onProgressUpdate(Progress): Displays the progress of task execution.
  • onPreExecute(): The interface that calls Excute.
  • onCancelled(): Is used when calling the cancel task.

GridView

GridView can be used to achieve a grid effect, is more commonly used as ListView multi-control layout.

GridView layout, common properties are:

android:columnWidth
android:numColumns
android:verticalSpacing
android:horizontalSpacing
android:stretchMode
android:cacheColorHint
android:listSelector

<GridView
 android:id="@+id/gridview"
 android:numColumns="auto_fit"
 android:verticalSpacing="10dp"
 android:horizontalSpacing="10dp"
 android:layout_width="match_parent"
 android:layout_height="match_parent"/>
Copy the code

CardView

CardView is also a kind of layout, like CARDS, a lot like the male tweets, with shadows and rounded corners, this kind of commonly used controls such as news video, Android5.0 is new, you need to import the com. When using android. Support: CardView – v7: ~ more unified version number.

Properties:

<android.support.v7.widget.CardView
        app:cardBackgroundColor="# 000000"
        app:cardCornerRadius="10dp"
        app:contentPadding="10dp"
        android:layout_width="wrap_content"
        android:layout_gravity="center"
        android:layout_height="wrap_content">
        <TextView
            android:gravity="center"
            android:layout_width="200dp"
            android:layout_height="50dp"
            android:text="Hello World!"/>
</android.support.v7.widget.CardView>
Copy the code

Information:

Public class Message {private int id; private int imgResId; private String title; private String content; // Create constructor publicMessage(){ } public Message (int id, int imgResId, String title, String content) { this.id = id; this.imgResId = imgResId; this.title = title; this.content = content; } // Automatically import public intgetId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getImgResId() {
        return imgResId;
    }

    public void setImgResId(int imgResId) {
        this.imgResId = imgResId;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) { this.content = content; }}Copy the code

The adapter:

Public class MessageAdapter extends BaseAdapter{//Context Context private Context mContext; // Render layout private LayoutInflater mInflater; Private List<Message> mDatas; Public MessageAdapter (Context Context, List<Message> datas){mContext = Context; mInflater = LayoutInflater.from(context); // specify mDatas = datas; } @Override public intgetCount() {// Get the data lengthreturnmDatas.size(); } @override public Msg getItem(int position)returnmDatas.get(position); } @override public long getItemId(int position)returnposition; } @override public View getView(int position, View convertView, ViewGroup parent) {// create ViewHolder ViewHolder ViewHolder = null; // If it is nullif(convertView == null){// minflater.inflate (render layout, parent,false)
         convertView = mInflater.inflate(R.layout.item_msg,parent,false); viewHolder = new ViewHolder(); Viewholder. mIvImg = convertView.findViewById(r.idd_iv_img); viewHolder.mTvTitle = convertView.findViewById(R.id.id_tv_title); viewHolder.mTvContent = convertView.findViewById(R.id.id_tv_content); convertView.setTag(viewHolder); // convertView.getTag(); }else{ viewHolder = (ViewHolder) convertView.getTag(); // convertView.getTag(); Message MSG = mdatas.get (position); Private List<Message> mDatas; viewHolder.mIvImg.setImageResource(msg.getImgResId()); / / get photo position viewHolder. MTvTitle. SetText (MSG) getTitle ()); / / get title viewHolder. MTvContent. SetText (MSG) getContent ()); // Get the contentreturnconvertView; } public static class ViewHolder{ImageView mIvImg; TextView mTvTitle; TextView mTvContent; }}Copy the code

The rest is ok.

Data storage mode

Four:

  1. SharedPreferences
  2. SQLite
  3. Content Provider
  4. File

Local data store

Shared Preferences are stored as key-values. (support for Boolean, int, float, long, string); The Internal Storage has high data security and limited space. External Storage is the opposite of Internal Storage.

SharedPreferences is a lightweight data store, an XML-based key-value pair store that stores simple information.

SharedPreferences can only obtain data and cannot be stored or modified, but can be stored and modified through the Editor.

SharedPreferences.Editor Editor’s putXXX method editor.mit ()

SharedPreferences sharedPreferences = getSharedPreferences("sharedPreferences", MODE_PRIVATE);
Editor editor = sharedPreferences.edit();
editor.putXXX();
editor.commit();
Copy the code

Create a class

SharedPreferences sharedPreferences = getSharedPreferences("text",Context.MODE_PRIVATE);
sharedPreferences.edit().putInt("test",1).commit(); Int value = sharedPreferences. GetInt ("test", 0);Copy the code

SQLite database

SQLite is a kind of lightweight system database, essentially binary files, the so-called relational, is a relational schema, here represents the two-dimensional table structure schema. In a relational database, column attributes in a two-dimensional table are called fields. Behavior records, such as objects; The range of values in a property is called a field.

Here we need to learn database, such as DDL, DML, data definition language and data manipulation language, create tables and add, delete, change and check.

SQLiteOpenHelper SQLiteDatabase SQLiteOpenHelper SQLiteDatabase SQLiteOpenHelper And two rawQuery() methods: for query and execSQL() : for add, delete, change, and query. SQLiteDatabase is provided on Android to create objects using API classes encapsulated without writing database syntax. Query (),insert(),delete(), and update(), respectively.

SQLite, in the form of a single file storage, storage 2T memory, in the form of b-tree.

SQLiteDatabase db = openOrCreateDatabase("table.db", MODE_PRIVATE, null);
Copy the code

SQL

insert into student values("077555"."dashu"."1444.2.2"."Male"); select... from... where... update student set... where...Copy the code

Relational data integrity is a constraint on a relationship

  • Entity integrity: Limits the primary code
  • Referential integrity: Limits the external code
  • User-defined integrity: Restrictions on specific data

Characteristics of relational database (1) Simple data structure. (2) Strong function. (3) Easy to use. (4) High data independence.

The main function of SQL (1) data definition function. (2) Data manipulation function. (3) Data control function.

Sqlite: Efficient, open source, small, application-driven, transaction support, no data type, embeddable relational database, independent, cross-platform, less code, easy to use.

Create a table sentence

// Notice that the _id is written in Android in this form, Create table student(_id Integer primary key autoincrement, name vARCHar (10), age Integer not NULL) create table student(_id Integer primary key autoincrement, name varchar(10), age Integer not NULL)Copy the code

Delete table

drop table student;
Copy the code

Insert data

Insert into values; Insert into student (_id, age) values (1, 2); insert into student values(1,"vic"17);Copy the code

Modify the data

update student set name="dashu",age=17 where _id=1;
Copy the code

Update the data

Update the table namesetField = condition for value updatesCopy the code

Delete the data

Delete from table name [delete condition]; delete from studentwhere _id=1;
Copy the code

The query

Select column name from table namewhereConditions; Order by desc select * from student; select _id from student; select * from studentwhere _id=1 and age>17;
select * from student where age like "% 1%";
select * from student where age>17 order by _id=1;
Copy the code

SQLite

/ / SD card path, then the database location is under the specified path String path = Environment. External.getexternalstoragedirectory () +"/student.db";
Copy the code
// Three arguments, this, context, path = path, null = none, the last one is int, Version SQLiteOpenHelper Helper = new SQLiteOpenHelper(this,path,null,1) {@override public void onCreate(SQLiteDatabase) SqLiteDatabase) {// Create toast.makeText (mainactivity.this,"Database created successfully",Toast.LENGTH_SHORT).show(); // If the database does not exist, the onCreate method String SQL = is called"create table info_tb_student (_id integer primary key autoincrement," +
                      "name varhcar(20)," +
                       "age integer, "+
                       "gender varhcar(4) )"; sqLiteDatabase.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, Int i1) {// Update prompt toast.maketext (mainactivity.this,"Database Upgrade",Toast.LENGTH_SHORT).show(); }}; / / if found that can't find the database above, because no call below code helper. GetReadableDatabase ();Copy the code

If you like it, give it a thumbs up! My goal is to get better and better every day