Метод Android Asynctask не отображает данные

I tried to display data(string) from android device to java desktop server application. I was successful in that. I tried to find wifi signal strength from wifi access point to android device. I did that too. Now, I need to integrate this both thing. 

First, is the client code where I find the signal strength and pass it to server. First, I run the server. It runs and waits. As soon as I run the client the signal strength from 1st router is displayed and then the app crashes. I have given the error log. 

It crashes because of Async method in the client. This Async task code works well when I try to send string from android mobile to java desktop server. But, here it gives me an error. I think, I have made some simple error.



Client.java

    package com.example.temp;    
public class MainActivity extends Activity {
    private Socket client;
    private PrintWriter printwriter;
    private EditText textField;
    private Button button;
    private String messsage;

    StringBuilder sb = new StringBuilder();
    public final static String extra = "com.example.temp.MESSAGE";  
    protected static final long TIME_DELAY = 5000;
    TextView mTextView;
    Handler handler=new Handler();  
    int count =0; String data ="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView = (TextView) findViewById(R.id.text_id);
        handler.post(updateTextRunnable);

        messsage=mTextView.getText().toString();

        new Asynctask().execute(messsage);  
    }

    Runnable updateTextRunnable = new Runnable() {
        public void run() {
            if (count < 5) {
                WifiManager mainWifiObj;
                mainWifiObj = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                class WifiScanReceiver extends BroadcastReceiver {
                    public void onReceive(Context c, Intent intent) {
                    }
                }

                WifiScanReceiver wifiReciever = new WifiScanReceiver();
                registerReceiver(wifiReciever, new IntentFilter(
                        WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));                
                List<ScanResult> wifiScanList = mainWifiObj.getScanResults();
                for (ScanResult result : wifiScanList) {
                    if (result.SSID.equals("Dal-WPA2")) {
                        sb.append(result.level);
                    }
                    if (result.SSID.equals("eduroam")) {
                        sb.append(result.level);
                    }
                    if (result.SSID.equals("Dal")) {
                        sb.append(result.level);
                    }
                }               
                count++; mTextView.setText("getting called " +count + sb);
            } else {

            }               
                //----------------code here to send values to java server---
                  handler.postDelayed(this, TIME_DELAY);
                    }
            };



    class Asynctask extends AsyncTask<String, Void, Void> {
        private static final String IP_ADDRESS = "134.190.162.165";
        private static final int DEST_PORT = 4444;

        private EditText mTextField;
        protected Void doInBackground(String... messages) {
          //  if (messages.length != 1) { return null; }
            String message = messages[0];
            Socket client = null;

            try {
                client = new Socket(IP_ADDRESS, DEST_PORT); // connect to server
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            // Write to server.
            try {
                printwriter = new PrintWriter(client.getOutputStream(), true);
                printwriter.write(messsage); // write the message to output stream

                printwriter.flush();
                printwriter.close();
            }
            catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
    }

}     

The  Error from the log cat I found is : It is in the Async task here.

>FATAL EXCEPTION: AsyncTask #1  
         java.lang.RuntimeException: An error occured while executing doInBackground()  
        android.os.AsyncTask$3.done(AsyncTask.java:278)  
        java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)  
        java.util.concurrent.FutureTask.setException(FutureTask.java:124)  
        java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)  


java.util.concurrent.FutureTask.run(FutureTask.java:137)
android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
 at java.lang.Thread.run(Thread.java:856)
 Caused by: java.lang.NullPointerException
com.example.temp.MainActivity$Asynctask.doInBackground(MainActivity.java:114)
com.example.temp.MainActivity$Asynctask.doInBackground(MainActivity.java:1)
android.os.AsyncTask$2.call(AsyncTask.java:264)
java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
 Activity com.example.temp.MainActivity has leaked IntentReceiver com.example.temp.MainActivity $1$1WifiScanReceiver@41756998 that was originally registered here. Are you missing a call to unregisterReceiver()?
02-17 15:13:52.771: E/ActivityThread(25738): android.app.IntentReceiverLeaked: Activity com.example.temp.MainActivity has leaked IntentReceiver com.example.temp.MainActivity$1$1WifiScanReceiver@41756998 that was originally registered here. Are you missing a call to unregisterReceiver()?
 android.app.LoadedApk$ReceiverDispatcher.<init>(LoadedApk.java:763)
android.app.LoadedApk.getReceiverDispatcher(LoadedApk.java:567)
android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:1167)
android.app.ContextImpl.registerReceiver(ContextImpl.java:1154)
android.app.ContextImpl.registerReceiver(ContextImpl.java:1148)
android.content.ContextWrapper.registerReceiver(ContextWrapper.java:348)
com.example.temp.MainActivity$1.run(MainActivity.java:58)
android.os.Handler.handleCallback(Handler.java:605)
android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
android.app.ActivityThread.main(ActivityThread.java:4517)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:511)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760)
at dalvik.system.NativeStart.main(Native Method)

The server just waits for the response and displays the data. With simple string it displays  the data But here, the client crashes so, it is not possible. So, I assume that client code is perfect.

There is no compile time error only run time. In the run(), I call Async method and then do handler.postdelayed, so that code runs again after few second. But it runs correctly till Asynctask class is called In the Async task, it gives me error. 

I am new. It would be great if someone can point out my mistake.

I tried but I am not getting what I should do. I think my logic is correct as individual parts are running. But dont know why async task is not running here.

Thank you in advance.

Edited : The print writer and other sockets closed. 
Still getting the same error.

I have just used class Asynctask and not public class Asycntask, hope there wont be any problem in this.

I just understand from the log file that error is in asynctask background , but exactly the error is not understandable also. 

I dont know where I am getting wrong.

Thanks for the help.

fdvkfdnvkkfdnb fdkvj nfdvnjfdknv fdvnfdvnkdfnv fdjkvnfdkjvnjkfdn fdjvfdjkv fdvndfkjvn fdlvnkdfvn fdkvnfdnvk fdvknfdkvn fdvklmfd fdkv flkk fdkvkfl fdkkklvklfdm flvmalsvmaslvv dfvkfdlkv е lkfdv fdlkvmfdklvm fdvkfdklv dfklvlfdknvkfdnv dfvknfdklvn dfkvfdkvn fdkvnfdkvn dfkkvnfdknv dfjkvnfdkjnv

1 ответ

Я думаю, что проблема возникает потому, что вы не закрываете должным образом client а также printwriter, (Вам необходимо закрыть все потоки для сокета, а также самого сокета.) При повторном выполнении AsyncTask пытается открыть новый сокет, и в конце концов у ОС заканчиваются ресурсы для этого из-за сбоя при закрытии. Призыв к new Socket(...) выдает исключение (которое вы ловите), но затем client остатки null, Поскольку вы не вернетесь после исключения, вы получите NullPointerException, Я думаю, что это NullPointerException это то, что несет ответственность за сбой приложения. (Это на самом деле всего лишь предположение; информация в сообщенной вами ошибке довольно скудна.)

Попробуйте этот код вместо этого:

public class Asynctask extends AsyncTask<String, Void, Void> {        
    private EditText mTextField;
    protected Void doInBackground(String... messages) {
        String message = messages[0];
        Socket client = null;        
        try {
            client = new Socket(IP_ADDRESS, DEST_PORT);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        try {
            printwriter = new PrintWriter(client.getOutputStream(), true);
            printwriter.write(messsage);
        }
            catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (printwriter != null) {
                try {
                    printwriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                printwriter = null;
            }
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } 
        return null;
    }
}
Другие вопросы по тегам