《移动终端软件开发技术》第七周作业:ContentProvider和HttpClient

/ 0评 / 1

建立一个ContentProvider,用来共享第六周作业第3题所建立的数据库。

开发一个利用HttpClient下载并显示网络图片的Android应用程序。

第一小题:

MainActivity.java

package bupt.hkt2017211874.lab07_1;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

    private EditText nameText;
    private EditText sexText;
    private EditText departmentText;
    private EditText salaryText;
    private EditText idEntry;

    //private TextView labelView;
    private TextView displayView;

    private ContentResolver resolver;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //姓名
        nameText = (EditText)findViewById(R.id.name);
        //性别
        sexText = (EditText)findViewById(R.id.sex);
        //部门
        departmentText = (EditText)findViewById(R.id.department);
        //工资
        salaryText=(EditText)findViewById(R.id.salary);
        //id
        idEntry = (EditText)findViewById(R.id.id);

        //labelView = (TextView)findViewById(R.id.label);
        displayView = (TextView)findViewById(R.id.display);



        Button addButton = (Button)findViewById(R.id.add);
        Button queryAllButton = (Button)findViewById(R.id.query_all);
        //Button clearButton = (Button)findViewById(R.id.clear);
        //Button deleteAllButton = (Button)findViewById(R.id.delete_all);

        Button queryButton = (Button)findViewById(R.id.query);
        //Button deleteButton = (Button)findViewById(R.id.delete);
        //Button updateButton = (Button)findViewById(R.id.update);


        addButton.setOnClickListener(addButtonListener);
        queryAllButton.setOnClickListener(queryAllButtonListener);
        //clearButton.setOnClickListener(clearButtonListener);
        //deleteAllButton.setOnClickListener(deleteAllButtonListener);

        queryButton.setOnClickListener(queryButtonListener);
        //deleteButton.setOnClickListener(deleteButtonListener);
        //updateButton.setOnClickListener(updateButtonListener);

        resolver = this.getContentResolver();

    }

    //添加
    OnClickListener addButtonListener = new OnClickListener() {
        @Override
        public void onClick(View v) {

            ContentValues values = new ContentValues();

            values.put(People.KEY_NAME, nameText.getText().toString());
            values.put(People.KEY_SEX, sexText.getText().toString());
            values.put(People.KEY_DEPARTMENT, departmentText.getText().toString());
            values.put(People.KEY_SALARY, salaryText.getText().toString());

            Uri newUri = resolver.insert(People.CONTENT_URI, values);

            //labelView.setText("添加成功,URI:" + newUri);

        }
    };

    //输出全部
    OnClickListener queryAllButtonListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            Cursor cursor = resolver.query(People.CONTENT_URI,
                    new String[] { People.KEY_ID, People.KEY_NAME, People.KEY_SEX, People.KEY_DEPARTMENT, People.KEY_SALARY},
                    null, null, null);
            if (cursor == null){
                displayView.setText("数据库中没有数据");
                return;
            }
            //labelView.setText("数据库:" + String.valueOf(cursor.getCount()) + "条记录");

            String msg = "";
            if (cursor.moveToFirst()){
                do{
                    msg += "ID:" + cursor.getInt(cursor.getColumnIndex(People.KEY_ID)) + ",";
                    msg += "姓名:" + cursor.getString(cursor.getColumnIndex(People.KEY_NAME))+ ",";
                    msg += "性别:" + cursor.getString(cursor.getColumnIndex(People.KEY_SEX)) + ", ";
                    msg += "部门:" + cursor.getString(cursor.getColumnIndex(People.KEY_DEPARTMENT)) + ", ";
                    msg += "工资:" + cursor.getString(cursor.getColumnIndex(People.KEY_SALARY)) + "\n";
                }while(cursor.moveToNext());
            }

            displayView.setText(msg);
        }
    };


    /**
    OnClickListener clearButtonListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            displayView.setText("");
        }
    };


    OnClickListener deleteAllButtonListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            resolver.delete(People.CONTENT_URI, null, null);
            String msg = "数据全部删除" ;
            labelView.setText(msg);
        }
    };
     **/

    OnClickListener queryButtonListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            Uri uri = Uri.parse(People.CONTENT_URI_STRING + "/" + idEntry.getText().toString());
            Cursor cursor = resolver.query(uri,
                    new String[] { People.KEY_ID, People.KEY_NAME, People.KEY_SEX, People.KEY_DEPARTMENT, People.KEY_SALARY},
                    null, null, null);
            if (cursor == null){
                displayView.setText("数据库中没有数据");
                return;
            }

            String msg = "";
            if (cursor.moveToFirst()){
                msg += "ID:" + cursor.getInt(cursor.getColumnIndex(People.KEY_ID)) + ",";
                msg += "姓名:" + cursor.getString(cursor.getColumnIndex(People.KEY_NAME))+ ",";
                msg += "性别:" + cursor.getString(cursor.getColumnIndex(People.KEY_SEX)) + ", ";
                msg += "部门:" + cursor.getString(cursor.getColumnIndex(People.KEY_DEPARTMENT)) + ", ";
                msg += "工资:" + cursor.getString(cursor.getColumnIndex(People.KEY_SALARY)) + "\n";
            }

            //labelView.setText("数据库:");
            displayView.setText(msg);
        }
    };

    /**
    OnClickListener deleteButtonListener = new OnClickListener() {
        @Override
        public void onClick(View v) {

            Uri uri = Uri.parse(People.CONTENT_URI_STRING + "/" + idEntry.getText().toString());
            int result = resolver.delete(uri, null, null);
            String msg = "删除ID为"+idEntry.getText().toString()+"的数据" + (result>0?"成功":"失败");
            labelView.setText(msg);
        }
    };

    OnClickListener updateButtonListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            ContentValues values = new ContentValues();

            values.put(People.KEY_NAME, nameText.getText().toString());
            values.put(People.KEY_AGE, Integer.parseInt(ageText.getText().toString()));
            values.put(People.KEY_HEIGHT, Float.parseFloat(heightText.getText().toString()));

            Uri uri = Uri.parse(People.CONTENT_URI_STRING + "/" + idEntry.getText().toString());
            int result = resolver.update(uri, values, null, null);

            String msg = "更新ID为"+idEntry.getText().toString()+"的数据" + (result>0?"成功":"失败");
            labelView.setText(msg);
        }
    };
     **/
}

People.java

package bupt.hkt2017211874.lab07_1;

import android.net.Uri;

public class People{

    public static final String MIME_DIR_PREFIX = "vnd.android.cursor.dir";
    public static final String MIME_ITEM_PREFIX = "vnd.android.cursor.item";
    public static final String MINE_ITEM = "vnd.hrbeu.people";

    public static final String MINE_TYPE_SINGLE = MIME_ITEM_PREFIX + "/" + MINE_ITEM;
    public static final String MINE_TYPE_MULTIPLE = MIME_DIR_PREFIX + "/" + MINE_ITEM;

    public static final String AUTHORITY = "bupt.hkt2017211874.lab07_1";
    public static final String PATH_SINGLE = "people/#";
    public static final String PATH_MULTIPLE = "people";
    public static final String CONTENT_URI_STRING = "content://" + AUTHORITY + "/" + PATH_MULTIPLE;
    public static final Uri  CONTENT_URI = Uri.parse(CONTENT_URI_STRING);

    public static final String KEY_ID = "_id";
    public static final String KEY_NAME="name";
    public static final String KEY_SEX = "sex";
    public static final String KEY_DEPARTMENT = "department";
    public static final String KEY_SALARY = "salary";
}

PeopleProvider.java

package bupt.hkt2017211874.lab07_1;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.net.Uri;

public class PeopleProvider extends ContentProvider{

    private static final String DB_NAME = "people.db";
    private static final String DB_TABLE = "peopleinfo";
    private static final int DB_VERSION = 1;

    private SQLiteDatabase db;
    private DBOpenHelper dbOpenHelper;

    private static final int MULTIPLE_PEOPLE = 1;
    private static final int SINGLE_PEOPLE = 2;
    private static final UriMatcher uriMatcher;

    static {
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        uriMatcher.addURI(People.AUTHORITY, People.PATH_MULTIPLE, MULTIPLE_PEOPLE);
        uriMatcher.addURI(People.AUTHORITY, People.PATH_SINGLE, SINGLE_PEOPLE);
    }

    @Override
    public String getType(Uri uri) {
        switch(uriMatcher.match(uri)){
            case MULTIPLE_PEOPLE:
                return People.MINE_TYPE_MULTIPLE;
            case SINGLE_PEOPLE:
                return People.MINE_TYPE_SINGLE;
            default:
                throw new IllegalArgumentException("Unkown uri:"+uri);
        }
    }


    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        int count = 0;
        switch(uriMatcher.match(uri)){
            case MULTIPLE_PEOPLE:
                count = db.delete(DB_TABLE, selection, selectionArgs);
                break;
            case SINGLE_PEOPLE:
                String segment = uri.getPathSegments().get(1);
                count = db.delete(DB_TABLE, People.KEY_ID + "=" + segment, selectionArgs);
                break;
            default:
                throw new IllegalArgumentException("Unsupported URI:" + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }


    @Override
    public Uri insert(Uri uri, ContentValues values) {
        long id = db.insert(DB_TABLE, null, values);
        if ( id > 0 ){
            Uri newUri = ContentUris.withAppendedId(People.CONTENT_URI, id);
            getContext().getContentResolver().notifyChange(newUri, null);
            return newUri;
        }
        throw new SQLException("Failed to insert row into " + uri);
    }

    @Override
    public boolean onCreate() {
        Context context = getContext();
        dbOpenHelper = new DBOpenHelper(context, DB_NAME, null, DB_VERSION);
        db = dbOpenHelper.getWritableDatabase();

        if (db == null)
            return false;
        else
            return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        qb.setTables(DB_TABLE);
        switch(uriMatcher.match(uri)){
            case SINGLE_PEOPLE:
                qb.appendWhere(People.KEY_ID + "=" + uri.getPathSegments().get(1));
                break;
            default:
                break;
        }
        Cursor cursor = qb.query(db,
                projection,
                selection,
                selectionArgs,
                null,
                null,
                sortOrder);
        cursor.setNotificationUri(getContext().getContentResolver(), uri);
        return cursor;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {
        int count;
        switch(uriMatcher.match(uri)){
            case MULTIPLE_PEOPLE:
                count = db.update(DB_TABLE, values, selection, selectionArgs);
                break;
            case SINGLE_PEOPLE:
                String segment = uri.getPathSegments().get(1);
                count = db.update(DB_TABLE, values, People.KEY_ID+"="+segment, selectionArgs);
                break;
            default:
                throw new IllegalArgumentException("Unknow URI:" + uri);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }


    private static class DBOpenHelper extends SQLiteOpenHelper {

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

        private static final String DB_CREATE = "create table " +
                DB_TABLE + " (" + People.KEY_ID + " integer primary key autoincrement, " +
                People.KEY_NAME+ " text not null, " + People.KEY_SEX+ " text," + People.KEY_DEPARTMENT+ " text," + People.KEY_SALARY + " test);";

        @Override
        public void onCreate(SQLiteDatabase _db) {
            _db.execSQL(DB_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion) {
            _db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
            onCreate(_db);
        }
    }


}

忘记注册,所以报错找不到content

java.lang.IllegalArgumentException: Unknown URL content://bupt.hkt2017211874.lab07_1.peopleprovider/people
        at android.content.ContentResolver.insert(ContentResolver.java:1850)
        at bupt.hkt2017211874.lab07_1.MainActivity$1.onClick(MainActivity.java:84)

注册信息

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="bupt.hkt2017211874.lab07_1">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <provider
            android:authorities="bupt.hkt2017211874.lab07_1"
            android:name=".PeopleProvider"/>
    </application>

</manifest>

第二小题:

比较简单,参考示例代码改改就能用了

MainActivity.java

package bupt.hkt2017211874.lab07_2;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

public class MainActivity extends Activity {

    public static EditText editText;
    public static ImageView imageView;
    public static Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText=(EditText)findViewById(R.id.editText);
        imageView=(ImageView)findViewById(R.id.imageView);
        button=(Button)findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                String imgUrl = editText.getText().toString();
                new Download().execute(imgUrl);
            }
        });
    }


}

Download.java

package bupt.hkt2017211874.lab07_2;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class Download extends AsyncTask<String, Void, Bitmap> {
    @Override
    protected Bitmap doInBackground(String... strings) {
        Bitmap b = getImageBitmap(strings[0]);
        return b;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        MainActivity.imageView.setImageBitmap(null);
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        super.onPostExecute(result);
        if(result!=null){
            MainActivity.imageView.setImageBitmap(result);
        }
    }

    private Bitmap getImageBitmap(String url){
        URL imgUrl = null;
        Bitmap bitmap = null;
        try {
            //1、创建一个URL对象
            imgUrl = new URL(url);
            //2、获取HttpURLConnection对象实例
            HttpURLConnection conn = (HttpURLConnection)imgUrl.openConnection();
            conn.setDoInput(true);
            conn.connect();
            //3、获得服务器返回的输入流
            InputStream is = conn.getInputStream();
            //4、解码数据流
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
            //5、断开连接
            conn.disconnect();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }catch(IOException e){
            e.printStackTrace();
        }
        return bitmap;
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="bupt.hkt2017211874.lab07_2">

    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

发表评论

电子邮件地址不会被公开。 必填项已用*标注