最近在自学Android开发,从这篇开始作为我学习android开发的笔记,来记录学习过程中遇到的问题点和其解决的方法;

Ui界面代码

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.lidezhen.myapplication.MainActivity"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/text1"
android:hint="请是输入网址"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="打开"
android:onClick="Onclick"/>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/tv1"
android:hint="这是源码"/> </LinearLayout>

界面后台代码

package com.example.lidezhen.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView; import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL; public class MainActivity extends AppCompatActivity { EditText et;
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et= (EditText) findViewById(R.id.text1);
tv= (TextView) findViewById(R.id.tv1);
// if (android.os.Build.VERSION.SDK_INT > 9) {
// StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
// StrictMode.setThreadPolicy(policy);
// }
}
public void Onclick(View v)
{ try {
String path=et.getText().toString(); URL url = new URL(path);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
int code=con.getResponseCode();
if (code==200)
{ InputStream stream = con.getInputStream();
ByteArrayOutputStream os=new ByteArrayOutputStream();
int len=-1;
byte[] buff=new byte[1024];
while ( (len=stream.read(buff))!=-1)
{
os.write(buff,0,len); }
tv.setText(os.toString());
}
} catch (Exception e) {
Log.e("错误",e.toString());
} }
}编译并执行程序
 

  程序报错

07-20 02:30:00.361 15820-15820/com.example.lidezhen.myapplication E/错误: android.os.NetworkOnMainThreadException

错误原因:Android在4.0之前的版本 支持在主线程中访问网络,但是在4.0以后对这部分程序进行了优化,也就是说访问网络的代码不能写在主线程中了(我的虚拟机是android6.0的)

错误解决方法1:

在onCreate方法中添加如下代码

 if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}

方法2:在点击事件里面添加多线程

public void Onclick(View v)
{
new Thread() {
@Override
public void run() {
try {
String path=et.getText().toString(); URL url = new URL(path);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
int code=con.getResponseCode();
if (code==200)
{ InputStream stream = con.getInputStream();
ByteArrayOutputStream os=new ByteArrayOutputStream();
int len=-1;
byte[] buff=new byte[1024];
while ( (len=stream.read(buff))!=-1)
{
os.write(buff,0,len); }
tv.setText(os.toString());
}
} catch (Exception e) {
Log.e("错误",e.toString());
} }
}.start();

程序执行成功

这样开新线程后程序还是报错

07-20 02:49:12.203 32712-707/com.example.lidezhen.myapplication E/错误: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

意思就是新的线程不能操作界面控件

解决方法:添加handeler

package com.example.lidezhen.myapplication;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView; import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL; public class MainActivity extends AppCompatActivity { EditText et;
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et= (EditText) findViewById(R.id.text1);
tv= (TextView) findViewById(R.id.tv1); // if (android.os.Build.VERSION.SDK_INT > 9) {
// StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
// StrictMode.setThreadPolicy(policy);
// }
}
public void Onclick(View v)
{ new Thread() {
@Override
public void run() {
try { String path=et.getText().toString();
URL url = new URL(path);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
int code=con.getResponseCode();
if (code==200)
{ InputStream stream = con.getInputStream();
ByteArrayOutputStream os=new ByteArrayOutputStream();
int len=-1;
byte[] buff=new byte[1024];
while ( (len=stream.read(buff))!=-1)
{
os.write(buff,0,len); }
// tv.setText(os.toString());
Message msg=new Message();
msg.obj=os.toString();
handler.sendMessage(msg);
}
} catch (Exception e) {
Log.e("错误",e.toString());
} }
}.start(); }
Handler handler=new Handler(){
public void handleMessage(Message msg) {
String s=(String)msg.obj;
tv.setText(s);
} }; }

这样就不会再报异常

最新文章

  1. Prototype原型(创建型模式)
  2. SharePoint Server 2016 Update
  3. PHP会话处理相关函数介绍
  4. CodeBlocks16.01+wxWidgets3.0.2
  5. MySQL Plugin &#39;InnoDB&#39; init function returned error一例
  6. JAVA 异常对于性能的影响
  7. java内存模型优化建议
  8. HTML5下通过response header解决跨域AJAX cookie的问题
  9. 将以管理员方式运行cmd运行方式放到win7任务栏
  10. E - Fibonacci Again(找规律)
  11. 初见 ThreadLocal 类
  12. poj2100还是尺取
  13. Luogu 2756 飞行员配对方案问题(二分图最大匹配)
  14. MySQL/MariaDB 在插入数据的时候提示 Incorrect string value
  15. spark下使用submit提交任务后报jar包已存在错误
  16. Java如何在运行时识别类型信息?
  17. 根据 label 的 text 的大小和长度 获取 尺寸
  18. Linux下载命令之rpm和yum比较
  19. JSON parse error: Cannot deserialize instance of `int` out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc
  20. ThinkPHP3的使用

热门文章

  1. AnguarJS 第二天----数据绑定
  2. .NET中那些所谓的新语法之三:系统预定义委托与Lambda表达式
  3. NoSQL初探之人人都爱Redis:(4)Redis主从复制架构初步探索
  4. [.net 面向对象程序设计深入](5)MVC 6 —— 构建跨平台.NET开发环境(Windows/Mac OS X/Linux)
  5. WCF:传输EntityFramework 实体类的POCO 代理
  6. intellij IDEA 出现“Usage of API documented as @since 1.6+”的解决办法
  7. 【hadoop摸索系列】记录使用libhdfs访问hdfs的关键问题
  8. c#写windows服务
  9. 模拟image的ajaxPrefilter与ajaxTransport处理
  10. Conversion Operators in OpenCascade