Android Development--notes (i)

Source: Internet
Author: User
Tags sqlite recyclerview android

My last blog, http://blog.csdn.net/callmesp/article/details/52895630, is about ListView and Recyclerview, and the cause is the problem when you want to develop a sticky note. After studying the Recyclerview, I spent some time this morning writing this app out (the level is limited) to share with you. First on the overall interface diagram bar.

looks ok ... Not too ugly.
then the structure diagram. The

is followed by the code. First recycle_new the

<?xml version= "1.0" encoding= "Utf-8"?> <android.support.design.widget.coordinatorlayout 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 "and Roid:fitssystemwindows= "true" tools:context= "com.example.notes_2.MainActivity" > <relativelayout andr Oid:layout_width= "Match_parent" android:layout_height= "match_parent" > <android.support.design.widge
            T.appbarlayout android:layout_width= "match_parent" android:layout_height= "Wrap_content" Android:theme= "@style/apptheme.appbaroverlay" android:id= "@+id/aaa" > <android.support.v7. Widgets. Toolbar android:id= "@+id/toolbar" android:layout_width= "Match_parent" Andr Oid:layout_height= "? attr/actionbArsize "android:background="? Attr/colorprimary "App:popuptheme=" @style/apptheme.popupoverl
            Ay "/> </android.support.design.widget.AppBarLayout> <android.support.v7.widget.recyclerview android:layout_below= "@+id/aaa" android:id= "@+id/recycle" android:layout_width= "fill_p" Arent "android:layout_height=" Match_parent "android:layout_weight=" 1 "> </android.sup port.v7.widget.recyclerview> <android.support.design.widget.floatingactionbutton android:id= "@+ Id/fab "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "Andro" Id:layout_gravity= "Bottom|end" android:src= "@android:d rawable/ic_menu_add" Android:layout_alignpar Entbottom= "true" android:layout_centerhorizontal= "true"/> </RelativeLayout> </android.support . Design.widget.CoordinatOrlayout>
 

The preceding appbarlayout is created automatically when you create project without the need to control it, you can also set a button on the toolbar to add an edit function (this feature has not yet been achieved, not yet learned.) And then come back and write an Android development – Sticky Note (ii), and tell me if you have any suggestions. The following two controls are the focus, and a recyclerview is responsible for displaying information and a Floatingactionbutton suspension button to trigger an increase in the sticky note event. Do not understand can see my last blog here is not in detail to say.
The following is List_item

<?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 "an" Droid:layout_width= "Match_parent" android:layout_height= "wrap_content" android:paddingleft= "@dimen/activity_ Horizontal_margin "android:paddingright=" @dimen/activity_horizontal_margin "app:layout_behavior=" @string/appbar_ Scrolling_view_behavior "tools:context=" com.example.notes_2.MainActivity "android:orientation=" vertical "> < Android.support.v7.widget.CardView xmlns:card_view= "Http://schemas.android.com/apk/res-auto" Android:layout_ Width= "Match_parent" android:layout_height= "wrap_content" card_view:cardbackgroundcolor= "#FFFFB9" CARD_VIEW:CA rdcornerradius= "10DP" card_view:cardpreventcorneroverlap= "true" card_view:cardusecompatpadding= "true" Card_vie
w:contentpadding= "10DP" > <linearlayout        Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:orientation= "vert"
        ical "> <textview android:layout_width=" wrap_content "android:layout_height=" Wrap_content " android:paddingleft= "10SP" android:paddingright= "10sp" android:paddingtop= "15SP" Android:singlel Ine= "true" android:id= "@+id/time"/> <textview android:id= "@+id/content" Android:layout_ Width= "Wrap_content" android:layout_height= "wrap_content" android:ellipsize= "End" Android:paddingl eft= "10SP" android:paddingright= "10sp" android:paddingtop= "15sp" android:paddingbottom= "15SP"/&gt
    ;
 </LinearLayout> </android.support.v7.widget.CardView> </LinearLayout>

A cardview was used here.

<android.support.v7.widget.cardview
    xmlns:card_view= "Http://schemas.android.com/apk/res-auto"
    Android:layout_width= "Match_parent"
    android:layout_height= "wrap_content"
    Card_view:cardbackgroundcolor = "#FFFFB9"
    card_view:cardcornerradius= "10DP"
    card_view:cardpreventcorneroverlap= "true"
    Card_view: Cardusecompatpadding= "true"
    card_view:contentpadding= "10DP" >

is also a relatively new control, this is learned today, here is a simple call, there is nothing to say, if there is time to in-depth research, study a variety of customizations, and then write a blog. Now, it's worth noting that I nested a linearlayout inside and then wrote two TextView in it, why do I have to do this rather than write two textview directly? Here in fact I did not add, but in the test when found two textview coincide, I feel that this cardview is equivalent to a modified style changed the background of a framelayout, so to first nest and then use, It's more convenient than customizing everything. Then two TextView one to display the time a display content.
The main content begins below.
Dbhelper.java

Package com.example.notes_2;
Import android.content.ContentValues;
Import Android.content.Context;
Import Android.database.Cursor;
Import Android.database.sqlite.SQLiteDatabase;
Import Android.database.sqlite.SQLiteOpenHelper;

Import Android.util.Log;
Import Java.text.SimpleDateFormat;

Import Java.util.Date;
 /** * Created by me on 2016/10/23.
    * * public class DBHelper extends Sqliteopenhelper {private final static String db_name= "My.db";
    Private final static int db_version=1;
    Private final static String table_name= "info";
    Private final static String content= "CONTENT";
    Private final static String time= "date";
    Private final static String id= "_id";
    Sqlitedatabase database=getwritabledatabase ();
    Public DBHelper {super (context,db_name,null,db_version); //paramsqlitedatabase.execsql ("CREATE TABLE" + NAME +) (ID INTEGER PRIMARY KEY autoincrement,title text,date text,c
    Ontent TEXT) "); @Override public void OncreatE (sqlitedatabase database) {database.execsql ("CREATE TABLE" + table_name +) (_id INTEGER PRIMARY KEY autoincremen
    T,date text,content TEXT) "); @Override public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {} public long Inser
        T (String text) {contentvalues contentvalues=new contentvalues ();

        Contentvalues.put ("content", text);
        Get the system time SimpleDateFormat formatter=new SimpleDateFormat ("Yy-mm-dd hh:mm");
        Date curdate = new Date (System.currenttimemillis ());


        String Time=formatter.format (curdate);
        Contentvalues.put ("date", time);
        Long Row=database.insert (table_name,null,contentvalues);
        LOG.E ("Time:", time);
        LOG.E ("content", text);
    return row;
        public void Update (int _id,string text) {contentvalues contentvalues=new contentvalues ();
        Contentvalues.put ("content", text); Database.update (table_name,contentvalues,id+ "=?", New StriNg[]{integer.tostring (_ID)});
    public void Delete (int _id) {Database.delete (table_name, id + "=?", new String[]{integer.tostring (_ID)});
        Public Cursor Select () {Cursor cursor=database.query (table_name,null,null,null,null,null,null);
    return cursor; }/* Public long Add (sqlitedatabase paramsqlitedatabase, Notepad paramnotepad) {contentvalues Localcontentvalue
        s = new Contentvalues ();
        Localcontentvalues.put ("title", Paramnotepad.gettitle ());
        Localcontentvalues.put ("Date", Paramnotepad.getdata ());
        Localcontentvalues.put ("Content", paramnotepad.getcontent ());
        Long L = paramsqlitedatabase.insert (table, NULL, localcontentvalues);
        Paramsqlitedatabase.close ();
    return l; }

 */

This is the core of the project, a database Help class, here with SQLite a lightweight database, I will specifically write a blog about it. This is a simple way to get to know each other first. It has a few parameters, but also in the construction of the need, database name, database version, table name, ID, as well as the contents of the table, you can freely set.

Sqlitedatabase database=getwritabledatabase ();

This uses a basic class to get permission to read and write to the database, otherwise it will flash back. Then there is the rewriting, adding, deleting, inserting, updating, and so on of its various functions. When you put the content, you use a contentvalues, a key value pair. For example, Contentvalues.put ("content", text), is to give the contents of the text to the table "content" this column. Nothing else is left.

Then write an adapter adpter to fit our recyclerview.

Package com.example.notes_2;
Import Android.content.Context;
Import Android.database.Cursor;
Import Android.support.v7.widget.RecyclerView;
Import Android.view.LayoutInflater;
Import Android.view.View;
Import Android.view.ViewGroup;
Import Android.widget.ImageView;

Import Android.widget.TextView;

Import java.util.List;
 /** * Created by me on 2016/10/23. * * public class Myrecycleradapter extends recyclerview.adapter<myrecycleradapter.myviewholder> {private LIST&L T
    String> Mdatas;
    Private context Mcontext;
    Private Layoutinflater Inflater;
    Private Cursor mmcursor;
    Private DBHelper Mmdbhelper;
    int k=0;
    Private Onitemclicklistener Monitemclicklistener;
        Public Myrecycleradapter (Context context,cursor Cursor,dbhelper dbhelper) {this.mcontext=context;
        This.mmcursor=cursor;
        This.mmdbhelper=dbhelper; Inflater= Layoutinflater.
    From (Mcontext); @Override public int GetItemCount () {return mmcursor.GetCount ();  The controls in the holder returned by the Oncreateviewholder method are populated @Override public void Onbindviewholder (Myviewholder holder, final int
        Position) {mmcursor.movetoposition (Mmcursor.getcount ()-position-1);
        Holder.tv_time.setText (mmcursor.getstring (1));
        Holder.tv_content.setText (mmcursor.getstring (2));  Implement interface if (monitemclicklistener!= null) {Holder.itemView.setOnClickListener (New View.onclicklistener ()) {@Override public void OnClick (View v) {monitemclicklistener.onclic
                K (position);
        }
            }); }///override Oncreateviewholder method to return a custom Viewholder @Override public myviewholder oncreateviewholder (Viewgrou
        P parent, int viewtype) {View view = Inflater.inflate (R.layout.list_item,parent, false);
        Myviewholder holder= New Myviewholder (view);
    return holder;
   Class Myviewholder extends Recyclerview.viewholder {     TextView Tv_time;
        TextView tv_content;
            Public Myviewholder (view view) {super (view);
            Tv_time= (TextView) View.findviewbyid (r.id.time);
        Tv_content= (TextView) View.findviewbyid (r.id.content);
    } public interface onitemclicklistener{void OnClick (int position); public void Setonitemclicklistener (Onitemclicklistener onitemclicklistener) {this. monitemclicklistener=oni
    Temclicklistener;
 }
}

Here used cursor to fit this dbhelper, and later on SQLite will also be in detail, here only need to understand it as a pointer, and then take the value from the table, with cursor.movetoposition (int position); Move to that line; cursor.getstring (int x)); Move to that column, the order of the columns is Atabase.execsql ("CREATE TABLE" + table_name + "(_id INTEGER PRIMARY KEY A Utoincrement,date text,content TEXT); The order in which they are defined inside the quotation marks. Starting from 0.
The next step is our mainactivity.

Package com.example.notes_2;
Import android.content.Intent;
Import Android.database.Cursor;
Import Android.os.Bundle;
Import Android.support.design.widget.FloatingActionButton;
Import Android.support.design.widget.Snackbar;
Import android.support.v7.app.AppCompatActivity;
Import Android.support.v7.widget.DefaultItemAnimator;
Import Android.support.v7.widget.GridLayoutManager;
Import Android.support.v7.widget.LinearLayoutManager;
Import Android.support.v7.widget.OrientationHelper;
Import Android.support.v7.widget.RecyclerView;
Import Android.support.v7.widget.StaggeredGridLayoutManager;
Import Android.support.v7.widget.Toolbar;
Import Android.util.Log;
Import Android.view.View;
Import Android.view.Menu;
Import Android.view.MenuItem;
Import Android.widget.AdapterView;
Import Android.widget.ListView;
Import Android.widget.SimpleCursorAdapter;

Import Android.widget.Toast;
    public class Mainactivity extends Appcompatactivity {private ListView ListView;
    Private Cursor Cursor; PRivate DBHelper DBHelper;
    Private Recyclerview Recyclerview;
    Private Myrecycleradapter adapter;

    private int _id=0;
        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);

        Setcontentview (r.layout.revycle_new);
        Dbhelper=new DBHelper (this);
        Cursor=dbhelper.select ();
        recyclerview= (Recyclerview) Findviewbyid (r.id.recycle);
        Adapter=new Myrecycleradapter (This,cursor,dbhelper);
        Linearlayoutmanager LayoutManager = new Linearlayoutmanager (this);
        Gridlayoutmanager gridlayoutmanager=new Gridlayoutmanager (this,2); Staggeredgridlayoutmanager staggeredgridlayoutmanager= New Staggeredgridlayoutmanager (2,
        staggeredgridlayoutmanager.vertical);
        Set the layout manager Recyclerview.setlayoutmanager (Staggeredgridlayoutmanager);
        Set to vertical layout, which is also the default layoutmanager.setorientation (orientationhelper.vertical); Set Adapter Recyclerview.setadapter (ADApter);
        LOG.E ("0", "GetCount:" +adapter.getitemcount ());
        Sets the animated Recyclerview.setitemanimator (New Defaultitemanimator ()) for adding or removing entries;  Adapter.setonitemclicklistener (New Myrecycleradapter.onitemclicklistener () {@Override public void
                OnClick (int position) {cursor.movetoposition (Cursor.getcount () -1-position);
                _id=cursor.getint (0);
                Intent intent=new Intent (mainactivity.this,modify.class);
                Intent.putextra ("id", _id); Intent.putextra ("Data", cursor.getstring (2)),//getstring (1) shows cursor the contents of the column LOG.E ("0", "mainactivity to Modify_
                CONTETN: "+cursor.getstring (2));
                LOG.E ("0", "ID:" +_id);
                StartActivity (Intent);
            Finish ();




        }
        });
        Toolbar Toolbar = (Toolbar) Findviewbyid (R.id.toolbar);
        Setsupportactionbar (toolbar); Floatingactionbutton fab = (Floatingactionbutton) FindvieWbyid (R.id.fab);
                Fab.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (view view) {
                Intent Intent = new Intent (mainactivity.this,content.class);
            StartActivity (Intent);
    }
        }); @Override public boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the A
        Ction Bar if it is present.
        Getmenuinflater (). Inflate (R.menu.menu_main, menu);
    return true; @Override public boolean onoptionsitemselected (MenuItem Item) {//Handle Action Bar item clicks here. The action bar would//automatically handle clicks on the Home/up button, so long//As you specify a pare
        NT activity in Androidmanifest.xml.

        int id = item.getitemid ();
        Noinspection simplifiableifstatement if (id = = r.id.action_settings) {return true; Return Super.onoptionsitemselected (item);
 }
}

The logic is clear and there is no need to talk about it. There is the activity that clicks on the add note and a bit of the activity of the sticky note to post the code.
Content.java

Package com.example.notes_2;

Import android.app.Activity;
Import Android.content.DialogInterface;
Import android.content.Intent;
Import Android.database.Cursor;
Import Android.os.Bundle;
Import Android.util.Log;
Import android.view.KeyEvent;
Import Android.view.View;
Import Android.widget.Button;
Import Android.widget.EditText;
Im
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.