AsyncTASK出错..... NetworkOnMainThreadException

时间:2017-01-07 18:46:54

标签: java android android-asynctask

我正在使用AsyncTask在后台执行某些操作......

我在

中调用Oncreate方法中的AsyncTask
  

new BGSERIVCE()。execute();

public class BGSERIVCE extends AsyncTask<Void,Void,Void> {


        @Override
        protected Void doInBackground(Void... params) {


            FirebaseUser currentuser = FirebaseAuth.getInstance().getCurrentUser();

            Cdb = getApplicationContext().openOrCreateDatabase("zumi1.db", Context.MODE_PRIVATE, null);
            Cdb.execSQL(TABLE_CREATE);


//            Toast.makeText(getApplicationContext(), "background Running....", Toast.LENGTH_SHORT).show();
            String email_Current = currentuser.getEmail().replace(".", "@");
            ref = new Firebase("https://zumi-60a8f.firebaseio.com/Users/");
            final ContentValues values = new ContentValues();
            ref.child(email_Current).addValueEventListener(new com.firebase.client.ValueEventListener() {
                @Override
                public void onDataChange(com.firebase.client.DataSnapshot snapshot) {
                    for (com.firebase.client.DataSnapshot postSnapshot : snapshot.getChildren()) {


                        //Adding it to a string
                        String url = snapshot.child("image").getValue().toString();
                        String Dname = snapshot.child("Dname").getValue().toString(); // NAME

                        String email = snapshot.child("email_phone").getValue().toString().replace("@zumi.com", ""); // PHONE@EMAIL.co
                        String status_E = snapshot.child("status").getValue().toString();


                        values.put("email_phone", email);
                        values.put("status", status_E);
                        values.put("Dname", Dname);
                        values.put("snyc", "Yes");
                        try {
                            Toast.makeText(MainActivity.this, "URL : " + url, Toast.LENGTH_SHORT).show();
                            InputStream is = (InputStream) new URL(url).getContent();
                            byte[] image = new byte[is.available()];
                            is.read(image);
                            // values.put("image", image);

                            Cdb.insert("current_Luser", null, values);

                            is.close();

                        } catch (Exception e) {
                            //Toast.makeText(MainActivity.this, "error Occured : "+e, Toast.LENGTH_SHORT).show();
                            Log.e("", "" + e);

                        }
                        //  values.put("image",);


                    }
                }

                @Override
                public void onCancelled(FirebaseError firebaseError) {
                    //System.out.println("The read failed: " + firebaseError.getMessage());
                }
            });

            return null;
        }
    }

错误:&gt;&gt;&gt;

  

[01-08 00:09:54.023 8732:8732 E /]                                                                                android.os.NetworkOnMainThreadException

01-08 00:09:54.028 8732-8732/com.example.cosmic.zumi_test I/System.out:
     

开放:https://firebasestorage.googleapis.com/v0/b/zumi-60a8f.appspot.com/o/Profile_Image%2Fcropped-122662379.jpg?alt=media&token=c8f3e9ee-637d-4bdd-9a76-a186ecd07e37

01-08 00:09:54.028 8732-8732/com.example.cosmic.zumi_test I/System.out: [CDS][DNS] getAllByNameImpl netId = 0
01-08 00:09:54.028 8732-8732/com.example.cosmic.zumi_test D/libc-netbsd: [getaddrinfo]: hostname=firebasestorage.googleapis.com;
     

servname =(NULL); cache_mode =(null),netid = 0;标记= 0

01-08 00:09:54.028 8732-8732/com.example.cosmic.zumi_test D/libc-netbsd: [getaddrinfo]: ai_addrlen=0; ai_canonname=(null);
     

填上ai_flags = 4; ai_family = 0

请帮助......

1 个答案:

答案 0 :(得分:1)

即使您启动了在不同线程上运行的AsyncTask,也会在主线程上执行onDataChange上的回调。

那里,一旦到达 InputStream is = (InputStream) new URL(url).getContent(); 它在NetworkOnMainThreadException

上崩溃了

Firebase为您完成工作,并将网络调用委托给工作线程。仅对InputStream

使用AsyncTask或Thread-Runnable
FirebaseUser currentuser = FirebaseAuth.getInstance().getCurrentUser();
    Cdb = getApplicationContext().openOrCreateDatabase("zumi1.db", Context.MODE_PRIVATE, null);
    Cdb.execSQL(TABLE_CREATE);

    String email_Current = currentuser.getEmail().replace(".", "@");
    ref = new Firebase("https://zumi-60a8f.firebaseio.com/Users/");
    final ContentValues values = new ContentValues();
    ref.child(email_Current).addValueEventListener(new com.firebase.client.ValueEventListener() {
        @Override
        public void onDataChange(com.firebase.client.DataSnapshot snapshot) {
            for (com.firebase.client.DataSnapshot postSnapshot : snapshot.getChildren()) {

                //Adding it to a string
                String url = snapshot.child("image").getValue().toString();
                String Dname = snapshot.child("Dname").getValue().toString(); // NAME

                String email = snapshot.child("email_phone").getValue().toString().replace("@zumi.com", ""); // PHONE@EMAIL.co
                String status_E = snapshot.child("status").getValue().toString();

                values.put("email_phone", email);
                values.put("status", status_E);
                values.put("Dname", Dname);
                values.put("snyc", "Yes");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Toast.makeText(MainActivity.this, "URL : " + url, Toast.LENGTH_SHORT).show();
                            InputStream is = (InputStream) new URL(url).getContent();
                            byte[] image = new byte[is.available()];
                            is.read(image);
                            // values.put("image", image);
                            Cdb.insert("current_Luser", null, values);
                            is.close();

                        } catch (Exception e) {
                            //Toast.makeText(MainActivity.this, "error Occured : "+e, Toast.LENGTH_SHORT).show();
                            Log.e("", "" + e);
                        }
                    }
                }).start();
            }
        }
    });