炒空心菜 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 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试