I would like use JSOUP in two Activity, but in both I have same code.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button titlebutton = (Button) findViewById(R.id.button1);
titlebutton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// Execute Title AsyncTask
new AsyncTest().execute();
}
});
}
private class AsyncTest extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
Connection.Response response = null;
try {
response = Jsoup.connect("http://example.com")
.data("param1", "aaaa")
.data("param2", "bbbb")
.data("param3", "ccc")
.data("param4", "dd")
.execute();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}
and:
public class Second extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
get();
}
public Connection.Response get()
{
Connection.Response response = null;
try {
response = Jsoup.connect("http://example.com")
.data("param1", "aaaa")
.data("param2", "bbbb")
.data("param3", "ccc")
.data("param4", "dd")
.execute();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
This is only example - I use in Second Activity a lot of operation with JSOUP, so I would like have function get in this class and import it into MainActivity.
I try in MainActivity:
private class AsyncTest extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
Connection.Response response = null;
response = new Second().get();
return null;
}
}
but this return errors:
08-25 21:18:00.164: W/dalvikvm(1552): threadid=11: thread exiting with uncaught exception (group=0x409961f8)
08-25 21:18:00.174: E/AndroidRuntime(1552): FATAL EXCEPTION: AsyncTask #1
08-25 21:18:00.174: E/AndroidRuntime(1552): java.lang.RuntimeException: An error occured while executing doInBackground()
08-25 21:18:00.174: E/AndroidRuntime(1552): at android.os.AsyncTask$3.done(AsyncTask.java:278)
08-25 21:18:00.174: E/AndroidRuntime(1552): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
08-25 21:18:00.174: E/AndroidRuntime(1552): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
08-25 21:18:00.174: E/AndroidRuntime(1552): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
08-25 21:18:00.174: E/AndroidRuntime(1552): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
08-25 21:18:00.174: E/AndroidRuntime(1552): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
08-25 21:18:00.174: E/AndroidRuntime(1552): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
08-25 21:18:00.174: E/AndroidRuntime(1552): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
08-25 21:18:00.174: E/AndroidRuntime(1552): at java.lang.Thread.run(Thread.java:856)
08-25 21:18:00.174: E/AndroidRuntime(1552): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
08-25 21:18:00.174: E/AndroidRuntime(1552): at android.os.Handler.<init>(Handler.java:121)
08-25 21:18:00.174: E/AndroidRuntime(1552): at android.app.Activity.<init>(Activity.java:735)
08-25 21:18:00.174: E/AndroidRuntime(1552): at com.example.js.Second.<init>(Second.java:11)
08-25 21:18:00.174: E/AndroidRuntime(1552): at com.example.js.MainActivity$AsyncTest.doInBackground(MainActivity.java:35)
08-25 21:18:00.174: E/AndroidRuntime(1552): at com.example.js.MainActivity$AsyncTest.doInBackground(MainActivity.java:1)
08-25 21:18:00.174: E/AndroidRuntime(1552): at android.os.AsyncTask$2.call(AsyncTask.java:264)
08-25 21:18:00.174: E/AndroidRuntime(1552): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
08-25 21:18:00.174: E/AndroidRuntime(1552): ... 5 more
How is the best way to non-repeat code in my example?
Make your AsyncTask public and move it to a separate class (file):
AsyncTest.java:
public class AsyncTest extends AsyncTask<Void, Void, Void> {
...
}
Then in your activities call:
new AsyncTest().execute();
Related
I am reading the .OBJ file which is in asset folder. But I am getting exception while reading the file. Even I debug the project on eclipse but I could find the reason for this.
Please help me
Thanks in advance.
/**
* Load Object Asynchronous.
* #author Ajay
*/
private class ObjLoaderAsync extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
try {
progressDialog = new ProgressDialog(localContext);
progressDialog.setTitle(localContext
.getString(R.string.app_name));
progressDialog.setMessage(localContext
.getString(R.string.please_wait));
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(true);
progressDialog.show();
} catch (Exception e) {
}
}
#Override
protected Void doInBackground(Void... arg0) {
try {
mr[getCurrentPosition()] = new ModelRenderer(localContext,
localContext.getAssets().open(RendererView.objName));
} catch (java.io.IOException e) {
Log.v("DemoRendererView", "loading model: " + e);
}
return null;
}
#Override
protected void onPostExecute(Void param) {
try {
progressDialog.cancel();
} catch (Exception e) {
}
}
}
public ModelRenderer(Context paramContext, InputStream localFileInputStream) throws FileNotFoundException {
ModelStaticClassTransfer.value = -777.0F;
while (true) {
try {
i = localFileInputStream.read();
if (i != -1)
continue;
localFileInputStream.close();
if ((char) i == 'v') {
i = localFileInputStream.read();
if ((char) i != ' ')
continue;
this.verticeCounter = (1 + this.verticeCounter);
continue;
}
if ((char) i == 'f') {
i = localFileInputStream.read();
if ((char) i != ' ')
continue;
this.indexCounter = (1 + this.indexCounter);
continue;
}
int j = localFileInputStream.read();
i = j;
} catch (IOException localIOException) {
localIOException.printStackTrace();
return;
}
}
}
Error Trace
09-12 12:54:57.516: E/AndroidRuntime(29949): FATAL EXCEPTION: AsyncTask #2
09-12 12:54:57.516: E/AndroidRuntime(29949): java.lang.RuntimeException: An error occured while executing doInBackground()
09-12 12:54:57.516: E/AndroidRuntime(29949): at android.os.AsyncTask$3.done(AsyncTask.java:278)
09-12 12:54:57.516: E/AndroidRuntime(29949): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
09-12 12:54:57.516: E/AndroidRuntime(29949): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
09-12 12:54:57.516: E/AndroidRuntime(29949): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
09-12 12:54:57.516: E/AndroidRuntime(29949): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
09-12 12:54:57.516: E/AndroidRuntime(29949): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
09-12 12:54:57.516: E/AndroidRuntime(29949): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
09-12 12:54:57.516: E/AndroidRuntime(29949): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
09-12 12:54:57.516: E/AndroidRuntime(29949): at java.lang.Thread.run(Thread.java:856)
09-12 12:54:57.516: E/AndroidRuntime(29949): Caused by: java.lang.NullPointerException: asset
09-12 12:54:57.516: E/AndroidRuntime(29949): at android.content.res.AssetManager.readAssetChar(Native Method)
09-12 12:54:57.516: E/AndroidRuntime(29949): at android.content.res.AssetManager.access$200(AssetManager.java:35)
09-12 12:54:57.516: E/AndroidRuntime(29949): at android.content.res.AssetManager$AssetInputStream.read(AssetManager.java:548)
09-12 12:54:57.516: E/AndroidRuntime(29949): at com.amplimesh.models.ModelRenderer.<init>(ModelRenderer.java:64)
09-12 12:54:57.516: E/AndroidRuntime(29949): at com.amplimesh.models.ModelGLRenderer$ObjLoaderAsync.doInBackground(ModelGLRenderer.java:138)
09-12 12:54:57.516: E/AndroidRuntime(29949): at com.amplimesh.models.ModelGLRenderer$ObjLoaderAsync.doInBackground(ModelGLRenderer.java:1)
09-12 12:54:57.516: E/AndroidRuntime(29949): at android.os.AsyncTask$2.call(AsyncTask.java:264)
09-12 12:54:57.516: E/AndroidRuntime(29949): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
09-12 12:54:57.516: E/AndroidRuntime(29949): ... 5 more
I think you are mistaken with the meaning of the continue keyword. This keyword means that the loop jumps immediately to the next iteration without executing the rest of the code in the loop block.
In your case, it means that this code
i = localFileInputStream.read();
if (i != -1)
continue;
localFileInputStream.close();
if ((char) i == 'v') {
i = localFileInputStream.read();
closes the inputStream, and then tries to read from it. You algorithm is not very clear because of all the continues, so I can't really tell you how to fix that.
#Override
protected void onPostExecute(Void param) {
try {
mr[getCurrentPosition()] = new ModelRenderer(localContext,
localContext.getAssets().open(RendererView.objName));
dialog.cancle();
} catch (java.io.IOException e) {
Log.v("DemoRendererView", "loading model: " + e);
}
}
please check this...
you start with
try {
i = localFileInputStream.read();
if (i != -1)
continue;
localFileInputStream.close();
so, you are closing the stream and after that you are trying to read again from it. Also you are running this inside an infinite loop and exit from it only in a the catch section. Consider closing the stream after you are done reading it.
I have the following code:
public String test(){
URL url = null;
try {
url = new URL("http://api.heroesofnewerth.com/player_statistics/ranked/nickname/Hieratic/?token=0CZGH8ZI7UR8J2GN");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedReader reader = null;
String x = "";
try {
reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
x = line;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
if (reader !=null) try{reader.close();} catch (IOException ignore) {
}{}
}
JsonElement root = new JsonParser().parse(x);
return x;
}
}
now i want to insert the text into the following textView.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_competetion);
TextView tv = (TextView) findViewById(R.id.competetion_text);
JsonCollector jc = new JsonCollector();
tv.setText(jc.test());
However when i try to run it. i get the following error:
FATAL EXCEPTION: main
E/AndroidRuntime(1800): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.konkurrencesigner/com.example.konkurrencesigner.CreateCompetetion}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
E/AndroidRuntime(1800): at android.app.ActivityThread.access$600(ActivityThread.java:141)
E/AndroidRuntime(1800): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
E/AndroidRuntime(1800): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(1800): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(1800): at android.app.ActivityThread.main(ActivityThread.java:5039)
E/AndroidRuntime(1800): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(1800): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(1800): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
E/AndroidRuntime(1800): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
E/AndroidRuntime(1800): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(1800): Caused by: android.os.NetworkOnMainThreadException
E/AndroidRuntime(1800): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
E/AndroidRuntime(1800): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
E/AndroidRuntime(1800): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
E/AndroidRuntime(1800): at java.net.InetAddress.getAllByName(InetAddress.java:214)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
E/AndroidRuntime(1800): at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
E/AndroidRuntime(1800): at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316)
E/AndroidRuntime(1800): at libcore.net.http.HttpEngine.connect(HttpEngine.java:311)
E/AndroidRuntime(1800): at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
E/AndroidRuntime(1800): at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
E/AndroidRuntime(1800): at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:282)
Can anyone tell me why this is happening?
please note that i have already added the following line in my android manifest:
<uses-permission android:name="android.permission.INTERNET" />
You are doing HTTP communication on the main thread, that's why you're getting a NetworkOnMainThreadException. Do it in a separate thread, using an AsyncTask would be an ideal solution, here's an example of how you could implement it:
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_competetion);
tv = (TextView) findViewById(R.id.competetion_text);
JsonCollector jc = new JsonCollector();
// Create and execute a new AsyncTask, the TextView will
// be updated asynchronously when the task has finished.
updateTextView();
}
private void updateTextView() {
new AsyncTask<Void, Void, String>() {
#Override
/* Runs on a separate thread */
protected String doInBackground(Void... params) {
String result = null;
BufferedReader reader = null;
try {
URL url = new URL("http://api.heroesofnewerth.com/player_statistics/ranked/nickname/Hieratic/?token=0CZGH8ZI7UR8J2GN");
reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
for (String line; (line = reader.readLine()) != null;) {
System.out.println(line);
result = line;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// Ignore
}
}
}
return result;
}
#Override
/* Runs on the UI/Main thread when doInBackground()
* has finished */
protected void onPostExecute(String result) {
if(result != null) {
// Update the TextView only if we got a result
// from the HTTP request
tv.setText(result);
}
}
}.execute();
}
If you need networking in main thread add these lines of code in the onCreate() method
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
i get this error in fetching json(null values):
03-21 12:32:02.918: E/AndroidRuntime(20383): FATAL EXCEPTION: AsyncTask #2
03-21 12:32:02.918: E/AndroidRuntime(20383): java.lang.RuntimeException: An error occured while executing doInBackground()
03-21 12:32:02.918: E/AndroidRuntime(20383): at android.os.AsyncTask$3.done(AsyncTask.java:299)
03-21 12:32:02.918: E/AndroidRuntime(20383): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
03-21 12:32:02.918: E/AndroidRuntime(20383): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
03-21 12:32:02.918: E/AndroidRuntime(20383): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
03-21 12:32:02.918: E/AndroidRuntime(20383): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
03-21 12:32:02.918: E/AndroidRuntime(20383): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
03-21 12:32:02.918: E/AndroidRuntime(20383): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
03-21 12:32:02.918: E/AndroidRuntime(20383): at java.lang.Thread.run(Thread.java:856)
03-21 12:32:02.918: E/AndroidRuntime(20383): Caused by: java.lang.NullPointerException
03-21 12:32:02.918: E/AndroidRuntime(20383): at Dic.proj.pkg.notifService$check_last_asyn.doInBackground(notifService.java:253)
03-21 12:32:02.918: E/AndroidRuntime(20383): at Dic.proj.pkg.notifService$check_last_asyn.doInBackground(notifService.java:1)
03-21 12:32:02.918: E/AndroidRuntime(20383): at android.os.AsyncTask$2.call(AsyncTask.java:287)
03-21 12:32:02.918: E/AndroidRuntime(20383): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
03-21 12:32:02.918: E/AndroidRuntime(20383): ... 4 more
and this is my check_last_asyn AsynTask:
// check if notification is available asyntask
class check_last_asyn extends AsyncTask<Void, Integer, Boolean> {
#Override
protected Boolean doInBackground(Void... arg0) {
if(isOnline()){
RestClient client = new RestClient(
"http://mysite.org/api/check_last.php");
client.AddParam("last", String.valueOf(last_notif_no));
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
String response = client.getResponse();
if(!response.equals(null)){
update_response = response;
}else{
update_response= "{'update':'no'}";
}
}
return true;
}
}
i know this is because of null values but i dont know how to controll null values in this code...
This should do
if(response!=null && !(response.trim()).equals("")){
update_response = response;
}else{
update_response= "{'update':'no'}";
}
the check should be something like:
if(response != null && !response.equals(""))
I think, String responce var could be null, so just add check for null value:
String responce = client.getResponce();
if (responce == null) {
// As flag, which represents, that there is no answer from service
// Or other logic
return false;
}
// your code
you may control like
if(!TextUtils.isEmpty(response)){
try {
JSONObject jobj = new JSONObject(response);
String stolan_id = null;
Boolean bstolan_id = jobj.has("keyhere");
if(bstolan_id){
stolan_id = jobj.getString("keyhere");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
i have make one android application in that data is coming from server so it's time consuming process so i have created one progress dialog box..
below is my code
#Override
protected void onResume() {
super.onResume();
if (placesListItems != null)
placesListItems.clear();
new LoadPlaces().execute();
}
#Override
public void onPause() {
super.onPause();
if (pDialog != null)
pDialog.dismiss();
}
class LoadPlaces extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage(Html.fromHtml("<b>Search</b><br/>Loading Places..."));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... args) {
GooglePlaces googlePlaces = new GooglePlaces();
try {
double radius = 1000; // 10000 meters
// get nearest places
if (query != null) {
nearPlaces = googlePlaces.search(lat, lon, radius, query);
if (nearPlaces != null) {
for (Place p : nearPlaces.results) {
reference = p.reference;
lat = p.geometry.location.lat;
lon = p.geometry.location.lng;
break;
}
}
}
String types = "bar|restaurant|night_club|gym|health|food|shopping_mall|hospital";
if (reference != null) {
PlaceDetails placeDetails = googlePlaces.getPlaceDetails(reference);
if (placeDetails != null) {
String status = placeDetails.status;
// check place deatils status
// Check for all possible status
if (status.equals("OK")) {
if (placeDetails.result != null) {
lat = placeDetails.result.geometry.location.lat;
lon = placeDetails.result.geometry.location.lng;
nearDeals = googlePlaces.search(lat, lon, radius, types);
In below code if i press home button or screen goes of during fetching data from server (You can say progress dialog box is running) and if i come back to my application i got an error ARRAY INDEX OUT OF BOUND
// int total = ;
for (int i = nearDeals.results.size() - 1; i >= 0; i--) {
// Log.i("WHAT THE HELL",nearPlaces.results.get(i).name);
if (getResult(nearDeals.results.get(i).name, nearDeals.results.get(i).geometry.location.lat,
nearDeals.results.get(i).geometry.location.lng) == 0) {
// nearDeals.results.add(nearPlaces.results.get(i));
nearDeals.results.remove(i);
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
below is logcat
09-25 18:23:13.429: W/System.err(4375): java.lang.IndexOutOfBoundsException: Invalid index 15, size is 15
09-25 18:23:13.429: W/System.err(4375): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:257)
09-25 18:23:13.429: W/System.err(4375): at java.util.ArrayList.get(ArrayList.java:311)
09-25 18:23:13.429: W/System.err(4375): at com.eheuristics.android.diegodeals.googleplacesandmaps.MainActivity$LoadPlaces.doInBackground(MainActivity.java:204)
09-25 18:23:13.429: W/System.err(4375): at com.eheuristics.android.diegodeals.googleplacesandmaps.MainActivity$LoadPlaces.doInBackground(MainActivity.java:1)
09-25 18:23:13.429: W/System.err(4375): at android.os.AsyncTask$2.call(AsyncTask.java:185)
09-25 18:23:13.439: W/System.err(4375): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
09-25 18:23:13.439: W/System.err(4375): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
09-25 18:23:13.439: W/System.err(4375): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
09-25 18:23:13.439: W/System.err(4375): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
09-25 18:23:13.439: W/System.err(4375): at java.lang.Thread.run(Thread.java:1019)
if i do not press home key, or do not screen goes off during progress dialog box is running then everything is working fine
//After getting solution from all of you, i have done blow like all suggest but i got another error like blow
LoadPlaces ob;
protected void onResume() {
super.onResume();
if (placesListItems != null)
placesListItems.clear();
ob.execute();
}
#Override
public void onPause() {
super.onPause();
if(ob!=null)
if(ob.getStatus() == AsyncTask.Status.RUNNING){
ob.cancel(true);
}
if (pDialog != null)
pDialog.dismiss();
}
then i got error like below
09-25 18:53:30.609: E/AndroidRuntime(4674): java.lang.RuntimeException: Unable to resume activity {com.eheuristics.android.diegodeals/com.eheuristics.android.diegodeals.googleplacesandmaps.MainActivity}: java.lang.IllegalStateException: Cannot execute task: the task is already running.
09-25 18:53:30.609: E/AndroidRuntime(4674): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2241)
09-25 18:53:30.609: E/AndroidRuntime(4674): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2256)
09-25 18:53:30.609: E/AndroidRuntime(4674): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:965)
09-25 18:53:30.609: E/AndroidRuntime(4674): at android.os.Handler.dispatchMessage(Handler.java:99)
09-25 18:53:30.609: E/AndroidRuntime(4674): at android.os.Looper.loop(Looper.java:130)
09-25 18:53:30.609: E/AndroidRuntime(4674): at android.app.ActivityThread.main(ActivityThread.java:3835)
09-25 18:53:30.609: E/AndroidRuntime(4674): at java.lang.reflect.Method.invokeNative(Native Method)
09-25 18:53:30.609: E/AndroidRuntime(4674): at java.lang.reflect.Method.invoke(Method.java:507)
09-25 18:53:30.609: E/AndroidRuntime(4674): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:864)
09-25 18:53:30.609: E/AndroidRuntime(4674): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622)
09-25 18:53:30.609: E/AndroidRuntime(4674): at dalvik.system.NativeStart.main(Native Method)
09-25 18:53:30.609: E/AndroidRuntime(4674): Caused by: java.lang.IllegalStateException: Cannot execute task: the task is already running.
09-25 18:53:30.609: E/AndroidRuntime(4674): at android.os.AsyncTask.execute(AsyncTask.java:380)
09-25 18:53:30.609: E/AndroidRuntime(4674): at com.eheuristics.android.diegodeals.googleplacesandmaps.MainActivity.onResume(MainActivity.java:137)
09-25 18:53:30.609: E/AndroidRuntime(4674): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1150)
09-25 18:53:30.609: E/AndroidRuntime(4674): at android.app.Activity.performResume(Activity.java:3832)
09-25 18:53:30.609: E/AndroidRuntime(4674): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2231)
09-25 18:53:30.609: E/AndroidRuntime(4674): ... 10 more
You are starting the asynctask every time you show your activity. So, you should cancel the task when exiting (AsyncTask.cancel(true)), or check if it is still running in the onResume method.
In the cases where you get the error onResume() gets called again, starting a new AsyncTask. Now you have multiple AsyncTask simultanously accessing and altering the size of nearDeals.results (you call remove on it). When one asyncTask removes an item from the list, the second asyncTask may run into the ArrayIndexOutOfBounds since the list size has changed.
EDIT: It's actually not the removal of an item, but that you set a new instance of the list in googlePlaces.search and this list may have a different size than the one used by the old asynctask.
Solution: call cancel on your running async tasks in onPause (or in onResume before starting
the new task)
What I'm doing exactly is this:
I have a class "Welcome" that calls another class "textWriter" which contains a method "write". Welcome passes two strings to "write", "name" is the name of the text file to write to and "something" is the thing to print.
i keep getting null pointer error on prt = new PrintStream(output);
here is the logcat
07-22 16:40:22.561: ERROR/AndroidRuntime(2245): FATAL EXCEPTION: main
07-22 16:40:22.561: ERROR/AndroidRuntime(2245): java.lang.NullPointerException
07-22 16:40:22.561: ERROR/AndroidRuntime(2245): at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:158)
07-22 16:40:22.561: ERROR/AndroidRuntime(2245): at com.rhobot.budget.textWriter.write(textWriter.java:24)
07-22 16:40:22.561: ERROR/AndroidRuntime(2245): at com.rhobot.budget.Welcome.setSubChoices(Welcome.java:37)
07-22 16:40:22.561: ERROR/AndroidRuntime(2245): at com.rhobot.budget.Welcome$1.onClick(Welcome.java:76)
07-22 16:40:22.561: ERROR/AndroidRuntime(2245): at android.view.View.performClick(View.java:2408)
07-22 16:40:22.561: ERROR/AndroidRuntime(2245): at android.view.View$PerformClick.run(View.java:8816)
07-22 16:40:22.561: ERROR/AndroidRuntime(2245): at android.os.Handler.handleCallback(Handler.java:587)
07-22 16:40:22.561: ERROR/AndroidRuntime(2245): at android.os.Handler.dispatchMessage(Handler.java:92)
07-22 16:40:22.561: ERROR/AndroidRuntime(2245): at android.os.Looper.loop(Looper.java:123)
07-22 16:40:22.561: ERROR/AndroidRuntime(2245): at android.app.ActivityThread.main(ActivityThread.java:4627)
07-22 16:40:22.561: ERROR/AndroidRuntime(2245): at java.lang.reflect.Method.invokeNative(Native Method)
07-22 16:40:22.561: ERROR/AndroidRuntime(2245): at java.lang.reflect.Method.invoke(Method.java:521)
07-22 16:40:22.561: ERROR/AndroidRuntime(2245): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
07-22 16:40:22.561: ERROR/AndroidRuntime(2245): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
07-22 16:40:22.561: ERROR/AndroidRuntime(2245): at dalvik.system.NativeStart.main(Native Method)
here is the Welcome class:
public class Welcome extends Activity
{
P p = new P(); //shared prefs helper
loadArray la = new loadArray(); //array loader
textWriter tw = new textWriter();
private EditText txtBalance;
private Button btnEnter;
int subItemCount, addItemCount;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.welcomescreen);
capture();
}
public static String sub_choice_key = "sub_choice_key.txt";
public static String sub_compare = "sub_compare.txt";
public static String add_choice_key = "add_choice_key.txt";
public static String add_compare = "add_compare.txt";
public void setSubChoices() throws FileNotFoundException {
// TODO create a master list of choices
tw.write(sub_choice_key,"-1");
tw.write(sub_choice_key,"-2");
tw.write(sub_choice_key,"-3");
tw.write(sub_compare,"-1");
tw.write(sub_compare,"-2");
tw.write(sub_compare,"-3");
p.pisI("subItemCount", 3, this);
}...
Here is the textWriter class
public class textWriter extends Activity{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
public void write(String name, String something) {
try {
FileOutputStream output;
output = openFileOutput(name,MODE_APPEND);
PrintStream prt;
prt = new PrintStream(output);
prt.println(something);
prt.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
id like to emphasize that these are two different files as well, and i am importing all the right stuff i believe.. also i have the line
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
in my android manifest.
what am i doing wrong? is it context? or lack there of? if so how should i implement it?
i am doing it this way because i want to use this textWrite in other programs as an easy (less messy) way of writing data. in my main it could save me about 50 lines of code if i do it this way.
Thanks in advance-
Tricknology
As probablykevin said, the issue is a lack of a valid Context.
One simple fix you could do if you want your class structure to stay the same is to remove the extends Activity from textWriter and instead pass in a Context in the constructor, i.e.:
public class textWriter{
private Context m_context;
public textWriter(Context ctx) {
m_context = ctx;
}
public void write(String name, String something) {
try {
FileOutputStream output;
output = m_context.openFileOutput(name,MODE_APPEND);
PrintStream prt;
prt = new PrintStream(output);
prt.println(something);
prt.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You'd then need to construct it like so: textWriter tw = new textWriter(this);
Instead of creating a new Activity, place the write method in your original activity that you are calling it from.
The problem arises when textWriter calls openOutputStream() but has not been created yet. So yes, I would say it is a problem of Context because the context calling openOutputStream() has not been created yet.