private final WorkerRunnable<Params, Result> mWorker;
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
Params[] mParams;
}
I take red line in mWorker = new WorkerRunnable<Params, Result>() row.This is java own class.I don't understand how can i take error.Please help me.
public AsyncTask(Looper callbackLooper) {
mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper()
? getMainHandler()
: new Handler(callbackLooper);
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
mTaskInvoked.set(true);
Result result = null;
try {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
//noinspection unchecked
result = doInBackground(mParams);
Binder.flushPendingCommands();
} catch (Throwable tr) {
mCancelled.set(true);
throw tr;
} finally {
postResult(result);
}
return result;
}
};
I called execute in oncreate() method like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_solution);
resultt = findViewById(R.id.recognizeResult2);
resultview = findViewById(R.id.textView);
new WolframFeed().execute();
}
and I use AsyncTask like this
private class WolframFeed extends AsyncTask<Void, Void, String> {
private WAException exception;
#Override
protected String doInBackground(Void... params) {
String result="";
inputText = "solve " +resultt.getText().toString();
try {
Log.e("TRYing", "wolfram try/");
WAEngine engine = new WAEngine();
engine.setAppID(APP_ID);
//engine.addPodState("Result__Step-by-step solution");
engine.addFormat("plaintext");
WAQuery query = engine.createQueryFromURL(createFullURL());
/*WAQuery query = engine.createQuery();
query.setInput(inputText);*/
WAQueryResult queryResult = engine.performQuery(query);
if (queryResult.isError()) {
String err= "Query error" + " error code: " + queryResult.getErrorCode() + " error message: " + queryResult.getErrorMessage();
Log.e("err: ",err);
} else if (!queryResult.isSuccess()) {
Log.e("err: " ,"Query was not understood; no results available.");
} else {
// Got a result.
Log.e("err: ","Successful query. Pods follow:\n");
for (WAPod pod : queryResult.getPods()) {
if (!pod.isError()) {
result+="\n";
for (WASubpod subpod : pod.getSubpods()) {
for (Object element : subpod.getContents()) {
if (element instanceof WAPlainText) {
if(((WAPlainText) element).getText()!=""){
result+=pod.getTitle();
result+= ((WAPlainText) element).getText();
result+="\n";
}
}
}
}
}
}
}
} catch (WAException e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
resultview.setText(result);
}
}
Please help me where am i making a mistake.
Related
I am writing a programm that returns me a ArrayList of Strings. Problem is, when I call the method the list is not filled yet so I get an empty list back .
I tried it with a thread but now I get a null reference when I call the method. By the way i had to implement a async task, otherwise I get an exception when trying to use InetAddress.
private class DeviceManager extends Thread {
private ArrayList<String> deviceList;
private String networkIP;
public DeviceManager(String networkIP) {
this.networkIP = networkIP;
}
public void run() {
getDeviceList();
}
public ArrayList<String> getDeviceList() {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
deviceList = new ArrayList<String>();
InetAddress address;
Log.i("NetworkIPgetDeviceList", networkIP);
String deviceIP = networkIP;
for (int i = 0; i < 255; i++) {
address = InetAddress.getByName(deviceIP += "" + i);
if (address.isReachable(2000)) {
Log.i("Devicefound", deviceIP);
deviceList.add(deviceIP);
}
deviceIP = networkIP;
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}.execute();
return deviceList;
}
public ArrayList<String> getList() {
return this.deviceList;
}
}
Artur what you are doing in your code is starting a thread to retrieve device list and then another thread(AsyncTask) to actually creates the device list. So you have three threads running here simultaneously (assuming you are using DeviceManager class in UIThread). The reason getDeviceList() is returning null is because AsyncTasks doInBackground hasn't run yet to collect your device list it might be waiting for its chance to get scheduled. so to conclude that, you just need one thread(other than UIThread), it can either be a Thread or AsyncTask (more preferable as it gives better control) as rusted brain has used in his answer. I prefer to make DeviceManager as AsyncTask (just a bit cleaner and if device managers only task is to retrieve device list) as code below.
in AsyncTask doInBackground runs in a background thread(as name suggests) and onPostExecute runs on the UI thread after doInBackground
class DeviceManager extends AsyncTask<String, Void, List<String>> {
private ConnectionCompleteListener listener;
public interface ConnectionCompleteListener {
void onSuccess(List<String> deviceList);
// if you need to know reason for failure you can add
// parameter to onFailure
void onFailure();
}
public DeviceManager(ConnectionCompleteListener listener) {
this.listener = listener;
}
#Override
protected List<String> doInBackground(String... params) {
List<String> deviceList = new ArrayList<>();
String networkIP = params[0];
try {
InetAddress address;
Log.i("NetworkIPgetDeviceList", networkIP);
String deviceIP = networkIP;
for (int i = 0; i < 255; i++) {
address = InetAddress.getByName(deviceIP += "" + i);
if (address.isReachable(2000)) {
Log.i("Devicefound", deviceIP);
deviceList.add(deviceIP);
}
deviceIP = networkIP;
}
} catch (IOException e) {
deviceList = null;
e.printStackTrace();
}
return deviceList;
}
#Override
protected void onPostExecute(List<String> deviceList) {
if (deviceList == null) {
this.listener.onFailure();
} else {
this.listener.onSuccess(deviceList);
}
}
}
so in your activity you can call
new DeviceManager(new DeviceManager.ConnectionCompleteListener
() {
#Override
public void onSuccess(List<String> deviceList) {
}
#Override
public void onFailure() {
}
}).execute("YOUR_NETWORK_IP");
You are doing it completely wrong. A Thread runs in the background and so does AsyncTask, so basically you are making a background task run in background. Inception.
Try this:
public class DeviceManager {
private ArrayList<String> deviceList;
private String networkIP;
private ConnectionCompleteListener listener;
public interface ConnectionCompleteListener {
void onSuccess();
void onFailure();
}
public void setConnectionCompleteListener(ConnectionCompleteListener listener) {
this.listener = listener;
}
public DeviceManager(String networkIP) {
this.networkIP = networkIP;
}
public void getDeviceList() {
new AsyncTask<Void, Void, Boolean>() {
#Override
protected void onPostExecute(Boolean result) {
if(result) listener.onSuccess();
else listener.onFailure();
}
#Override
protected Boolean doInBackground(Void... params) {
try {
deviceList = new ArrayList<String>();
InetAddress address;
Log.i("NetworkIPgetDeviceList", networkIP);
String deviceIP = networkIP;
for (int i = 0; i < 255; i++) {
address = InetAddress.getByName(deviceIP += "" + i);
if (address.isReachable(2000)) {
Log.i("Devicefound", deviceIP);
deviceList.add(deviceIP);
}
deviceIP = networkIP;
}
return true;
} catch (UnknownHostException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
return null;
}
}.execute();
}
public ArrayList<String> getList() {
return this.deviceList;
}
}
Then in your other class:
private class classname{
DeviceManager manager=new DeviceMnager(networkIp);
manger.setConnectionCompleteListener(new DeviceManager.ConnectionCompleteListener() {
#Override
public void onSuccess() {
// get your list here
manager.getList();
}
#Override
public void onFailure() {
// connection failed show error
}
});
}
You are getting empty array list because as you are using async task for getting array list and async task doINBackground method runs on different thread(means not on main thread). So when your program runs then your program doesn't wait for async task response.
You can solve this like that...
Use onPostExecute method in async task class and return the arraylist
#Override
protected void onPostExecute(Void result) {
//return array list here
getList();
}
Hope this will help you
First of All you don't need to make DeviceManager a thread as the task which you are running in getDeviceList will start in another new thread. Second You shouldn't wait on main(UI) thread so instead of waiting callback is a better mechanism.
If you insist on the same code try this..
public class DeviceManager extends Thread {
private ArrayList<String> deviceList;
private String networkIP;
private boolean dataAvailable;
public DeviceManager(String networkIP) {
this.networkIP = networkIP;
}
public void run() {
getDeviceList();
}
public ArrayList<String> getDeviceList() {
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
deviceList = new ArrayList<String>();
InetAddress address;
Log.i("NetworkIPgetDeviceList", networkIP);
String deviceIP = networkIP;
for (int i = 0; i < 255; i++) {
System.out.println("checking " + i);
address = InetAddress.getByName(deviceIP += "" + i);
if (address.isReachable(2000)) {
Log.i("Devicefound", deviceIP);
deviceList.add(deviceIP);
}
deviceIP = networkIP;
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
dataAvailable = true;
synchronized (DeviceManager.this) {
DeviceManager.this.notify();
}
return null;
}
}.execute();
return deviceList;
}
synchronized public ArrayList<String> getList() {
while (!dataAvailable) {
try {
wait();
} catch (InterruptedException e) {
}
}
return this.deviceList;
}
}
I am having trouble with my listblogs=parseJSONResponse(result), result is underlined red and if I hover over it it says that, I cannot apply a parseJsonResponse JSONARRAY to a JSONARRAY[]. Does anyone know why this is being caused does it have something to do with the params?
class YourTask extends AsyncTask<JSONArray, String, ArrayList<Blogs> > {
#Override
protected ArrayList<Blogs> doInBackground(JSONArray... result) {
listblogs.clear(); // here you clear the old data
listblogs=parseJSONResponse(result);
return listblogs;
}
#Override
protected void onPostExecute(ArrayList<Blogs> blogs) {
mAdapterDashBoard.setBloglist(listblogs);
}
}
private void JsonRequestMethod() {
final long start = SystemClock.elapsedRealtime();
mVolleySingleton = VolleySingleton.getInstance();
//intitalize Volley Singleton request key
mRequestQueue = mVolleySingleton.getRequestQueue();
//2 types of requests an Array request and an Object Request
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, URL_API, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
System.out.print(response);
listblogs = new YourTask().doInBackground();
listblogs.clear();
listblogs=parseJSONResponse(response);
try {
listblogs = new YourTask().execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println(response);
Log.d("Testing", "Time elapsed: " + (SystemClock.elapsedRealtime() - start));
System.out.println("it worked!!!");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
mRequestQueue.add(request);
}
private ArrayList<Blogs> parseJSONResponse(JSONArray response) {
if (!response.equals("")) {
try {
StringBuilder data = new StringBuilder();
for (int i = 0; i < response.length(); i++) {
JSONObject currentQuestions = response.getJSONObject(i);
String text = currentQuestions.getString("text");
String points = currentQuestions.getString("points");
String ID=currentQuestions.getString("id");
String studentId = currentQuestions.getString("studentId");
String DateCreated=currentQuestions.getString("created");
long time=Long.parseLong(DateCreated.trim());
data.append(text + "\n" + points + "\n");
System.out.println(data);
Blogs blogs = new Blogs();
blogs.setId(ID);
blogs.setMstudentId(studentId);
blogs.setMtext(text);
blogs.setPoints(points);
//The dateCreated was off by 1 hour so 3600000 ms where added=1hour, (UPDATE)
blogs.setDateCreated(getTimeAgo(time));
System.out.println(time + "time");
listblogs.add(blogs);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return listblogs;
}
AsyncTask
public class MyAsyncTask extends AsyncTask<Void, Void, ArrayList> {
JsonArray myJsonArray;
#Override
protected void onPreExecute() {
super.onPreExecute();
mVolleySingleton = VolleySingleton.getInstance();
mRequestQueue = mVolleySingleton.getRequestQueue();
listblogs.clear();
}
#Override
protected ArrayList doInBackground(Void... params) {
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, URL_API, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
myJsonArray = response;
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
mRequestQueue.add(request);
return null;
}
#Override
protected void onPostExecute(ArrayList arrayList) {
super.onPostExecute(arrayList);
ArrayList<Blogs> blogsArrayList = new ArrayList<>();
try {
StringBuilder data = new StringBuilder();
for (int i = 0; i < myJsonArray.length(); i++) {
JSONObject currentQuestions = myJsonArray.getJSONObject(i);
String text = currentQuestions.getString("text");
String points = currentQuestions.getString("points");
String ID=currentQuestions.getString("id");
String studentId = currentQuestions.getString("studentId");
String DateCreated=currentQuestions.getString("created");
long time=Long.parseLong(DateCreated.trim());
data.append(text + "\n" + points + "\n");
System.out.println(data);
Blogs blogs = new Blogs();
blogs.setId(ID);
blogs.setMstudentId(studentId);
blogs.setMtext(text);
blogs.setPoints(points);
//The dateCreated was off by 1 hour so 3600000 ms where added=1hour, (UPDATE)
blogs.setDateCreated(getTimeAgo(time));
System.out.println(time+"time");
blogsArrayList.add(blogs);
}
} catch (JSONException e) {
e.printStackTrace();
}
return blogsArrayList;
}
ArrayList
synchronous:
listblogs = new MyAsyncTask().execute().get();
asynchronous:
....
} catch (JSONException e) {
e.printStackTrace();
}
listblogs = blogsArrayList;
return blogsArrayList;
}
new MyAsyncTask().execute();
you can run any code inside an async task like this:
public class YourTask extends AsyncTask<String, Void, ArrayList<Blogs> > {
private static final String TAG = YourTask.class.getSimpleName();
private JSONArray mResponse;
private Activity mActivity;
public YourTask(final Activity activity, final JSONArray response) {
super();
this.mActivity = activity;
this.mResponse = response;
}
#Override
protected ArrayList<Blogs> doInBackground(String... params) {
if (!mResponse.equals("")) {
// Your Code
}
return listblogs;
}
#Override
protected void onPostExecute(final ArrayList<Blogs> blogs) {
if (mActivity instanceOf YourActivity) {
((YourActivity) activity).finishTask(blogs);
}
}
#Override
protected void onCancelled() {}
}
call this Task from your activity like:
AsyncTask<String, Void, JSONArray> task = new YourTask(this, response);
task.executeContent();
Basically just send the JSONArray you want to parse to the Async Task and handle all the UI in den finishTask method in your Activity. The advantage is that you can extract your task in an extra file and leave your activity to just handle controlling your views.
When the new message is received, message should be passed to the internet for my further business logic.
To receive the new messages I used onReceive of broadcastreceiver and to process the internet business logics in background I used AsyncTask.
I am getting the null pointer exception in onPostExecute method of AyncTask, I read many stackoverflow and other website solutions and created the interface and initialized it in the AsyncTask extended class constructor. But getting only nullpointer.
My Full code:
MainActivity:
public class SmsActivity extends Activity implements ParseURL.OnAsyncRequestComplete {
private static SmsActivity inst;
public static final String SMS_BUNDLE = "pdus";
public static SmsActivity instance() {
return inst;
}
#Override
public void onStart() {
super.onStart();
inst = this;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sms);
}
#Override
public void processResp(String output){
String outpu1 = output+" in main";
}
}
BroadCastReceiver:
public class SmsBroadcastReceiver extends BroadcastReceiver{
public static final String SMS_BUNDLE = "pdus";
public void onReceive(Context context, Intent intent) {
Bundle intentExtras = intent.getExtras();
if (intentExtras != null) {
Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);
String smsMessageStr = "";
boolean rechargeResult = false;
for (int i = 0; i < sms.length; ++i) {
SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);
String smsBody = smsMessage.getMessageBody().toString();
String address = smsMessage.getOriginatingAddress();
smsMessageStr += "SMS From: " + address + "\n";
if (smsBody != null) {
String[] splitValues = smsBody.split(" ");
if (splitValues != null && splitValues.length > 0) {
String siteURL = "SITE_URL";
try {
ParseURL.OnAsyncRequestComplete procesInterf = null;
ParseURL urlParse = new ParseURL(procesInterf);
Toast.makeText(context, siteURL, Toast.LENGTH_LONG).show();
new ParseURL(procesInterf).execute(new String[]{siteURL});
} catch (Exception e) {
Toast.makeText(context, "123 "+e.getMessage(), Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(context, "split values is null", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(context, "smsbody is null", Toast.LENGTH_LONG).show();
}
}
}
}
}
}
ParseURL:
public class ParseURL extends AsyncTask<String, Void, String> {
ProgressDialog progressDialog;
OnAsyncRequestComplete caller;
//Context context;
public ParseURL(OnAsyncRequestComplete a) {
caller = a;
// context = a;
}
public interface OnAsyncRequestComplete {
public void processResp(String response);
}
#Override
protected void onPreExecute()
{
progressDialog.setMessage("WAIT...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected String doInBackground(String... strings) {
String responseStatus = "";
try {
if(strings!=null) {
if (null != strings[0]) {
Document doc = Jsoup.connect(strings[0]).timeout(0).get();
if (doc != null) {
String result = doc.select("body").text();
if (null != result) {
if (result.toLowerCase().contains("FAILED".toLowerCase())) {
responseStatus = result;
} else if (result.toLowerCase().contains("SUCCESS".toLowerCase())) {
responseStatus = "SUCCESS";
} else {
responseStatus = "FAILED";
}
} else {
responseStatus = "google";
}
} else {
responseStatus = "facebook";
}
} else {
responseStatus = "youtube";
}
}else{
responseStatus = "ebay";
}
} catch (Throwable t) {
t.printStackTrace();
}
return responseStatus;
}
#Override
protected void onPostExecute(String s) {
caller.processResp(s);
}
}
I tried many solutions which is shared in the stackoverflow and other sites. But I could not solve it. Please do not mark this as duplicate.
Thanks in advance.
Ohh maaan...
ParseURL.OnAsyncRequestComplete procesInterf = null;
ParseURL urlParse = new ParseURL(procesInterf);
public ParseURL(OnAsyncRequestComplete a) {
caller = a;
}
#Override
protected void onPostExecute(String s) {
caller.processResp(s);
}
Are You see mistake?
You pass null to the ParseUrl constructor, so on PosteExecute() tries to call a method of a null callback.
I suspect that you would like to do that
ParseURL.OnAsyncRequestComplete procesInterf = SmsActivity.this;
But it will work, if your SmsBroadcastReceiver class is a inner class of SmsActivity.
You never initialize caller. Basically you set it to null, then you pass it to your AsyncTask, then you try to use it.
You already use the singleton pattern in your Activity, so you were probably after
ParseURL.OnAsyncRequestComplete procesInterf = SmsActivity.instance();
My App shows a NetworkOnMainThreadException in the Log Cat.
So I found the Asynctask Method to offload network operations to a background thread.
After adding the AsyncTask.It shows ViewRootImpl$CalledFromWrongThreadException.So i have to use onPostExecute.
I learnt the Asyntack Docs & tried.Now i got Stuck it is not Returning the correct output.I don't know whether i declared it under the respective Method's.
I want to display the processed Text in the Textview tv
So Help me in the Right Direction :)
Thanks for your Help ...
WifiApManager
public class WifiApManager {
private final WifiManager mWifiManager;
public WifiApManager(Context context) {
mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
}
public boolean setWifiApEnabled(WifiConfiguration wifiConfig, boolean enabled) {
try {
if (enabled) { // disable WiFi in any case
mWifiManager.setWifiEnabled(false);
}
Method method = mWifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, boolean.class);
return (Boolean) method.invoke(mWifiManager, wifiConfig, enabled);
} catch (Exception e) {
Log.e(this.getClass().toString(), "wifi", e);
return false;
}
}
public WIFI_AP_STATE getWifiApState() {
try {
Method method = mWifiManager.getClass().getMethod("getWifiApState");
int tmp = ((Integer)method.invoke(mWifiManager));
// Fix for Android 4
if (tmp > 10) {
tmp = tmp - 10;
}
return WIFI_AP_STATE.class.getEnumConstants()[tmp];
} catch (Exception e) {
Log.e(this.getClass().toString(), "wifi", e);
return WIFI_AP_STATE.WIFI_AP_STATE_FAILED;
}
}
public boolean isWifiApEnabled() {
return getWifiApState() == WIFI_AP_STATE.WIFI_AP_STATE_ENABLED;
}
public WifiConfiguration getWifiApConfiguration() {
try {
Method method = mWifiManager.getClass().getMethod("getWifiApConfiguration");
return (WifiConfiguration) method.invoke(mWifiManager);
} catch (Exception e) {
Log.e(this.getClass().toString(), "wifi", e);
return null;
}
}
public boolean setWifiApConfiguration(WifiConfiguration wifiConfig) {
try {
Method method = mWifiManager.getClass().getMethod("setWifiApConfiguration", WifiConfiguration.class);
return (Boolean) method.invoke(mWifiManager, wifiConfig);
} catch (Exception e) {
Log.e(this.getClass().toString(), "wifi", e);
return false;
}
}
public ArrayList<ClientScanResult> getClientList(boolean onlyReachables) {
return getClientList(onlyReachables, 10);
}
public ArrayList<ClientScanResult> getClientList(boolean onlyReachables, int reachableTimeout) {
BufferedReader br = null;
ArrayList<ClientScanResult> result = null;
try {
result = new ArrayList<ClientScanResult>();
br = new BufferedReader(new FileReader("/proc/net/arp"));
String line;
while ((line = br.readLine()) != null) {
String[] splitted = line.split(" +");
if ((splitted != null) && (splitted.length >= 4)) {
// Basic sanity check
String mac = splitted[3];
if (mac.matches("..:..:..:..:..:..")) {
boolean isReachable = InetAddress.getByName(splitted[0]).isReachable(reachableTimeout);
if (!onlyReachables || isReachable) {
result.add(new ClientScanResult(splitted[0], splitted[3], splitted[5], isReachable));
}
}
}
}
} catch (Exception e) {
Log.e(LOGTAG, e.toString());
} finally {
try {
br.close();
} catch (IOException e) {
Log.e(LOGTAG, e.toString());
}
}
return result;
}
}
connect.java
public class connect extends Activity{
WifiApManager wifiApManager;
TextView tv;
Button scan;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.connect);
tv =(TextView) findViewById(R.id.iptv);
scan myScan = new scan(this); // pass the context to the constructor
myScan.execute();
}
class scan extends AsyncTask<String, Void, Void> {
public Context context;
ArrayList<ClientScanResult> clients;
public scan(Context c) // constructor to take Context
{
context = c; // Initialize your Context variable
}
protected Void doInBackground(String... params) {
wifiApManager = new WifiApManager(context); // use the variable here
clients = wifiApManager.getClientList(false);
return null;
}
}
protected void onPostExecute(Void result){
ArrayList<ClientScanResult> clients;
tv.setText("WifiApState: " + wifiApManager.getWifiApState() + "\n\n");
tv.append("Clients: \n");
for (ClientScanResult clientScanResult : clients) //showin error in clients
{
tv.append("####################\n");
tv.append("IpAddr: " + clientScanResult.getIpAddr() + "\n");
tv.append("Device: " + clientScanResult.getDevice() + "\n");
tv.append("HWAddr: " + clientScanResult.getHWAddr() + "\n");
tv.append("isReachable: " + clientScanResult.isReachable()+ "\n");
}
}
}
Note:
It shows a error in connect.java on onPostExecute Method in Clients Variable.
in your onPostExecute(...) you have
ArrayList<ClientScanResult> **clients**;
and then
for (ClientScanResult clientScanResult : **clients**) //showin error in clients
clients is null therefore the loop is never executed. you don't need to define a new ArrayList since you already have one defined as a global variable in the scan class
A better way to do this is to set the return type of doInBackground to ArrayList< ClientScanResult> and then you have onPostExecute take an ArrayList< ClientScanResult>
class scan extends AsyncTask<Void, Void, ArrayList<ClientScanResult>> {
protected ArrayList<ClientScanResult> doInBackground(Void... params) {
wifiApManager = new WifiApManager(context); // use the variable here
return wifiApManager.getClientList(false);
}
protected void onPostExecute(ArrayList<ClientScanResult> clients){
tv.setText("WifiApState: " + wifiApManager.getWifiApState() + "\n\n");
tv.append("Clients: \n");
for (ClientScanResult clientScanResult : clients) //showin error in clients
{
tv.append("####################\n");
tv.append("IpAddr: " + clientScanResult.getIpAddr() + "\n");
tv.append("Device: " + clientScanResult.getDevice() + "\n");
tv.append("HWAddr: " + clientScanResult.getHWAddr() + "\n");
tv.append("isReachable: " + clientScanResult.isReachable()+ "\n");
}
}
This code is causing ANR force close any idea how to improve this code? i try with asynctask and i cant make it work in this code :
What i try to do here is updater activity will check for latest version and if got new version it will pop up alertdialog to ask user to update in the market
public class Updater extends Activity {
private int newVerCode = 0;
private String newVerName = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (getServerVerCode()) {
int vercode = Config.getVerCode(this);
if (newVerCode > vercode) {
doNewVersionUpdate();
} else {
notNewVersionShow();
}
}
}
//check version using json
private boolean getServerVerCode() {
try {
String verjson = NetworkTool.getContent(Config.UPDATE_SERVER
+ Config.UPDATE_VERJSON);
JSONArray array = new JSONArray(verjson);
if (array.length() > 0) {
JSONObject obj = array.getJSONObject(0);
try {
newVerCode = Integer.parseInt(obj.getString("verCode"));
newVerName = obj.getString("verName");
} catch (Exception e) {
newVerCode = -1;
newVerName = "";
return false;
}
}
} catch (Exception e) {
return false;
}
return true;
}
//Found No new version
private void notNewVersionShow() {
Updater.this.finish(); // End updater activity
}
//Found New version
private void doNewVersionUpdate() {
//Display alertdialog
}
}
You can use an AsyncTask - yes. In doInBackground you can add the code from getServerVerCode() and in onPostExecute everything in the if (getServerVerCode()).
doInBackground can return boolean so you know in onPostExecute what the result is.
Something like this:
private class GetServerVerCode extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... params) {
try {
String verjson = NetworkTool.getContent(Config.UPDATE_SERVER
+ Config.UPDATE_VERJSON);
JSONArray array = new JSONArray(verjson);
if (array.length() > 0) {
JSONObject obj = array.getJSONObject(0);
try {
newVerCode = Integer.parseInt(obj.getString("verCode"));
newVerName = obj.getString("verName");
} catch (Exception e) {
newVerCode = -1;
newVerName = "";
return false;
}
}
} catch (Exception e) {
return false;
}
return true;
}
#Override
protected void onPostExecute(Boolean result) {
if (result) {
int vercode = Config.getVerCode(this);
if (newVerCode > vercode) {
doNewVersionUpdate();
} else {
notNewVersionShow();
}
}
}
}