3. Introduction to Database and Basic Use of listview

Posted by eightonesix on Thu, 11 Jul 2019 19:51:04 +0200

1 Database Creation under Android

When do we use databases for data storage? When large amounts of data with the same structure need to be stored.
MySQL SQL Server 2000 SQLite embedded lightweight

SqliteOpenHelper

Create a database step:
1. To create a class integration SqliteOpenHelper, you need to add a constructor to implement two methods, oncreate and onupgrade.
    Introduction of the parameters in the construction method:

    // context, name: The name of the database file factory: used to create cursor objects, default to null 
    // version: The version number of the database. Starting from 1, if it changes, the onUpgrade method will be called. After 4.0, it can only be upgraded.
    super(context, "info.db", null,1);


2. Creating an object of this help class and calling the getReadableDatabase() method will help us create and open a database.

3. Overwriting oncreate and onupgrdate methods:
    The oncreate method is called when the database is first created; it is especially suitable for initializing the table structure and needs to execute sql statements; SQLiteDatabase db can be used to execute sql statements.

    // onUpgrade database version number changes before execution; especially suitable for table structure modification



Both getWritableDatabase and getReadableDatabase in the help class object can help us obtain a database operation object SqliteDatabase.

Difference:
getReadableDatabase:
    First try to open the database in read-write mode. If the disk space is full, he will try to open the database in read-only mode again.
getWritableDatabase:
    Open the database directly by reading and writing. If the disk space is full, it will report the error directly.

2 Addition, deletion and modification of database in Android

1.Create an object of a help class and call it getReadableDatabase Method, return one SqliteDatebase object

2.Use SqliteDatebase Object Call execSql()Addition, deletion and modification,call rawQuery Method Query.

******Characteristic:Addition, deletion and alteration have no return value and cannot be judged. sql Is the statement executed successfully? sql Statements written manually are prone to errors



private MySqliteOpenHelper mySqliteOpenHelper;
public InfoDao(Context context){
    //Create a Help Class Object
    mySqliteOpenHelper = new MySqliteOpenHelper(context);


}

public void add(InfoBean bean){

    //Executing sql statements requires sqliteDatabase objects
    //Initialize database creation by calling getReadableDatabase method
    SQLiteDatabase  db = mySqliteOpenHelper.getReadableDatabase();
    //The placeholder value in the sql:sql statement, bindArgs: SQL statement
    db.execSQL("insert into info(name,phone) values(?,?);", new Object[]{bean.name,bean.phone});
    //Close database objects
    db.close();
}

public void del(String name){


    //Executing sql statements requires sqliteDatabase objects
    //Initialize database creation by calling getReadableDatabase method
    SQLiteDatabase db = mySqliteOpenHelper.getReadableDatabase();
    //The placeholder value in the sql:sql statement, bindArgs: SQL statement
    db.execSQL("delete from info where name=?;", new Object[]{name});
    //Close database objects
    db.close();

}
public void update(InfoBean bean){

    //Executing sql statements requires sqliteDatabase objects
    //Initialize database creation by calling getReadableDatabase method
    SQLiteDatabase db = mySqliteOpenHelper.getReadableDatabase();
    //The placeholder value in the sql:sql statement, bindArgs: SQL statement
    db.execSQL("update info set phone=? where name=?;", new Object[]{bean.phone,bean.name});
    //Close database objects
    db.close();

}
public void query(String name){

    //Executing sql statements requires sqliteDatabase objects
    //Initialize database creation by calling getReadableDatabase method
    SQLiteDatabase db = mySqliteOpenHelper.getReadableDatabase();
    //sql:sql statement, selectionArgs: Query the value of the conditional placeholder and return a cursor object
    Cursor cursor = db.rawQuery("select _id, name,phone from info where name = ?", new String []{name});
    //Parsing Data in Cursor
    if(cursor != null && cursor.getCount() >0){//Determine whether data exists in cursor

        //Loop through the result set to get the contents of each row
        while(cursor.moveToNext()){//Conditions, whether the cursor can be positioned on the next line
            //get data
            int id = cursor.getInt(0);
            String name_str = cursor.getString(1);
            String phone = cursor.getString(2);
            System.out.println("_id:"+id+";name:"+name_str+";phone:"+phone);
        }
        cursor.close();//Close the result set

    }
    //Close database objects
    db.close();

}

3 Another way to add, delete and modify search under Android

1.Create an object of a help class and call it getReadableDatabase Method, return one SqliteDatebase object

2.Use SqliteDatebase Object Call insert,update,delete ,query Methods Addition, deletion and alteration were performed.

******Characteristic:Addition, deletion and alteration can be judged by the return value. sql Statement execution is successful, but the query is not flexible enough to do multi-table query. So in the company, ordinary people like to use the second way to add or delete, and the first way to query.

        private MySqliteOpenHelper mySqliteOpenHelper;
public InfoDao(Context context){
    //Create a Help Class Object
    mySqliteOpenHelper = new MySqliteOpenHelper(context);
}

public boolean add(InfoBean bean){

    //Executing sql statements requires sqliteDatabase objects
    //Initialize database creation by calling getReadableDatabase method
    SQLiteDatabase  db = mySqliteOpenHelper.getReadableDatabase();


    ContentValues values = new ContentValues();//An object encapsulated in map to store values
    values.put("name", bean.name);
    values.put("phone", bean.phone);

    //Table: table name, nullColumn Hack: you can add a blank line for null, label, values: the value of a row of data, return value: Id for adding this new row, and - 1 for adding failure
    long result = db.insert("info", null, values);//The bottom line is to assemble sql statements

    //Close database objects
    db.close();

    if(result != -1){//- 1 represents add failure
        return true;
    }else{
        return false;
    }
}

public int del(String name){

    //Executing sql statements requires sqliteDatabase objects
    //Initialize database creation by calling getReadableDatabase method
    SQLiteDatabase db = mySqliteOpenHelper.getReadableDatabase();

    //table: table name, whereClause: Delete condition, whereArgs: placeholder parameter for condition; Return value: How many rows were successfully deleted
    int result = db.delete("info", "name = ?", new String[]{name});
    //Close database objects
    db.close();

    return result;

}
public int update(InfoBean bean){

    //Executing sql statements requires sqliteDatabase objects
    //Initialize database creation by calling getReadableDatabase method
    SQLiteDatabase db = mySqliteOpenHelper.getReadableDatabase();
    ContentValues values = new ContentValues();//An object encapsulated in map to store values
    values.put("phone", bean.phone);
    //Table: table name, values: updated value, whereClause: updated condition, whereArgs: updated condition placeholder value, return value: how many rows were successfully modified
    int result = db.update("info", values, "name = ?", new String[]{bean.name});
    //Close database objects
    db.close();
    return result;

}
public void query(String name){

    //Executing sql statements requires sqliteDatabase objects
    //Initialize database creation by calling getReadableDatabase method
    SQLiteDatabase db = mySqliteOpenHelper.getReadableDatabase();

    //table: table name, columns: column name of the query, if null represents all columns of the query; selection: query condition, selectionArgs: parameter value of conditional placeholder,
    //groupBy: groupBy by what fields, have: Grouping conditions, orderBy: Sort by what fields
    Cursor cursor = db.query("info", new String[]{"_id","name","phone"}, "name = ?", new String[]{name}, null, null, "_id desc");
    //Parsing Data in Cursor
    if(cursor != null && cursor.getCount() >0){//Determine whether data exists in cursor

        //Loop through the result set to get the contents of each row
        while(cursor.moveToNext()){//Conditions, whether the cursor can be positioned on the next line
            //get data
            int id = cursor.getInt(0);
            String name_str = cursor.getString(1);
            String phone = cursor.getString(2);
            System.out.println("_id:"+id+";name:"+name_str+";phone:"+phone);


        }
        cursor.close();//Close the result set

    }
    //Close database objects
    db.close();

}

4 database transactions

Transactions: multiple executions sql Statements can either be executed successfully at the same time or fail at the same time. Some cannot succeed or others fail.

//Bank transfer


//Click the button to execute the method
public void transtation(View v){
    //1. Create an object of a help class
    BankOpenHelper bankOpenHelper = new BankOpenHelper(this);
    //2. Call database to help getReadable Database of class object create database, initialize table data, get a SqliteDatabase object to do transfer (sql statement)
    SQLiteDatabase db = bankOpenHelper.getReadableDatabase();
    //3. Transfer, reduce Li Si's money by 200, Zhang San plus 200
    db.beginTransaction();//Open a database transaction
    try {
        db.execSQL("update account set money= money-200 where name=?",new String[]{"Li Si"});
        int i = 100/0;//Simulate an anomaly
        db.execSQL("update account set money= money+200 where name=?",new String[]{"Zhang San"});

        db.setTransactionSuccessful();//All sql statements in markup transactions were successfully executed
    } finally {
        db.endTransaction();//Determine whether the transaction's markup succeeds or, if not, roll back the sql statement executed before the error 
    }
}

5 listview introduction

    ListView Is a control,A control that displays entries in a vertically scrolled list, the contents of which are derived from one ListAdapter . EditText Button TextView ImageView Checkbox Five layouts.


    1.Layout addition Listview

    2.find listview

    3.Create a Adapter Adapter inheritance BaseAdapter,Four encapsulation methods, of which getcount,getview Must be encapsulated
        getcount:tell listview Number of entries to display
        getview: tell listview The content displayed by each entry.
    4.Establish Adapter An object that is set to listview. 
            listview.setAdapter(ListAdapter adapter);

6 listview optimization

adapter in getview A method will come in. convertView,convertView It refers to the one that has been used. view Objects can be reused, but before they are used, it is necessary to determine whether they are empty, not directly reused for empty, and act as getview Method's return object.
        TextView view = null;
        if(convertView != null){//Determine whether converView is empty and not reused for empty
            view = (TextView) convertView;
        }else{
            view = new TextView(mContext);//Create a textView object
        }
        return view;

7 listview - slot machine

javaweb mvc
m....mode....javabean
v....view....jsp
c....control...servlet

listview mvc
m....mode....Bean
v....view....listview
c....control...adapter

8 listview Display Principle (Understanding)

1. Consider the number of entries getcount displayed by listview
 2. Consider the content getview displayed by each entry in listview
 3. Consider the height of each item because of the diversity of screens
 4. Consider also the sliding of listview to monitor the disappearance of an old entry and the display of a new entry.

9 Complex listview interface shows Black Horse News (* Important *)

1.Layout Writing listview

2.find listview

3.Get news data encapsulated into list In a set(Only use analog data),Act as adapter Display data,How to get the news data to adapter???

4.Create a adapter inherit BaseAdapter,Realize four methods
    getcount: There are as many news items as there are news data.
    getView:Return a complex layout to display as the content of the entry; and the data displayed is news information.?????

public View getView(int position, View convertView, ViewGroup parent) {
    View view = null;
    //1. Reuse converView to optimize listview and create a view as the return value of getview to display an entry
    if(convertView != null){
        view = convertView;
    }else {
        //context: context, resource: To convert the layout ID of the view object, root: wraps the layout with a layer of root(ViewGroup) as the return value of getview, and generally passes null.
        view = View.inflate(context, R.layout.item_news_layout, null);//Convert a layout file into a view object
    }
    //2. Get child control objects on view
    ImageView item_img_icon = (ImageView) view.findViewById(R.id.item_img_icon);
    TextView item_tv_des = (TextView) view.findViewById(R.id.item_tv_des);
    TextView item_tv_title = (TextView) view.findViewById(R.id.item_tv_title);
    //3. Get the news data in the list set corresponding to the postion location entry, the Bean object
    NewsBean newsBean = list.get(position);
    //4. Set the data to these sub-controls for display
    item_img_icon.setImageDrawable(newsBean.icon);//Pictures for setting up imageView
    item_tv_title.setText(newsBean.title);
    item_tv_des.setText(newsBean.des);

    return view;
}

5.Create a adapter Objects are set to listview

6.Set up listview Click events for entries and encapsulate click events,Check out the details of the news. ?????????
    //Setting Click Events for listview Items
    lv_news.setOnItemClickListener(this);

        //The method parent is called when an item of listview is clicked: the view object position on the item that represents listviw view: the location id of the item: the id of the item

public void onItemClick(AdapterView<?> parent, View view, int position,
        long id) {

    //You need to get the url in the bean object on the entry to make a jump
    NewsBean bean = (NewsBean) parent.getItemAtPosition(position);

    String url = bean.news_url;

    //Jump Browser
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_VIEW);
    intent.setData(Uri.parse(url));
    startActivity(intent);
}



1.Layout Writing listview ok

2.find listview ok 

3.Encapsulating news data to list In a collection, the purpose is to adapter Provide data display. ok 

4.Encapsulate one Adapter Class Inheritance BaseAdatper,Write a construction method to accept list Collecting data and copying four methods
    a.Create a constructor  ok 
    b.encapsulation getCount Method   ok 
    c.getView Method: No ok
        1.multiplexing convertview,Template code,If not, you need to convert a layout file to view Object as getview The return object of the.
            view = View.inflater(Context context, int resuorceId,ViewGroup root)
        2.find view These child controls on the list In a collection bean Data is set to these subcontrols one by one

        3.from list Acquisition in a collection postion Data to be displayed on entries Bean

        4.What will be acquired bean The data in the
    d.getItem Method: list Specify in a collection postion Upper bean Object return
    e.getItemId,Direct return postion

5.Create an encapsulated Adapter Object, set to listview   ok
6.Set up listview Click events for entries  ok
    listview.setOnItem....

7.Make carbon copies OnItemClicklistener Method, get the corresponding entries on the _____________ bean Object, eventually obtained url,do Intent Jump;  No ok

10 Commonly used ways to get inflate

        1.
        //context: context, resource: To convert the layout ID of the view object, root: wraps the layout with a layer of root(ViewGroup) as the return value of codify, and generally passes null.
            //view = View.inflate(context, R.layout.item_news_layout, null); // Convert a layout file into a view object

        2.
        //Converting Layout to view Object through LayoutInflate
        //view =  LayoutInflater.from(context).inflate(R.layout.item_news_layout, null);

        3.
        //Get a LayoutInflater from the system service through context, and convert a layout into a view object through LayoutInflate
        LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = layoutInflater.inflate(R.layout.item_news_layout, null);

11 arrayadapter

    //Find Control
    ListView lv_array = (ListView) findViewById(R.id.lv_array);
    ListView lv_simple = (ListView) findViewById(R.id.lv_simple);

    //Create an arrayAdapter
//Context, resource: layout id, textViewResourceId: ID of textview control in item layout, objects: content displayed by texitview on item layout
    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, R.layout.item_listview_layout, R.id.item_tv_class, classz);
    lv_array.setAdapter(arrayAdapter);

12 simpleadapter

    //Create a simple adapter that encapsulates the data of the simple adapter
    ArrayList<Map<String, String>> arrayList = new ArrayList<Map<String,String>>();
    HashMap<String, String> hashMap = new HashMap<String, String>();
    hashMap.put("class", "C++");
    arrayList.add(hashMap);

    HashMap<String, String> hashMap1 = new HashMap<String, String>();
    hashMap1.put("class", "android");
    arrayList.add(hashMap1);


    HashMap<String, String> hashMap2 = new HashMap<String, String>();
    hashMap2.put("class", "javaEE");
    arrayList.add(hashMap2);

    //context, data: Displayed data, resource:item layout id, from: key in map, to: control ID in layout
    SimpleAdapter simpleAdapter = new SimpleAdapter(this, arrayList, R.layout.item_listview_layout, new String[]{"class"}, new int[]{R.id.item_tv_class});

    lv_simple.setAdapter(simpleAdapter);

listview interface display of 13 database (news conference, this will be)

Topics: Database SQL Android MySQL