《第一行代码》学习记录(二)

第四章

  1. fragment的生命周期
//当activity和fragment直接建立联系是调用
onAttach()
//
onCreate()
//fragment创建视图是调用
onCreateView()
//确保与fragment相关联的activity一切创建完毕是调用
onActivityCreated()
//
onStart()
//
onResume()
//
onPause()
//
onStop()
//
onDestroyView()
//
onDestroy()
//解除时调用
onDetach()

这里写图片描述
2. 动态添加fragment

//创建待添加碎片实例
AnotherRightFragment fragment = new AnotherRightFragment();
//获取FragmentManager,在activity中直接通过getFragmentManager得到
FragmentManager fragmentManager = getFragmentManager();
//开启一个事务,通过beginTransaction 方法开启
FragmentTransaction transaction = fragmentManager
                    .beginTransaction();
//向容器中添加一个fragment,一般用replace实现,要传入容器id和实例
//这里的容器是一个frameLayout                   
transaction.replace(R.id.right_layout, fragment);
//将事务添加到返回栈中
transaction.addToBackStack(null);
//提交事务
transaction.commit();

3.在activity中得到fragment的实例

NewsContentFragment newsContentFragment = (NewsContentFragment) getFragmentManager()
            .findFragmentById(R.id.news_content_fragment);

4.在fragment中得到activity的实例

MainActivity activity = (MainActivity)getActivity();

5.在fragment中也可以通过onSaveInstanceState()保存数据,然后在
oncreate(),oncreateView(),和onActivityCreated()中都可以得到

6.动态加载布局可以使用限定符,在res下创建一个layout-large的文件夹,里面放大屏幕的xml文件,小屏幕依旧加载layout中的xml文件

第五章

1.标准广播是异步的,发出后所有接收器都能同一时刻收到,效率高但是不能被拦截,而有序广播是同步的,可以被拦截
2.创建一个广播接收器,只有新建一个类继承broadcastReceiver,然后重写onRecevier()方法,然后在Activity的oncreate方法中注册。

class LocalReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "received local broadcast",
                    Toast.LENGTH_SHORT).show();
        }

    }
//oncreate()
intentFilter = new IntentFilter();      intentFilter.addAction("com.example.broadcasttest.LOCAL_BROADCAST");
localReceiver = new LocalReceiver();
registerReceiver(localReceiver, intentFilter);
//取消注册
@Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(localReceiver);
    }

3.得到手机网络信息

ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        if(info != null && info.isAvailable()){
            //有
        }else {
            //无
        }

4.热注册只能在应用启动后才能接收广播,因为在oncreate方法中注册,只有冷注册才能在未启动是接收广播??
5.发送标准广播(自定义广播)

//定义
public class MyBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "received in MyBroadcastReceive",
                Toast.LENGTH_SHORT).show();
    }

}
//注册
<receiver android:name=".MyBroadcastReceiver">
            <intent-filter>
                <action android:name="com.example.broadcasttest.MY_BROADCAST"/>
            </intent-filter>
        </receiver>
//使用
Intent intent = new Intent("com.example.broadcasttest.MY_BROADCAST");
        sendBroadcast(intent);

6.发送有序广播

sendOrderedBroadcast(intent, null);

//设置优先级priority
<receiver
            android:name=".AnotherBroadcastReceiver"
            android:priority="100" >
            <intent-filter>
                <action android:name="com.example.broadcasttest.MY_BROADCAST" />
            </intent-filter>
        </receiver>
//拦截广播
@Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "received in AnotherBroadcastReceiver",
                Toast.LENGTH_SHORT).show();
        abortBroadcast();//该方法表示拦截广播不向下传递
    }

7.本地广播,只能在应用内部发送广播,解决了广播发送的安全性问题,其中只需要一个LocalBroadcastManager来管理就好

localBroadcastManager = LocalBroadcastManager.getInstance(this);
intentFilter = new IntentFilter();
        intentFilter.addAction("com.example.broadcasttest.LOCAL_BROADCAST");
        localReceiver = new LocalReceiver();
        localBroadcastManager.registerReceiver(localReceiver, intentFilter);
//
@Override
    protected void onDestroy() {
        super.onDestroy();
        localBroadcastManager.unregisterReceiver(localReceiver);
    }

8.强制下线功能,见p205

第六章

1.文件读取:

//写文件
FileOutputStream out = null;
BufferedWriter writer = null;
        try {
            out = openFileOutput("data", Context.MODE_PRIVATE);
            writer = new BufferedWriter(new OutputStreamWriter(out));
            writer.write(inputText);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
//读文件
FileInputStream in = null;
BufferedReader reader = null;
        StringBuilder content = new StringBuilder();
        try {
            in = openFileInput("data");
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            while ((line = reader.readLine()) != null) {
                content.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return content.toString();      

2.设置edittext光标位置

edit.setSelection(inputText.length());

3.SharedPreferences

SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("name", "Tom");
editor.putInt("age", 28);
editor.putBoolean("married", false);
editor.commit();
//
SharedPreferences pref = getSharedPreferences("data", MODE_PRIVATE);
String name = pref.getString("name", "");
int age = pref.getInt("age", 0);
boolean married = pref.getBoolean("married", false);

3.SQLiteDatabase

public class MyDatabaseHelper extends SQLiteOpenHelper {

    public static final String CREATE_BOOK = "create table Book ("
            + "id integer primary key autoincrement, " 
            + "author text, "
            + "price real, " 
            + "pages integer, " 
            + "name text)";

    public static final String CREATE_CATEGORY = "create table Category ("
            + "id integer primary key autoincrement, "
            + "category_name text, "
            + "category_code integer)";

    private Context mContext;

    public MyDatabaseHelper(Context context, String name,
            CursorFactory factory, int version) {
        super(context, name, factory, version);
        mContext = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_BOOK);
        db.execSQL(CREATE_CATEGORY);
        Toast.makeText(mContext, "Create succeeded", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("drop table if exists Book");
        db.execSQL("drop table if exists Category");
        onCreate(db);
    }

}
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 2);
        Button createDatabase = (Button) findViewById(R.id.create_database);
        createDatabase.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                dbHelper.getWritableDatabase();
            }
        });
        Button addData = (Button) findViewById(R.id.add_data);
        addData.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                SQLiteDatabase db = dbHelper.getWritableDatabase();
                ContentValues values = new ContentValues();
                values.put("name", "The Da Vinci Code");
                values.put("author", "Dan Brown");
                values.put("pages", 454);
                values.put("price", 16.96);
                db.insert("Book", null, values);
                values.clear();
                values.put("name", "The Lost Symbol");
                values.put("author", "Dan Brown");
                values.put("pages", 510);
                values.put("price", 19.95);
                db.insert("Book", null, values);
            }
        });
        Button updateData = (Button) findViewById(R.id.update_data);
        updateData.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                SQLiteDatabase db = dbHelper.getWritableDatabase();
                ContentValues values = new ContentValues();
                values.put("price", 10.99);
                db.update("Book", values, "name = ?",
                        new String[] { "The Da Vinci Code" });
            }
        });
        Button deleteButton = (Button) findViewById(R.id.delete_data);
        deleteButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                SQLiteDatabase db = dbHelper.getWritableDatabase();
                db.delete("Book", "pages > ?", new String[] { "500" });
            }
        });
        Button queryButton = (Button) findViewById(R.id.query_data);
        queryButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                SQLiteDatabase db = dbHelper.getWritableDatabase();
                Cursor cursor = db.query("Book", null, null, null, null, null,
                        null);
                if (cursor.moveToFirst()) {
                    do {
                        String name = cursor.getString(cursor
                                .getColumnIndex("name"));
                        String author = cursor.getString(cursor
                                .getColumnIndex("author"));
                        int pages = cursor.getInt(cursor
                                .getColumnIndex("pages"));
                        double price = cursor.getDouble(cursor
                                .getColumnIndex("price"));
                        Log.d("MainActivity", "book name is " + name);
                        Log.d("MainActivity", "book author is " + author);
                        Log.d("MainActivity", "book pages is " + pages);
                        Log.d("MainActivity", "book price is " + price);
                    } while (cursor.moveToNext());
                }
                cursor.close();
            }
        });
        Button replaceData = (Button) findViewById(R.id.replace_data);
        replaceData.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                SQLiteDatabase db = dbHelper.getWritableDatabase();
                db.beginTransaction();//开启事务
                try {
                    db.delete("Book", null, null);
//                  if (true) {
//                      throw new NullPointerException();
//                  }
                    ContentValues values = new ContentValues();
                    values.put("name", "Game of Thrones");
                    values.put("author", "George Martin");
                    values.put("pages", 720);
                    values.put("price", 20.85);
                    db.insert("Book", null, values);
                    db.setTransactionSuccessful();//事务已经执行成功
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    db.endTransaction();//结束事务
                }
            }
        });
    }

4.SQLiteDatabase安全升级数据库见p260

第七章

1.ContentResolver

//想另一个应用的表里插入数据
Uri uri = Uri.parse("content://com.example.databasetest.provider/book");
ContentValues values = new ContentValues();
values.put("name", "A Clash of Kings");
values.put("author", "George Martin");
values.put("pages", 1040);
values.put("price", 55.55);
Uri newUri = getContentResolver().insert(uri, values);
newId = newUri.getPathSegments().get(1);
//从另一个应用的表里查数据
Uri uri = Uri                   .parse("content://com.example.databasetest.provider/book");
Cursor cursor = getContentResolver().query(uri, null, null,
                        null, null);
if (cursor != null) {
    while (cursor.moveToNext()) {
        String name = cursor.getString(cursor
                                .getColumnIndex("name"));
        String author = cursor.getString(cursor
                                .getColumnIndex("author"));
        int pages = cursor.getInt(cursor
                                .getColumnIndex("pages"));
        double price = cursor.getDouble(cursor
                                .getColumnIndex("price"));
                    }
                    cursor.close();
                }
//更新
Uri uri = Uri.parse("content://com.example.databasetest.provider/book/" + newId);
ContentValues values = new ContentValues();
values.put("name", "A Storm of Swords");
values.put("pages", 1216);
values.put("price", 24.05);
getContentResolver().update(uri, values, null, null);   
//删
Uri uri = Uri                   .parse("content://com.example.databasetest.provider/book/" + newId);
getContentResolver().delete(uri, null, null);           

2.读取系统联系人

private void readContacts() {
        Cursor cursor = null;
        try {
            cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null, null, null, null);
            while (cursor.moveToNext()) {
                String displayName = cursor.getString(cursor
                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                String number = cursor.getString(cursor
                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                contactsList.add(displayName + "\n" + number);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

<uses-permission android:name="android.permission.READ_CONTACTS" />
3.创建自己的内容提供者,提供给其他应用访问自己数据的接口
见书276

public class MyDatabaseHelper extends SQLiteOpenHelper {

public static final String CREATE_BOOK = "create table Book ("
        + "id integer primary key autoincrement, " 
        + "author text, "
        + "price real, " 
        + "pages integer, " 
        + "name text)";

public static final String CREATE_CATEGORY = "create table Category ("
        + "id integer primary key autoincrement, "
        + "category_name text, "
        + "category_code integer)";

public MyDatabaseHelper(Context context, String name,
        CursorFactory factory, int version) {
    super(context, name, factory, version);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(CREATE_BOOK);
    db.execSQL(CREATE_CATEGORY);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("drop table if exists Book");
    db.execSQL("drop table if exists Category");
    onCreate(db);
}

}

public class DatabaseProvider extends ContentProvider {

public static final int BOOK_DIR = 0;

public static final int BOOK_ITEM = 1;

public static final int CATEGORY_DIR = 2;

public static final int CATEGORY_ITEM = 3;

public static final String AUTHORITY = "com.example.databasetest.provider";

private static UriMatcher uriMatcher;

private MyDatabaseHelper dbHelper;

static {
    uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    uriMatcher.addURI(AUTHORITY, "book", BOOK_DIR);
    uriMatcher.addURI(AUTHORITY, "book/#", BOOK_ITEM);
    uriMatcher.addURI(AUTHORITY, "category", CATEGORY_DIR);
    uriMatcher.addURI(AUTHORITY, "category/#", CATEGORY_ITEM);
}

@Override
public boolean onCreate() {
    dbHelper = new MyDatabaseHelper(getContext(), "BookStore.db", null, 2);
    return true;
}

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
        String sortOrder) {
    SQLiteDatabase db = dbHelper.getReadableDatabase();
    Cursor cursor = null;
    switch (uriMatcher.match(uri)) {
    case BOOK_DIR:
        cursor = db.query("Book", projection, selection, selectionArgs, null, null, sortOrder);
        break;
    case BOOK_ITEM:
        String bookId = uri.getPathSegments().get(1);
        cursor = db.query("Book", projection, "id = ?", new String[] { bookId }, null, null,
                sortOrder);
        break;
    case CATEGORY_DIR:
        cursor = db.query("Category", projection, selection, selectionArgs, null, null,
                sortOrder);
        break;
    case CATEGORY_ITEM:
        String categoryId = uri.getPathSegments().get(1);
        cursor = db.query("Category", projection, "id = ?", new String[] { categoryId }, null,
                null, sortOrder);
        break;
    default:
        break;
    }
    return cursor;
}

@Override
public Uri insert(Uri uri, ContentValues values) {
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    Uri uriReturn = null;
    switch (uriMatcher.match(uri)) {
    case BOOK_DIR:
    case BOOK_ITEM:
        long newBookId = db.insert("Book", null, values);
        uriReturn = Uri.parse("content://" + AUTHORITY + "/book/" + newBookId);
        break;
    case CATEGORY_DIR:
    case CATEGORY_ITEM:
        long newCategoryId = db.insert("Category", null, values);
        uriReturn = Uri.parse("content://" + AUTHORITY + "/category/" + newCategoryId);
        break;
    default:
        break;
    }
    return uriReturn;
}

@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    int updatedRows = 0;
    switch (uriMatcher.match(uri)) {
    case BOOK_DIR:
        updatedRows = db.update("Book", values, selection, selectionArgs);
        break;
    case BOOK_ITEM:
        String bookId = uri.getPathSegments().get(1);
        updatedRows = db.update("Book", values, "id = ?", new String[] { bookId });
        break;
    case CATEGORY_DIR:
        updatedRows = db.update("Category", values, selection, selectionArgs);
        break;
    case CATEGORY_ITEM:
        String categoryId = uri.getPathSegments().get(1);
        updatedRows = db.update("Category", values, "id = ?", new String[] { categoryId });
        break;
    default:
        break;
    }
    return updatedRows;
}

@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    int deletedRows = 0;
    switch (uriMatcher.match(uri)) {
    case BOOK_DIR:
        deletedRows = db.delete("Book", selection, selectionArgs);
        break;
    case BOOK_ITEM:
        String bookId = uri.getPathSegments().get(1);
        deletedRows = db.delete("Book", "id = ?", new String[] { bookId });
        break;
    case CATEGORY_DIR:
        deletedRows = db.delete("Category", selection, selectionArgs);
        break;
    case CATEGORY_ITEM:
        String categoryId = uri.getPathSegments().get(1);
        deletedRows = db.delete("Category", "id = ?", new String[] { categoryId });
        break;
    default:
        break;
    }
    return deletedRows;
}

@Override
public String getType(Uri uri) {
    switch (uriMatcher.match(uri)) {
    case BOOK_DIR:
        return "vnd.android.cursor.dir/vnd.com.example.databasetest.provider.book";
    case BOOK_ITEM:
        return "vnd.android.cursor.item/vnd.com.example.databasetest.provider.book";
    case CATEGORY_DIR:
        return "vnd.android.cursor.dir/vnd.com.example.databasetest.provider.category";
    case CATEGORY_ITEM:
        return "vnd.android.cursor.item/vnd.com.example.databasetest.provider.category";
    }
    return null;
}
}
<provider
            android:name="com.example.databasetest.DatabaseProvider"
            android:authorities="com.example.databasetest.provider" >
        </provider>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值