炒空心菜 2016-11-25 17:31 采纳率: 66.7%
浏览 1464
已采纳

Android activity 中 打开Url 网络地址报错

public void dialog(View view)
{
String msg="";
Toast toast=Toast.makeText(this, "", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);

    LinearLayout layout=(LinearLayout)toast.getView();
    layout.setMinimumHeight(50);
    ImageView image=new ImageView(getApplicationContext());
    image.setImageResource(R.drawable.ic_launcher);
    image.setMaxHeight(50);
    image.setMaxWidth(50);
    layout.addView(image, 0);
    TextView txt=new TextView(getApplicationContext());

    try
    {

        String url_1="http://192.168.43.1:8080/android/legendary.db",url_2="http://localhost:8080/android/legendary.db";
        URI uri=new URI(url_2);
        URL url=uri.toURL(); 
        url.openConnection();
        InputStream in=url.openStream();
        toast.setText("---->");
        txt.setText("\n-----****");
        txt.setTextColor(Color.parseColor("#ffaaff"));
    }
    catch (Exception e)
    {
        msg = e.toString();
        e.printStackTrace();
        txt.setText(e.toString() + "\n-----****");
        txt.setTextColor(Color.RED);
        txt.setTextSize(16);

    }
    layout.addView(txt, 1);
    toast.show();

latelog2(msg);
setlog2();
notice("错误---->", msg);

}

/*错误信息
android.os.NetworkOnMainThreadException
*/

  • 写回答

5条回答 默认 最新

  • 全栈极简 博客专家认证 2016-11-26 00:27
    关注

    错误信息是不能在主线程中进行网络相关的操作。应该用thread+handler或者asynctask处理。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 opencv 无法读取视频
  • ¥15 用matlab 实现通信仿真
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数
  • ¥15 ffmpeg如何安装到虚拟环境
  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图