0

I am trying to run this script, but somewhere in doInBackground() it's being launched back to starting activity.

(What I'm trying to do is scan all available SSID's and check them in database)

Here is my code:

Button btnHit;
TextView txtJson;
private static final String  TAG = "My Activity";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_find_connection);

    btnHit = (Button) findViewById(R.id.request);
    txtJson = (TextView) findViewById(R.id.results);


    if (Build.VERSION.SDK_INT > 22) {

        final String CoarseLocation = Manifest.permission.ACCESS_COARSE_LOCATION;
        final String AccessWifi = Manifest.permission.ACCESS_WIFI_STATE;
        final String ChangeWifi = Manifest.permission.CHANGE_WIFI_STATE;

        if (checkSelfPermission(CoarseLocation) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 123);
        }

        if (checkSelfPermission(AccessWifi) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.ACCESS_WIFI_STATE}, 123);
        }

        if (checkSelfPermission(ChangeWifi) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.CHANGE_WIFI_STATE, Manifest.permission.CHANGE_WIFI_STATE}, 123);
        }
    }



    LocationManager lman = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
    boolean network_enabled = false;

    try
    {
        network_enabled = lman.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
    } catch (Exception ex) {}


    if (!network_enabled)
    {
        startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
    }



    final WifiManager mWifiManager = (WifiManager) getSystemService(WIFI_SERVICE);

    mWifiManager.setWifiEnabled(true);

    IntentFilter filter = new IntentFilter();
    filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);

    registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            List<ScanResult> results = mWifiManager.getScanResults();
            final int Amount = results.size();

            Log.v(TAG, "Wifi Scan Results Count: " + Amount);

            int num = 0;

            while (num < Amount)
            {
                Log.v(TAG, "SSID  =  " + results.get(num).SSID);

                num = num+1;
            }

            int dis = 0;

            String res = "Results:\n\n\n";

            while (dis < Amount)
            {
                res = res + results.get(dis).SSID + "\n\n";

                String surl = "http://myurl.com?ssid=" + results.get(dis).SSID;
                new JsonTask().execute(surl);

                dis = dis+1;
            }

            TextView textres = (TextView) findViewById(R. id. resnet);
            textres.setText(res);

        }
    }, filter);

    mWifiManager.startScan();

}



private class JsonTask extends AsyncTask<String, String, String> {

    ProgressDialog pd;

    protected void onPreExecute() {
        super.onPreExecute();

        pd = new ProgressDialog(FindConnection.this);
        pd.setMessage("Please wait");
        pd.setCancelable(false);
        pd.show();
    }

    protected String doInBackground(String... params) {


        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();


            InputStream stream = connection.getInputStream();

            reader = new BufferedReader(new InputStreamReader(stream));

            StringBuffer buffer = new StringBuffer();
            String line = "";

            while ((line = reader.readLine()) != null) {

                buffer.append(line+"\n");

                if (line != "null")
                {
                    Toast.makeText(getApplicationContext(), "Found one...", Toast.LENGTH_SHORT).show();
                }

                Log.d("Response: ", "> " + line);

            }

            return buffer.toString();


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if (pd.isShowing()){
            pd.dismiss();
        }
        txtJson.setText(result);
    }
}

And here's the error that I get:

11-12 19:48:56.920 21711-21811/com.comhet.comhet E/AndroidRuntime:
FATAL EXCEPTION: AsyncTask #1
Process: com.comhet.comhet, PID: 21711
java.lang.RuntimeException: An error occurred while executing doInBackground()
   at android.os.AsyncTask$3.done(AsyncTask.java:309)
   at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
   at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
   at java.util.concurrent.FutureTask.run(FutureTask.java:242)
   at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)  
   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
   at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.RuntimeException: Can't create handler inside thread
that has not called Looper.prepare()
   at android.os.Handler.<init>(Handler.java:200)
   at android.os.Handler.<init>(Handler.java:114)
   at android.widget.Toast$TN.<init>(Toast.java:362)
   at android.widget.Toast.<init>(Toast.java:109)
   at android.widget.Toast.makeText(Toast.java:276)
   at com.comhet.comhet.FindConnection$JsonTask.doInBackground(FindConnection.java:194)
   at com.comhet.comhet.FindConnection$JsonTask.doInBackground(FindConnection.java:156)
   at android.os.AsyncTask$2.call(AsyncTask.java:295)
   at java.util.concurrent.FutureTask.run(FutureTask.java:237)
   at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
   at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
   at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
   at java.lang.Thread.run(Thread.java:818)
CEGRD
  • 7,787
  • 5
  • 25
  • 35
Silver Boy
  • 113
  • 1
  • 1
  • 8
  • You may find that [other HTTP libraries](http://stackoverflow.com/questions/16902716/comparison-of-android-networking-libraries-okhttp-retrofit-volley) are much easier to deal with than AsyncTask – OneCricketeer Nov 12 '16 at 18:19
  • You may be right. I did this with AsyncTask because of the tutorial that I've found online. It was the only one that was working for me. – Silver Boy Nov 12 '16 at 18:22
  • Well, `line != "null"` is not how you compare Java strings. And you cannot Toast within `doInBackground`, so if your tutorial had those, it isn't right. – OneCricketeer Nov 12 '16 at 18:24
  • In my php file I have this if ($res == "") { echo "null"; } else { echo $res; } and yes, even if it echo'es null it still somehow passes through if statement. Any ideas how? – Silver Boy Nov 12 '16 at 18:32
  • [Java isn't like PHP](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – OneCricketeer Nov 12 '16 at 18:34
  • So is there a proper way to compare these two somehow? – Silver Boy Nov 12 '16 at 18:39
  • Read the link? That is how you compare Java strings correctly – OneCricketeer Nov 12 '16 at 18:41
  • OH GOSH. I haven't seen it, I must be colourblind. Thanks! – Silver Boy Nov 12 '16 at 18:43

3 Answers3

1

You are trying to show a Toast in the doInBackground() method of the AsyncTask. This is not allowed, as the doInBackground() method runs on a background thread and cannot perform actions related to the UI thread.

If you want to check the returned value, log the returned value or make the Toast inside the onPostExecute() method.

rhari
  • 1,367
  • 1
  • 11
  • 19
0

") Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()"

You can't create a Handler on a thread that hasn't called Looper.prepare. The main thread has that called for you. If you want to post to the main thread, you need to create than handler while on the main thread.

Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127
0

Have a look at your doInBackground method
You cannot do UI related operations in doInBackground.It should be done in onPostExecute{} method.

remove this from doInBackground:

while ((line = reader.readLine()) != null) {

            buffer.append(line+"\n");

            if (line != "null")
            {
                Toast.makeText(getApplicationContext(), "Found one...", Toast.LENGTH_SHORT).show();
            }

            Log.d("Response: ", "> " + line);

        }
}
Rajesh Gosemath
  • 1,812
  • 1
  • 17
  • 31