Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 安卓小案例收集二

安卓小案例收集二

日期:2017/2/23 15:22:07      編輯:關於Android編程

SQLite數據庫

OpenHelper類:

public class MyOpenHelper extends SQLiteOpenHelper {

    public MyOpenHelper(Context context) {
        //本來是四個參數,改成1個,其他寫死了
        //arg1:數據庫文件名字
        //arg2:游標工廠,游標等同於結果集,傳null使用默認工廠
        //arg3:版本,不能小於1,用於升級
        super(context, "people.db", null, 1);
    }

    //創建數據庫時調用
    @Override
    public void onCreate(SQLiteDatabase db) {
        //創建表
        db.execSQL("create table person(_id integer primary key autoincrement, name char(10), phone char(20), salary integer(10))");
    }

    //升級數據庫時調用
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        System.out.println("數據庫升級");
    }

}

Test類中的調用

public class Test extends AndroidTestCase{

    private MyOpenHelper oh;
    private SQLiteDatabase db;

    public void test(){
        //獲取虛擬上下文
        MyOpenHelper oh = new MyOpenHelper(getContext());
        //如果數據庫不存在,先創建,再打開,如果存在,就直接打開
        SQLiteDatabase db = oh.getWritableDatabase();
    }

    //測試方法執行前調用
    @Override
    protected void setUp() throws Exception {
        super.setUp();
        oh = new MyOpenHelper(getContext());
        db = oh.getWritableDatabase();
    }

    @Override
    protected void tearDown() throws Exception {
        super.tearDown();
        db.close();
    }

    public void insert(){
//      db.execSQL("insert into person(name, phone, salary) values (?, ?, ?)", new Object[]{"一", "138438", 13000});
        db.execSQL("insert into person(name, phone, salary) values (?, ?, ?)", new Object[]{"二 ", "138438", 13000});
        db.execSQL("insert into person(name, phone, salary) values (?, ?, ?)", new Object[]{"三", "138438", 13000});
    }

    public void delete(){
        db.execSQL("delete from person where name = ?", new Object[]{"一"});
    }

    public void update(){
        db.execSQL("update person set salary = ? where name = ?", new Object[]{13200, "一"});
    }

    public void select(){
        Cursor cursor = db.rawQuery("select * from person", null);
        //把指針移動至下一行
        while(cursor.moveToNext()){
            //先通過列名,獲取列索引,然後再獲取該列的內容
            String name = cursor.getString(cursor.getColumnIndex("name"));
            String phone = cursor.getString(cursor.getColumnIndex("phone"));
            int salary = cursor.getInt(cursor.getColumnIndex("salary"));
            System.out.println(name + ";" + phone + ";" + salary);
        }
    }

    public void insertApi(){
        ContentValues values = new ContentValues();
        values.put("name", "楊松");
        values.put("phone", "1388888");
        values.put("salary", "13201");
        //返回值-1,插入失敗
        long l = db.insert("person", null, values);
        System.out.println(l);
    }

    public void deleteApi(){
        int i = db.delete("person", "_id = ?", new String[]{"6"});
        System.out.println(i);
    }

    public void updateApi(){
        ContentValues values = new ContentValues();
        values.put("name", "二二");
        int i = db.update("person", values, "_id = ?", new String[]{"5"});
        System.out.println(i);
    }

    public void selectApi(){
        //arg1: 查詢的字段
        //arg2: 查詢的where條件
        //arg3: where條件的占位符
        Cursor cursor = db.query("person", null, null, null, null, null, null, null);
        while(cursor.moveToNext()){
            String name = cursor.getString(1);
            String phone = cursor.getString(2);
            int salary = cursor.getInt(3);
            System.out.println(name + ";" + phone + ";" + salary);
        }
    }

    public void transaction(){
        try{
            //開啟事務
            db.beginTransaction();
            ContentValues values = new ContentValues();
            values.put("salary", 13199);
            db.update("person", values, "name = ?", new String[]{"二二"});

            //清空values的內容
            values.clear();
            values.put("salary", 13202);
            db.update("person", values, "name = ?", new String[]{"一"});

//          int i = 9 / 0;
            //設置事務執行成功,提交時如果這行代碼沒有執行過,就會回滾
            db.setTransactionSuccessful();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally{
            //關閉事務,提交數據
            db.endTransaction();
        }
    }
}

ListView使用

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

        personList = new ArrayList();
        //查詢數據庫
        MyOpenHelper oh = new MyOpenHelper(this);
        SQLiteDatabase db = oh.getWritableDatabase();
        Cursor cursor = db.query("person", null, null, null, null, null, null, null);

        while(cursor.moveToNext()){
            String name = cursor.getString(1);
            String phone = cursor.getString(2);
            int salary = cursor.getInt(3);

            Person p = new Person(name, phone, salary);
            personList.add(p);
        }

        //找到listview
        ListView lv = (ListView) findViewById(R.id.lv);
        //設置顯示內容
        lv.setAdapter(new MyAdapter());

    }

    class MyAdapter extends BaseAdapter{

        //系統調用,用來獲知模型層有多少條數據
        @Override
        public int getCount() {
            return personList.size();
        }

        //系統調用,返回的View對象就會作為ListView的一個條目顯示在屏幕上
        //position:該次getView調用返回的View對象在ListView中是第幾個條目,position的值就是幾
        //convertView:系統之前緩存的條目
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            System.out.println("getView方法調用" + position + ":" + convertView);
            Person p = personList.get(position);            
//          TextView tv = new TextView(MainActivity.this);
//          tv.setText(p.toString());
//          tv.setTextSize(16);     
            //獲取布局填充器
//          LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
//          LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);

//          View view = inflater.inflate(R.layout.item_listview, null);         
            View view = null;
            if(convertView == null){
                //把布局文件填充成view對象
                view = View.inflate(MainActivity.this, R.layout.item_listview, null);

            }
            else{
                view = convertView;
            }

            //必須使用view.findViewById
            TextView tv_name = (TextView) view.findViewById(R.id.tv_name);
            tv_name.setText(p.getName());

            TextView tv_phone = (TextView) view.findViewById(R.id.tv_phone);
            tv_phone.setText(p.getPhone());

            TextView tv_salary = (TextView) view.findViewById(R.id.tv_salary);
            tv_salary.setText(p.getSalary() + "");//不能用整形會被做為id使用
            return view;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

    }

ArrayAdapter和SimpleAdapter的使用

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

        String[] objects = new String[]{
                "一",
                "二",
                "三"
        };      
        ListView lv = (ListView) findViewById(R.id.lv);
//      lv.setAdapter(new ArrayAdapter(this, R.layout.item_listview, //指定作為條目的布局文件
//              R.id.tv, //指定文本顯示在哪個文本框
//              objects));

        //把每個條目需要處理的所有數據封裝至map中,在把map封裝至list中
        //這樣就保證了list每個元素都包含了一個條目需要的所有數據
        List> data = new ArrayList>();

        Map map1 = new HashMap();
        map1.put("name", "周傑倫");
        map1.put("photo", R.drawable.photo1);
        data.add(map1);

        Map map2 = new HashMap();
        map2.put("name", "劉德華");
        map2.put("photo", R.drawable.photo2);
        data.add(map2);

        Map map3 = new HashMap();
        map3.put("name", "侃哥");
        map3.put("photo", R.drawable.photo3);
        data.add(map3);

        lv.setAdapter(new SimpleAdapter(this, data, R.layout.item_listview, 
                new String[]{"name", "photo"}, //存放鍵的數組
                new int[]{R.id.tv, R.id.iv}));//存放資源id的數組,兩個數組用下標來對應
    }

網絡請求下載圖片

public void click(View v){
    String path = "http://169.254.244.136:8080/dd.jpg";
    //發送http請求
    try {
        //1.使用網址構造一個URL對象
        URL url = new URL(path);
        //2.獲取連接對象
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //3.設置一些屬性
        //設置請求方式,注意大寫
        conn.setRequestMethod("GET");
        //設置請求超時
        conn.setConnectTimeout(8000);
        //設置讀取超時
        conn.setReadTimeout(8000);
        //4.發送請求,建立連接
        conn.connect();
        //5.判斷請求是否成功
        if(conn.getResponseCode() == 200){
            //獲取服務器返回的流,流裡就是客戶端請求的數據
            InputStream is = conn.getInputStream();
            //讀取流裡的數據,構造出一張圖片
            Bitmap bm = BitmapFactory.decodeStream(is);
            //把下載的圖片顯示至imageview
            ImageView iv = (ImageView) findViewById(R.id.iv);
            iv.setImageBitmap(bm);
        }
        else{
            Toast.makeText(this, "請求失敗鳥o(╯□╰)o", 0).show();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

子線程刷新頁面,Handler的使用(網絡請求必須在子線程)

Handler handler = new Handler(){
    //只要消息隊列有消息,此方法就會在主線程執行
    public void handleMessage(android.os.Message msg) {
        //在這裡刷新ui
        switch (msg.what) {
        case 1:
            ImageView iv = (ImageView) findViewById(R.id.iv);
            iv.setImageBitmap((Bitmap)msg.obj);
            break;
        case 2:
            Toast.makeText(MainActivity.this, "請求失敗o(╯□╰)o", 0).show();
            break;
        }

    }
};

public void click(View v){
    Thread t = new Thread(){
        @Override
        public void run() {
            String path = "http://169.254.244.136:8080/dd.jpg";
            //發送http請求
            try {
                //1.使用網址構造一個URL對象
                URL url = new URL(path);
                //2.獲取連接對象
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                //3.設置一些屬性
                //設置請求方式,注意大寫
                conn.setRequestMethod("GET");
                //設置請求超時
                conn.setConnectTimeout(8000);
                //設置讀取超時
                conn.setReadTimeout(8000);
                //4.發送請求,建立連接
                conn.connect();
                //5.判斷請求是否成功
                if(conn.getResponseCode() == 200){
                    //獲取服務器返回的流,流裡就是客戶端請求的數據
                    InputStream is = conn.getInputStream();             
                    //讀取流裡的數據,構造出一張圖片
                    Bitmap bm = BitmapFactory.decodeStream(is);             
                    //當子線程需要刷新ui時,只需發送一條消息至消息隊列
                    Message msg = new Message();
                    //消息對象本身是可以攜帶數據的
                    msg.obj = bm;
                    //使用what標注消息是什麼類型的
                    msg.what = 1;

                    handler.sendMessage(msg);

                }
                else{
                    //如果消息池有消息,取出消息池第一條消息,返回,如果沒有,就new一個消息返回
//                      Message msg = handler.obtainMessage();
//                      msg.what = 2;
//                      handler.sendMessage(msg);

                    handler.sendEmptyMessage(2);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    t.start();

}

帶緩存的圖片下載

Handler handler = new Handler(){
    //只要消息隊列有消息,此方法就會在主線程執行
    public void handleMessage(android.os.Message msg) {
        //在這裡刷新ui
        switch (msg.what) {
        case 1:
            ImageView iv = (ImageView) findViewById(R.id.iv);
            iv.setImageBitmap((Bitmap)msg.obj);
            break;
        case 2:
            Toast.makeText(MainActivity.this, "請求失敗o(╯□╰)o", 0).show();
            break;
        }

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

public void click(View v){
    final String path = "http://169.254.244.136:8080/dd.jpg";
    final File file = new File(getCacheDir(), getNameFromPath(path));
    if(file.exists()){
        System.out.println("從緩存獲取");
        Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());

        Message msg = new Message();
        msg.obj = bm;
        msg.what = 1;
        handler.sendMessage(msg);
//          ImageView iv = (ImageView) findViewById(R.id.iv);
//          iv.setImageBitmap((Bitmap)msg.obj);
    }
    else{
        Thread t = new Thread(){
            @Override
            public void run() {
                System.out.println("從網絡獲取");
                //發送http請求
                try {
                    //1.使用網址構造一個URL對象
                    URL url = new URL(path);
                    //2.獲取連接對象
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    //3.設置一些屬性
                    //設置請求方式,注意大寫
                    conn.setRequestMethod("GET");
                    //設置請求超時
                    conn.setConnectTimeout(8000);
                    //設置讀取超時
                    conn.setReadTimeout(8000);
                    //4.發送請求,建立連接
//                      conn.connect();
                    //5.判斷請求是否成功
                    if(conn.getResponseCode() == 200){
                        //獲取服務器返回的流,流裡就是客戶端請求的數據
                        InputStream is = conn.getInputStream();

                        //我們自己讀取流裡的數據,讀取1k,就把1k寫到本地文件緩存起來
                        byte[] b = new byte[1024];
                        int len;

                        FileOutputStream fos = new FileOutputStream(file);
                        while((len = is.read(b)) != -1){
                            fos.write(b, 0, len);
                        }
                        fos.close();

//                      因為緩存時已經把流裡數據讀取完了,此時流裡沒有任何數據
//                      Bitmap bm = BitmapFactory.decodeStream(is);

                        Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());

                        //當子線程需要刷新ui時,只需發送一條消息至消息隊列
                        Message msg = new Message();
                        //消息對象本身是可以攜帶數據的
                        msg.obj = bm;
                        //使用what標注消息是什麼類型的
                        msg.what = 1;

                        handler.sendMessage(msg);

                    }
                    else{
                        //如果消息池有消息,取出消息池第一條消息,返回,如果沒有,就new一個消息返回
//                      Message msg = handler.obtainMessage();
//                      msg.what = 2;
//                      handler.sendMessage(msg);

                        handler.sendEmptyMessage(2);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        t.start();
    }

}

public String getNameFromPath(String path){
    int index = path.lastIndexOf("/");
    return path.substring(index + 1);
}

使用SmartImageView 工具包(loopj)

public void click(View v){
    SmartImageView siv = (SmartImageView) findViewById(R.id.siv);
    //請求網絡圖片
    siv.setImageUrl("http://169.254.244.136:8080/dd.jpg");
}

請求html頁面並顯示其代碼

讀流的工具類

public class Tools {

    public static String getTextFromStream(InputStream is){
        byte[] b = new byte[1024];
        int len;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            while((len = is.read(b)) != -1){
                bos.write(b, 0, len);
            }
            //把字節數組輸出流轉換成字節數組,然後用字節數組構造一個字符串
            String text = new String(bos.toByteArray());
            return text;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }
}
Handler handler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            TextView tv = (TextView) findViewById(R.id.tv);
            tv.setText((String)msg.obj);
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void click(View v){
        final String path = "http://169.254.244.136:8080/baidu.html";
        Thread t = new Thread(){
            @Override
            public void run() {
                //使用網址構造url
                URL url;
                try {
                    url = new URL(path);
                    //獲取連接對象,做設置
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(8000);
                    conn.setReadTimeout(8000);
                    //發送請求,獲取響應碼
                    if(conn.getResponseCode() == 200){
                        //獲取服務器返回的輸入流
                        InputStream is = conn.getInputStream();
                        String text = Tools.getTextFromStream(is);

                        //發送消息至消息隊列,主線程會執行handleMessage
                        Message msg = handler.obtainMessage();
                        msg.obj = text;
                        handler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };
        t.start();
    }

模擬一個新聞客戶端

News是新聞對象,實際以xml的方式存在服務器

List newsList;

    Handler handler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            ListView lv = (ListView) findViewById(R.id.lv);
            lv.setAdapter(new MyAdapter());
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getNewsInfo();

//      ListView lv = (ListView) findViewById(R.id.lv);
        //此時新聞信息還沒有解析完畢,newsList還沒有new出來
//      lv.setAdapter(new MyAdapter());
    }

    class MyAdapter extends BaseAdapter{
        //返回的要顯示的條目的數量
        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return newsList.size();
        }

        //返回一個View對象,會作為ListView的一個條目顯示在界面上
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            News news = newsList.get(position);

            View v = null;
            ViewHolder mHolder = null;
            if(convertView == null){
                //如何填充的
                v = View.inflate(MainActivity.this, R.layout.item_listview, null);

                //創建viewHoler封裝所有條目使用的組件
                mHolder = new ViewHolder();
                mHolder.tv_title = (TextView) v.findViewById(R.id.tv_title);
                mHolder.tv_detail = (TextView) v.findViewById(R.id.tv_detail);
                mHolder.tv_comment = (TextView) v.findViewById(R.id.tv_comment);
                mHolder.siv = (SmartImageView) v.findViewById(R.id.siv);

                //把viewHolder封裝至view對象中,這樣view被緩存時,viewHolder也就被緩存了
                v.setTag(mHolder);
            }
            else{
                v = convertView;
                //從view中取出保存的viewHolder,viewHolder中就有所有的組件對象,不需要再去findViewById
                mHolder = (ViewHolder) v.getTag();
            }
            //給條目中的每個組件設置要顯示的內容
            mHolder.tv_title.setText(news.getTitle());
            mHolder.tv_detail.setText(news.getDetail());
            mHolder.tv_comment.setText(news.getComment() + "條評論");

            mHolder.siv.setImageUrl(news.getImageUrl());
            return v;
        }

        //把條目需要使用到的所有組件封裝在這個類中
        class ViewHolder{
            TextView tv_title;
            TextView tv_detail;
            TextView tv_comment;
            SmartImageView siv;
        }

        @Override
        public Object getItem(int position) {
            return newsList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

    }

    private void getNewsInfo() {
        Thread t = new Thread(){
            @Override
            public void run() {
                String path = "http://169.254.244.136:8080/news.xml";
                try {
                    URL url = new URL(path);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(8000);
                    conn.setReadTimeout(8000);

                    if(conn.getResponseCode() == 200){
                        //流裡的信息是一個xml文件的文本信息,用xml解析器去解析,而不要作為文本去解析
                        InputStream is = conn.getInputStream();
                        getNewsFromStream(is);

                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };
        t.start();
    }
    private void getNewsFromStream(InputStream is) {
        //從XML對象中獲取XML文件解析器對象。
        XmlPullParser xp = Xml.newPullParser();
        try {
            xp.setInput(is, "utf-8");

            //獲取事件類型,通過事件類型判斷出當前解析的是和什麼節點
            int type = xp.getEventType();

            News news = null;
            while(type != XmlPullParser.END_DOCUMENT){
                switch (type) {
                case XmlPullParser.START_TAG:
                    if("newslist".equals(xp.getName())){
                        newsList = new ArrayList();
                    }
                    else if("news".equals(xp.getName())){
                        news = new News();
                    }
                    else if("title".equals(xp.getName())){
                        String title = xp.nextText();
                        news.setTitle(title);
                    }
                    else if("detail".equals(xp.getName())){
                        String detail = xp.nextText();
                        news.setDetail(detail);
                    }
                    else if("comment".equals(xp.getName())){
                        String comment = xp.nextText();
                        news.setComment(comment);
                    }
                    else if("image".equals(xp.getName())){
                        String image = xp.nextText();
                        news.setImageUrl(image);
                    }

                    break;
                case XmlPullParser.END_TAG:
                    if("news".equals(xp.getName())){
                        newsList.add(news);
                    }
                    break;
                }
                //指針移動到下一個節點並返回事件類型
                type = xp.next();
            }       
            //發送消息,讓主線程刷新listview
            handler.sendEmptyMessage(1);
//          for (News n : newsList) {
//              System.out.println(n.toString());
//          }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

get方式提交表單

Handler handler = new Handler(){
    public void handleMessage(android.os.Message msg) {
        Toast.makeText(MainActivity.this, (String)msg.obj, 0).show();
    }
};
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void click(View v){

    EditText et_name = (EditText) findViewById(R.id.et_name);
    EditText et_pass = (EditText) findViewById(R.id.et_pass);

    final String name = et_name.getText().toString();
    final String pass = et_pass.getText().toString();

    Thread t = new Thread(){
        @Override
        public void run() {
            @SuppressWarnings("deprecation")
            String path = "http://169.254.244.136/Web2/servlet/Login?name=" + URLEncoder.encode(name) + //對要提交的表單數據進行url編碼
                                                                                    "&pass=" + pass;
            try {
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();

                conn.setRequestMethod("GET");
                conn.setConnectTimeout(8000);
                conn.setReadTimeout(8000);

                if(conn.getResponseCode() == 200){
                    InputStream is = conn.getInputStream();
                    String text = Tools.getTextFromStream(is);
                    Message msg = handler.obtainMessage();
                    msg.obj = text;
                    handler.sendMessage(msg);
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    };
    t.start();
}

post方式提交

Handler handler = new Handler(){
    public void handleMessage(android.os.Message msg) {
        Toast.makeText(MainActivity.this, (String)msg.obj, 0).show();
    }
};
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void click(View v){

    EditText et_name = (EditText) findViewById(R.id.et_name);
    EditText et_pass = (EditText) findViewById(R.id.et_pass);

    final String name = et_name.getText().toString();
    final String pass = et_pass.getText().toString();

    Thread t = new Thread(){
        @Override
        public void run() {
            String path = "http://169.254.244.136/Web2/servlet/Login";
            try {
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();

                conn.setRequestMethod("POST");
                conn.setConnectTimeout(8000);
                conn.setReadTimeout(8000);

                //添加post請求頭中自動添加的屬性
                //流裡的數據的mimetype
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                String content = "name=" + URLEncoder.encode(name) + "&pass=" + pass;
                //流裡數據的長度
                conn.setRequestProperty("Content-Length", content.length() + "");

                //打開連接對象的輸出流
                conn.setDoOutput(true);
                //獲取連接對象的輸出流
                OutputStream os = conn.getOutputStream();
                //把數據寫入輸出流中
                os.write(content.getBytes());   
                if(conn.getResponseCode() == 200){
                    InputStream is = conn.getInputStream();
                    String text = Tools.getTextFromStream(is);
                    Message msg = handler.obtainMessage();
                    msg.obj = text;
                    handler.sendMessage(msg);
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    };
    t.start();
}

使用HttpClient提交表單

Handler handler = new Handler(){
    public void handleMessage(android.os.Message msg) {
        Toast.makeText(MainActivity.this, (String)msg.obj, 0).show();
    }
};
   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
   }


   public void click1(View v){
    //獲取用戶輸入的賬號密碼
    EditText et_name = (EditText) findViewById(R.id.et_name);
    EditText et_pass = (EditText) findViewById(R.id.et_pass);

    String name = et_name.getText().toString();
    String pass = et_pass.getText().toString();

    final String path = "http://169.254.244.136/Web2/servlet/Login?name=" + URLEncoder.encode(name) + "&pass=" + pass;

    Thread t = new Thread(){
        @Override
        public void run() {
            //使用httpClient框架提交
            //1.創建client對象
            HttpClient client = new DefaultHttpClient();
            //2.創建get請求對象
            HttpGet get = new HttpGet(path);
            try {
                //3.使用client發送get請求
                HttpResponse response = client.execute(get);
                //獲取狀態行
                StatusLine line = response.getStatusLine();
                //獲取狀態碼
                int code = line.getStatusCode();
                if(code == 200){
                    //獲取實體
                    HttpEntity entity = response.getEntity();
                    InputStream is = entity.getContent();
                    String text = Tools.getTextFromStream(is);

                    Message msg = handler.obtainMessage();
                    msg.obj = text;
                    handler.sendMessage(msg);
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };
    t.start();
   }

   public void click2(View v){
    //獲取用戶輸入的賬號密碼
    EditText et_name = (EditText) findViewById(R.id.et_name);
    EditText et_pass = (EditText) findViewById(R.id.et_pass);

    final String name = et_name.getText().toString();
    final String pass = et_pass.getText().toString();

    final String path = "http://169.254.244.136/Web2/servlet/Login";

    Thread t = new Thread(){
        @Override
        public void run() {
            HttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(path);

            //把要提交的數據封裝至post中
            List parameters = new ArrayList();
            //arg0:表單的名字
            //arg1:表單中的值
            BasicNameValuePair bnvp1 = new BasicNameValuePair("name", name);
            BasicNameValuePair bnvp2 = new BasicNameValuePair("pass", pass);
            //把BasicNameValuePair對象放入集合
            parameters.add(bnvp1);
            parameters.add(bnvp2);
            //創建實體對象
            UrlEncodedFormEntity entity = null;
            try {
                //把集合對象封裝到實體中
                entity = new UrlEncodedFormEntity(parameters, "utf-8");
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            //把實體對象封裝至post對象中
            post.setEntity(entity);
            try {
                HttpResponse response = client.execute(post);

                if(response.getStatusLine().getStatusCode() == 200){
                    InputStream is = response.getEntity().getContent();
                    String text = Tools.getTextFromStream(is);

                    Message msg = handler.obtainMessage();
                    msg.obj = text;
                    handler.sendMessage(msg);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } 
        }
    };
    t.start();
   }

異步HttpClient

Handler handler = new Handler(){
    public void handleMessage(android.os.Message msg) {
        Toast.makeText(MainActivity.this, (String)msg.obj, 0).show();
    }
};
   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
   }


   public void click1(View v){
    //獲取用戶輸入的賬號密碼
    EditText et_name = (EditText) findViewById(R.id.et_name);
    EditText et_pass = (EditText) findViewById(R.id.et_pass);

    String name = et_name.getText().toString();
    String pass = et_pass.getText().toString();

    String path = "http://169.254.244.136/Web2/servlet/Login";
    //使用異步HttpClient發送get請求
    AsyncHttpClient client = new AsyncHttpClient();

    //把要提交的數據封裝在rp對象中
    RequestParams rp = new RequestParams();
    rp.put("name", name);
    rp.put("pass", pass);
    //發送get請求
    client.get(path, rp, new MyHandler());
   }

   class MyHandler extends AsyncHttpResponseHandler{

    //請求成功時回調
    @Override
    public void onSuccess(int statusCode, Header[] headers,
            byte[] responseBody) {
        Toast.makeText(MainActivity.this, new String(responseBody), 0).show();
    }

    //請求失敗時回調
    @Override
    public void onFailure(int statusCode, Header[] headers,
            byte[] responseBody, Throwable error) {
        Toast.makeText(MainActivity.this, "請求失敗", 0).show();
    }

   }


   public void click2(View v){
    //獲取用戶輸入的賬號密碼
    EditText et_name = (EditText) findViewById(R.id.et_name);
    EditText et_pass = (EditText) findViewById(R.id.et_pass);

    String name = et_name.getText().toString();
    String pass = et_pass.getText().toString();

    String path = "http://169.254.244.136/Web2/servlet/Login";

    //使用異步HttpClient發送post請求
    AsyncHttpClient client = new AsyncHttpClient();

    //把要提交的數據封裝在rp對象中
    RequestParams rp = new RequestParams();
    rp.put("name", name);
    rp.put("pass", pass);
    //發送get請求
    client.post(path, rp, new MyHandler());
   }
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved