Silver Boy Silver Boy - 26 days ago 8
Android Question

App goes to MainActivity when running class

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.(Handler.java:200)
at android.os.Handler.(Handler.java:114)
at android.widget.Toast$TN.(Toast.java:362)
at android.widget.Toast.(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)

Answer

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.