安卓小案例收集二

原创 2016年05月30日 20:34:24

收集二

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<Person>();
        //查询数据库
        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<String>(this, R.layout.item_listview, //指定作为条目的布局文件
//              R.id.tv, //指定文本显示在哪个文本框
//              objects));

        //把每个条目需要处理的所有数据封装至map中,在把map封装至list中
        //这样就保证了list每个元素都包含了一个条目需要的所有数据
        List<Map<String, Object>> data = new ArrayList<Map<String,Object>>();

        Map<String, Object> map1 = new HashMap<String, Object>();
        map1.put("name", "周杰伦");
        map1.put("photo", R.drawable.photo1);
        data.add(map1);

        Map<String, Object> map2 = new HashMap<String, Object>();
        map2.put("name", "刘德华");
        map2.put("photo", R.drawable.photo2);
        data.add(map2);

        Map<String, Object> map3 = new HashMap<String, Object>();
        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<News> 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<News>();
                    }
                    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<NameValuePair> parameters = new ArrayList<NameValuePair>();
            //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());
   }
版权声明:本文为博主原创文章,未经博主允许不得转载。

安卓小案例收集四(多媒体)

加载大图片 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInst...

安卓小案例收集五(内容提供者、动画)

内容提供者 获取系统短息 插入系统短信 获取系统联系人 插入联系人 内容观察者 Fragment Fragment数据传递 帧动画 补间动画 属性动画内容提供者配置:...

RSS阅读器-安卓小案例

  • 2016年04月17日 18:33
  • 1.95MB
  • 下载

安卓小游戏-猜猜鸡蛋在哪里

  • 2017年11月24日 15:30
  • 17.03MB
  • 下载

2.一个随机生成多种颜色并获取颜色RGB值以及对应十六进制的安卓小应用

安卓学习中,每次选择颜色十六进制都让人头大,试着开发一个应用解决这个问题。 实现效果如下图: 主要功能: 1. 随机生成100种颜色(有重复,重复并不影响选择,没喜欢的颜...

BMI测试 安卓小应用

  • 2016年01月20日 12:41
  • 590KB
  • 下载

安卓小视频压缩代码

  • 2017年08月15日 16:59
  • 47.7MB
  • 下载

初识安卓小程序(Android短信发送器)

首先,先创建一个安卓项目(我的版本是4.4.2的),名字为"短信发送器" 然后在res文件夹下找到layout文件夹,找到activity_main.xml或fragment_main.xml,在里...

安卓小软件

  • 2013年04月06日 13:17
  • 19KB
  • 下载

实用安卓小软件

  • 2012年06月28日 09:42
  • 627KB
  • 下载
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:安卓小案例收集二
举报原因:
原因补充:

(最多只允许输入30个字)