Android06

来源:互联网 发布:宋慧乔长相 知乎 编辑:程序博客网 时间:2024/05/29 19:43

Android06

新闻文本界面的展现

  1. 常规形成文字和图片

    public View getView(int position, View convertView, ViewGroup parent) {    View view = View.inflate(MainActivity.this, R.layout.item, null);    TextView tv_title = (TextView) view.findViewById(R.id.tv_item_title);    TextView tv_desc = (TextView) view.findViewById(R.id.tv_item_desc);    TextView tv_comment = (TextView) view.findViewById(R.id.tv_item_comment);    SmartImageView siv = (SmartImageView) view.findViewById(R.id.iv_item);    NewsItem item = items.get(position);    tv_title.setText(item.getTitle());    tv_desc.setText(item.getDescription());    String type = item.getType();//1  2 3    if("1".equals(type)){        tv_comment.setText("评论:"+item.getComment());    }else if("2".equals(type)){        tv_comment.setText("视频");        tv_comment.setBackgroundColor(0x66ff0000);    }else if("3".equals(type)){        tv_comment.setText("LIVE");        tv_comment.setBackgroundColor(0x660000ff);    }    System.out.println(item.getImage());    siv.setImageUrl(item.getImage());    return view;}
  2. 导入外部框架改图片显示

    public class SmartImageView extends ImageView {    private static final int LOADING_THREADS = 4;    private static ExecutorService threadPool =         Executors.newFixedThreadPool(LOADING_THREADS);private SmartImageTask currentTask;public SmartImageView(Context context) {    super(context);}}----------------------------view.findViewById(R.id.tv_item_comment);SmartImageView siv = (SmartImageView) ----------------------------siv.setImageUrl(item.getImage());


利用开源框架加载显示图片

    <com.smartimageview.ui.SmartImageView    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:id="@+id/siv" />

smartimageview的原理

    /**     * 设置一个网络的图片路径,直接把网络上的图片给显示出来     *      * @param url     */    public void setImageUrl(final String path) {        new Thread() {            public void run() {                try {                    URL url = new URL(path);                    HttpURLConnection conn = (HttpURLConnection) url                            .openConnection();                    conn.setRequestMethod("GET");                    conn.setConnectTimeout(5000);                    int code = conn.getResponseCode();                    if (code == 200) {                        InputStream is = conn.getInputStream();                        Bitmap bitmap = BitmapFactory.decodeStream(is);                        Message msg = Message.obtain();                        msg.obj = bitmap;                        handler.sendMessage(msg);                    }                } catch (Exception e) {                    e.printStackTrace();                }            };        }.start();    }

smartimageview异常的处理

/** * 设置一个网络的图片路径,直接把网络上的图片给显示出来 *  * @param url资源的路径 * @param errorres *            如果图片资源下载失败,显示什么样的默认图片 */public void setImageUrl(final String path, final int errorres) {    new Thread() {        public void run() {            try {                URL url = new URL(path);                HttpURLConnection conn = (HttpURLConnection) url                        .openConnection();                conn.setRequestMethod("GET");                conn.setConnectTimeout(5000);                int code = conn.getResponseCode();                if (code == 200) {                    InputStream is = conn.getInputStream();                    Bitmap bitmap = BitmapFactory.decodeStream(is);                    Message msg = Message.obtain();                    msg.what = SUCESS;                    msg.obj = bitmap;                    handler.sendMessage(msg);                } else {                    Message msg = Message.obtain();                    msg.what = ERROR;                    msg.obj = errorres;                    handler.sendMessage(msg);                }            } catch (Exception e) {                e.printStackTrace();                Message msg = Message.obtain();                msg.what = ERROR;                msg.obj = errorres;                handler.sendMessage(msg);            }        };    }.start();

get方式提交数据-服务器搭建

  1. tomcat服务
  2. javaweb的基础
  3. 要写后台的简单逻辑

采用get的方式提交数据到服务器

String path = "http://192.168.1.103:8080/web/LoginServlet?qq="+URLEncoder.encode(qq, "utf-8")+"&pwd="+URLEncoder.encode(pwd, "utf-8");URL url = new URL(path);conn.setRequestMethod("GET");

POST请求和GET请求的区别

  • GET请求

    优点:使用非常方便,只需要在url后面组拼数据
    缺点:数据在url的后面组拼,不安全,有数据长度限制

  • POST请求

    优点:安全,数据不是在url后面组拼而是通过流的方式写给服务器,数据长度不受限制
    缺点:编写麻烦.

POST方式提交数据到服务器

  • 服务器端有简单的逻辑

    String path = "http://192.168.1.103:8080/web/LoginServlet";URL url = new URL(path);HttpURLConnection conn = (HttpURLConnection) url.openConnection();//1.设置请求方式为POSTconn.setRequestMethod("POST"); //注意单词必须大写.conn.setConnectTimeout(5000);//2.设置http请求数据的类型为表单类型conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");//3.设置给服务器写的数据的长度//qq=10000&pwd=abcdeString data = "qq="+URLEncoder.encode(qq, "utf-8")+"&pwd="+URLEncoder.encode(pwd, "utf-8");conn.setRequestProperty("Content-Length", String.valueOf(data.length())); //4.记得指定要给服务器写数据conn.setDoOutput(true);//5.开始向服务器写数据conn.getOutputStream().write(data.getBytes());

中文乱码问题的处理

  • Android前台是UTF-8编码的,后台服务器tomcat是iso-8859-1编码的,会有乱码问题.
  • 解决方法统一编码集.要么改前台,要么改后台.

  • //先打回原形,在解码
    (message.getBytes(iso-8859-1”“), “UTF-8”);

中文乱码的补充-锟斤拷锟斤初体验

String message = "锟斤拷锟斤拷,锟斤拷锟斤拷,锟斤拷锟斤拷"; System.out.println(new String(message.getBytes("gbk"), "gbk"));

提交数据的中文问题

  1. Get

    String path = "http://192.168.1.103:8080/web/LoginServlet?qq="+URLEncoder.encode(qq, "utf-8")+"&pwd="+URLEncoder.encode(pwd, "utf-8");
  2. POSt

     String data = "qq="+URLEncoder.encode(qq, "utf-8")+"&pwd="+URLEncoder.encode(pwd, "utf-8");

采用httpclient提交数据到服务器

  1. Get

    String path = "http://192.168.1.103:8080/web/LoginServlet?qq="+URLEncoder.encode(qq, "utf-8")+"&pwd="+URLEncoder.encode(pwd, "utf-8");//1.打开浏览器HttpClient client = new DefaultHttpClient();//2.输入地址或者数据HttpGet httpGet = new HttpGet(path);//3.敲回车HttpResponse response = client.execute(httpGet);//获取状态码int code = response.getStatusLine().getStatusCode();InputStream is = response.getEntity().getContent();
  2. POST

    String path = "http://192.168.1.103:8080/web/LoginServlet";//1.打开浏览器HttpClient client = new DefaultHttpClient();//2.输入地址或者数据HttpPost httpPost = new HttpPost(path);List<NameValuePair> parameters = new ArrayList<NameValuePair>();parameters.add(new BasicNameValuePair("qq", qq));parameters.add(new BasicNameValuePair("pwd", pwd));httpPost.setEntity(new UrlEncodedFormEntity(parameters, "utf-8"));//3.敲回车HttpResponse response = client.execute(httpPost);//获取状态码int code = response.getStatusLine().getStatusCode();InputStream is = response.getEntity().getContent();

采用开源框架get的方式提交数据到服务器

String path = "http://192.168.1.103:8080/web/LoginServlet?qq="+URLEncoder.encode(qq)+"&pwd="+URLEncoder.encode(pwd);AsyncHttpClient client = new AsyncHttpClient();client.get(path, new AsyncHttpResponseHandler() {    @Override    public void onSuccess(int statusCode, Header[] headers,            byte[] responseBody) {        tv_status.setText(new String(responseBody));    }    @Override    public void onFailure(int statusCode, Header[] headers,            byte[] responseBody, Throwable error) {        tv_status.setText("http请求失败"+new String(responseBody));    } });

采用开源项目post数据到服务器

String path = "http://192.168.1.103:8080/web/LoginServlet";AsyncHttpClient client = new AsyncHttpClient();RequestParams params = new RequestParams();params.put("qq", qq);params.put("pwd", pwd);client.post(path, params, new AsyncHttpResponseHandler(){    @Override    public void onSuccess(int statusCode, Header[] headers,            byte[] responseBody) {        tv_status.setText("登陆结果:"+new String(responseBody));    }    @Override    public void onFailure(int statusCode, Header[] headers,            byte[] responseBody, Throwable error) {        tv_status.setText("请求失败请检查网络");    }});

上传文件到服务器

public void upload(View view){    String path = et_path.getText().toString().trim();    File file = new File(path);    if(file.exists()&&file.length()>0){        //上传        AsyncHttpClient client = new AsyncHttpClient();        RequestParams params = new RequestParams();        try {            params.put("file", file);        } catch (FileNotFoundException e) {            e.printStackTrace();        }        client.post("http://192.168.1.103:8080/web/UploadServlet", params, new AsyncHttpResponseHandler() {            @Override            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {                Toast.makeText(MainActivity.this, "上传成功", 0).show();            }            @Override            public void onFailure(int statusCode, Header[] headers,                    byte[] responseBody, Throwable error) {                Toast.makeText(MainActivity.this, "上传失败", 0).show();            }        });    }
0 0
原创粉丝点击