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)
Related
I got error when I tried to upload all of the images. I use for to loop the process, but still got error in looping. if i don't use for, it still can upload the image but only 1 image that will be uploaded. how can I solve this?
UploadActivity.java
Intent intent = getIntent();
filePath = intent.getStringExtra("filePath");
ArrayList<String> flpath = new ArrayList<String>();
SharedPreferences prefs = getSharedPreferences("SavedFilePathsJSONArray",
Context.MODE_PRIVATE);
String myJSONArrayString = prefs.getString("SavedFilePathsJSONArray",
"");
if (!myJSONArrayString.isEmpty()) {
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(myJSONArrayString);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < jsonArray.length(); i++) {
try {
flpath.add(jsonArray.get(i).toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
flpath.add(filePath);
JSONArray mJSONArray = new JSONArray(flpath);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("SavedFilePathsJSONArray", mJSONArray.toString()).commit();
for (int i = 0; i < flpath.size(); i++) {
imgFile = new File(flpath.get(i));
if (imgFile.exists()) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath(),options);
ImageView myImage = new ImageView(this);
myImage.setMaxHeight(100);
myImage.setMaxWidth(100);
myImage.setImageBitmap(myBitmap);
layout2.addView(myImage);
}
}
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
#Override
protected void onPreExecute() {
// setting progress bar to zero
progressBar.setProgress(0);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
progressBar.setVisibility(View.VISIBLE);
// updating progress bar value
progressBar.setProgress(progress[0]);
// updating percentage value
txtPercentage.setText(String.valueOf(progress[0]) + "%");
}
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
String responseString = null;
for (int i = 0; i < flPath.size(); i++) {
File file = new File( flPath.get(i));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
// Adding file data to http body
entity.addPart("image", new FileBody(file));
// Extra parameters if you want to pass to server
entity.addPart("website",
new StringBody("www.androidhive.info"));
entity.addPart("email", new StringBody("abc#gmail.com"));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
}
return responseString;
}
Config.Java
public class Config {
public static final String FILE_UPLOAD_URL = "http://....";
// Directory name to store captured images and videos
public static final String IMAGE_DIRECTORY_NAME = "andrd_upload";
}
error logcat
01-27 16:23:45.940: W/dalvikvm(15986): threadid=12: thread exiting with uncaught exception (group=0x40fe7438)
01-27 16:23:45.950: E/AndroidRuntime(15986): FATAL EXCEPTION: AsyncTask #1
01-27 16:23:45.950: E/AndroidRuntime(15986): java.lang.RuntimeException: An error occured while executing doInBackground()
01-27 16:23:45.950: E/AndroidRuntime(15986): at android.os.AsyncTask$3.done(AsyncTask.java:299)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-27 16:23:45.950: E/AndroidRuntime(15986): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.lang.Thread.run(Thread.java:856)
01-27 16:23:45.950: E/AndroidRuntime(15986): Caused by: java.lang.NullPointerException
01-27 16:23:45.950: E/AndroidRuntime(15986): at com.camerafileupload.UploadActivity$UploadFileToServer.uploadFile(UploadActivity.java:228)
01-27 16:23:45.950: E/AndroidRuntime(15986): at com.camerafileupload.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:221)
01-27 16:23:45.950: E/AndroidRuntime(15986): at com.camerafileupload.UploadActivity$UploadFileToServer.doInBackground(UploadActivity.java:1)
01-27 16:23:45.950: E/AndroidRuntime(15986): at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-27 16:23:45.950: E/AndroidRuntime(15986): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-27 16:23:45.950: E/AndroidRuntime(15986): ... 5 more
01-27 16:23:46.130: D/HardwareRenderer(15986): draw surface is valid dirty= null
01-27 16:23:46.180: D/HardwareRenderer(15986): draw surface is valid dirty= null
01-27 16:23:46.220: D/HardwareRenderer(15986): draw surface is valid dirty= null
01-27 16:25:29.910: D/dalvikvm(15986): WAIT_FOR_CONCURRENT_GC blocked 0ms
01-27 16:25:29.950: D/dalvikvm(15986): GC_EXPLICIT freed 223K, 8% free 15337K/16583K, paused 2ms+4ms, total 38ms
ScreenShoot
Edit: i put the error logcat and the screenshoot of the error page (UploadActivity.java).
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();
I know this is quite a common question, but I have searched around and my attempts to solve the below issue have been unsuccessful.
In particular, below are the messages that I am receiving from logcat.
08-03 17:55:53.885: E/AndroidRuntime(1286): FATAL EXCEPTION: main
08-03 17:55:53.885: E/AndroidRuntime(1286): Process: com.dooba.beta, PID: 1286
08-03 17:55:53.885: E/AndroidRuntime(1286): java.lang.RuntimeException: Unable to resume activity {com.dooba.beta/com.dooba.beta.MatchingActivity}: java.lang.NullPointerException
08-03 17:55:53.885: E/AndroidRuntime(1286): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2788)
08-03 17:55:53.885: E/AndroidRuntime(1286): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2817)
08-03 17:55:53.885: E/AndroidRuntime(1286): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250)
08-03 17:55:53.885: E/AndroidRuntime(1286): at android.app.ActivityThread.access$800(ActivityThread.java:135)
08-03 17:55:53.885: E/AndroidRuntime(1286): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
08-03 17:55:53.885: E/AndroidRuntime(1286): at android.os.Handler.dispatchMessage(Handler.java:102)
08-03 17:55:53.885: E/AndroidRuntime(1286): at android.os.Looper.loop(Looper.java:136)
08-03 17:55:53.885: E/AndroidRuntime(1286): at android.app.ActivityThread.main(ActivityThread.java:5017)
08-03 17:55:53.885: E/AndroidRuntime(1286): at java.lang.reflect.Method.invokeNative(Native Method)
08-03 17:55:53.885: E/AndroidRuntime(1286): at java.lang.reflect.Method.invoke(Method.java:515)
08-03 17:55:53.885: E/AndroidRuntime(1286): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-03 17:55:53.885: E/AndroidRuntime(1286): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-03 17:55:53.885: E/AndroidRuntime(1286): at dalvik.system.NativeStart.main(Native Method)
08-03 17:55:53.885: E/AndroidRuntime(1286): Caused by: java.lang.NullPointerException
08-03 17:55:53.885: E/AndroidRuntime(1286): at com.dooba.beta.MatchingActivity.onResume(MatchingActivity.java:82)
08-03 17:55:53.885: E/AndroidRuntime(1286): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1192)
08-03 17:55:53.885: E/AndroidRuntime(1286): at android.app.Activity.performResume(Activity.java:5310)
08-03 17:55:53.885: E/AndroidRuntime(1286): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2778)
08-03 17:55:53.885: E/AndroidRuntime(1286): ... 12 more
Below is the code for the activity
public class MatchingActivity extends Activity {
protected ParseRelation<ParseUser> mFriendsRelation;
protected ParseUser mCurrentUser;
protected List<ParseUser> mUsers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.matching);
// Show the Up button in the action bar.
}
#Override
protected void onResume() {
super.onResume();
mCurrentUser = ParseUser.getCurrentUser();
setProgressBarIndeterminateVisibility(true);
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> users, ParseException e) {
if (e == null) {
mUsers = users;
} else {
// Something went wrong.
}
}
});
//This give you a list of users. Then to access one user you need to know the index the user is at.
ParseUser user = mUsers.get(5);
//then you can access that user's information
user.getString("name");
user.getNumber("age");
user.getString("headline");
}
}
Below is the code for the xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
Any assistance would be greatly appreciated.
Thanks in advance.
Updated code:
Error received
for the line
mUsers = new List<ParseUser>();
I receive the following messages:
"Cannot instantiate the type List<ParseUser>"
for the lines
user.getString("name");
user.getNumber("age");
user.getString("headline");
I receive the following error:
"user cannot be resolved"
Thanks in advance, and below is the complete updated code.
public class MatchingActivity extends Activity {
protected ParseRelation<ParseUser> mFriendsRelation;
protected ParseUser mCurrentUser;
protected List<ParseUser> mUsers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.matching);
// Show the Up button in the action bar.
//create list variable
mUsers = new List<ParseUser>();
}
#Override
protected void onResume() {
super.onResume();
mCurrentUser = ParseUser.getCurrentUser();
setProgressBarIndeterminateVisibility(true);
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> users, ParseException e) {
if (e == null) {
//add all the users to your list variable
mUsers.addAll(users);
} else {
// Something went wrong.
}
}
});
//check the size of your list to see how big it is before accessing it
final int size = mUsers.size();
//or use a loop to loop through each one
for(ParseUser mParseUser : mUsers) {
//skip over the current user
if(mParseUser == ParseUser.getCurrentUser())
continue;
user.getString("name");
user.getNumber("age");
user.getString("headline");
}
}
}
I think your problem is in the following line of code
ParseUser user = mUsers.get(5);
mUsers.get(5) is probably null, or doesn't exist. There is nothing in your code which guarantees that the list has to be at least size 5.
Try this instead
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.matching);
//create list variable
mUsers = new List<ParseUser>();
}
#Override
protected void onResume() {
...
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.findInBackground(new FindCallback<ParseUser>()
{
public void done(List<ParseUser> users, ParseException e)
{
if (e == null)
{
//add all the users to your list variable
mUsers.addAll(users);
//check the size of your list to see how big it is before accessing it
final int size = mUsers.size();
//or use a loop to loop through each one
for(ParseUser mParseUser : mUsers)
{
//skip over the current user
if(mParseUser == ParseUser.getCurrentUser())
continue;
//use the correct type when getting
final String mName = user.getString("name");
final int mNumber = user.getNumber("age");
final String mHeadLine = user.getString("headline");
}
}
else
{
// Something went wrong.
}
}
});
}
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 am currently working on the new Google Maps Android API v2.
My MapActivity class is working with my Samsung galaxy s3 ans s2 with the code below:
However, there are some particular devices are not working such as: GT-S5830i
class MapActivity extends FragmentActivity implements OnMapClickListener, OnMapLongClickListener, OnMarkerClickListener
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
tvLocInfo = (TextView)findViewById(R.id.locinfo);
android.support.v4.app.FragmentManager myFragmentManager = getSupportFragmentManager();
SupportMapFragment myMapFragment = (SupportMapFragment)myFragmentManager.findFragmentById(R.id.map);
myMap = myMapFragment.getMap();
myMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
ArrayList<Cooridnates> cooridnatesList = MainActivity.getList();
for(int i=0;i<cooridnatesList.size();i++)
{
//Toast.makeText(MapActivity.this, "SIZE : " + " " + cooridnatesList.size(), Toast.LENGTH_LONG).show();
LatLng point = new LatLng(cooridnatesList.get(i).getLat(),cooridnatesList.get(i).getLon());
tvLocInfo.setText("markers added");
myMap.addMarker(new MarkerOptions().position(point).title(point.toString()));
center=CameraUpdateFactory.newLatLng(point);
}
CameraUpdate zoom=CameraUpdateFactory.zoomTo(16);
myMap.moveCamera(center);
myMap.animateCamera(zoom);
myMap.setOnMapClickListener(this);
myMap.setOnMarkerClickListener(this);
markerClicked = false;
}
For some reason, I am getting this error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.coldice.plotfinder/com.coldice.plotfinder.MapActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
at android.app.ActivityThread.access$1500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3687)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.google.android.gms.maps.GoogleMap.moveCamera(Unknown Source)
at com.coldice.plotfinder.MapActivity.onCreate(MapActivity.java:70)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
... 11 more
You function MainActivity.getList() probably returned an empty list, so for loop doesn't execute center=CameraUpdateFactory.newLatLng(point);.
it seems center is null in this >> myMap.moveCamera(center);, make an appropriate check on this variable before passing it in moveCamera method.
It seems problem is here. center might have null value, So to get proper explanation debug your application.
center is initialzed here.
center=CameraUpdateFactory.newLatLng(point);
It might assign null in center.
myMap.moveCamera(center); <<<PROBLEM is here
if(center != null )
myMap.moveCamera(center);