android连接mysql数据库,NetworkOnMainThreadException引起CommunicationsException

来源:互联网 发布:网络代购图片 编辑:程序博客网 时间:2024/06/05 18:12
error:com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.

刚开始,检查:

1.正确引入jar包

2.把 mysql 的 wait_timeout 设置长一点

3.数据库ip不能设置成127.0.0.1或localhost,设置成本机地址

4.(1)把Mysql需要访问的库的权限更改下,赋予某某一个用户访问权限,更改完后才可以支持远程访问。我的电脑上的用户名是“root”,密码是“root”.
    grant all privileges on 数据库名.*  to 'root'@‘localhost’ IDENTIFIED by 'root';
    grant all privileges on 数据库名.*  to 'root'@'%' IDENTIFIED by  'root';
    flush privileges;
    (解释:localhost表示可以通过本机访问指定的数据库。@‘%’表示可以通过远程访问指定的数据库。)
   (2)创建新用户mark
    grant all privileges on  *.*  to  'mark'  @'%'  identified  by  '123456';
    flush privileges;
    授予用户 mark,密码 123456,可以使用任意 ip (%)访问任何数据库(*.*) .

5.重启mysql服务

    启动: net stop mysql
  停止: net start mysql

    试过了上面的方法,还是不行,结果发现,该error cause="java.net.SocketException:android.os.NetworkOnMainThreadException",在网上查了下,

一个APP如果在主线程中请求网络操作,将会抛出此异常。Android这个设计是为了防止网络请求时间过长而导致界面假死的情况发生。

解决方法:

第一种方法:使用StrictMode在MainActivity文件的setContentView(R.layout.activity_main)下面加上如下代码

    if (android.os.Build.VERSION.SDK_INT > 9) {

       StrictMode.ThreadPolicy policy = newStrictMode.ThreadPolicy.Builder().permitAll().build();

       StrictMode.setThreadPolicy(policy);

    }


第二种方法,将请求网络资源的代码使用Thread去操作。在Runnable中做HTTP请求,不用阻塞UI线程。

    public void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);

       this.setContentView(R.layout.main_view);

       newThread(runnable).start();

    }

     Handler handler = new Handler(){

        @Override

        public void handleMessage(Message msg) {

        super.handleMessage(msg);

        Bundle data= msg.getData();

        String val= data.getString("value");

        Log.i(TAG,"请求结果:" +val);

        }

    }

    Runnable runnable = new Runnable(){

        @Override

        public void run() {

            // TODO:http request.

            Message msg= new Message();

            Bundle data= new Bundle();

            data.putString("value","请求结果");

            msg.setData(data);

            handler.sendMessage(msg);

    }

推荐使用线程池!

1 0
原创粉丝点击