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();
}
}
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).
My async function is this:
class ProfileCategoryCall extends AsyncTask<String, String, String>{
public ProfileCategoryCall() {
// TODO Auto-generated constructor stub
}
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}
#Override
protected void onPostExecute(String result) {
JSONObject HomeCardString = new JSONObject();
JSONObject ABC = new JSONObject();
try {
responseString = result;
joiningYear = new JSONObject(responseString);
HomeCardString = joiningYear.getJSONObject("CategoryLikesResult");
ABC = HomeCardString.getJSONObject("CategoryLikesResult");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Gson gson = new Gson();
try
{
((ProfileActivity)getActivity()).interestResult = gson.fromJson(ABC.toString(), LikeCategorySummaryResult.class);
}
catch(Exception e)
{
Log.i("myyyy", e.getMessage());
e.printStackTrace();
}
} catch (Throwable t) {
Log.e("My App", "Could not parse malformed JSON: \"" + responseString + "\"" + t.getMessage());
}
PopulateData();
progress.setVisibility(View.GONE);
super.onPostExecute(result);
//Do anything with response..
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progress.setVisibility(View.VISIBLE);
super.onPreExecute();
}
}
While Calling async service call this error occurs.
08-28 11:15:38.140: E/AndroidRuntime(14310): FATAL EXCEPTION: AsyncTask #1
08-28 11:15:38.140: E/AndroidRuntime(14310): java.lang.RuntimeException: An error occured while executing doInBackground()
08-28 11:15:38.140: E/AndroidRuntime(14310): at android.os.AsyncTask$3.done(AsyncTask.java:278)
08-28 11:15:38.140: E/AndroidRuntime(14310): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
08-28 11:15:38.140: E/AndroidRuntime(14310): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
08-28 11:15:38.140: E/AndroidRuntime(14310): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
08-28 11:15:38.140: E/AndroidRuntime(14310): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
08-28 11:15:38.140: E/AndroidRuntime(14310): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
08-28 11:15:38.140: E/AndroidRuntime(14310): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
08-28 11:15:38.140: E/AndroidRuntime(14310): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
08-28 11:15:38.140: E/AndroidRuntime(14310): at java.lang.Thread.run(Thread.java:856)
08-28 11:15:38.140: E/AndroidRuntime(14310): Caused by: java.lang.IllegalArgumentException: Illegal character in query at index 355: http://example.net/Service.svc/android/Profile/1361769105/Like/EXAMPLE?category=Public
08-28 11:15:38.140: E/AndroidRuntime(14310): at java.net.URI.create(URI.java:727)
08-28 11:15:38.140: E/AndroidRuntime(14310): at org.apache.http.client.methods.HttpGet.<init>(HttpGet.java:75)
08-28 11:15:38.140: E/AndroidRuntime(14310): at com.stalker.androidapp.InterestTabFragment$ProfileCategoryCall.doInBackground(InterestTabFragment.java:308)
08-28 11:15:38.140: E/AndroidRuntime(14310): at com.stalker.androidapp.InterestTabFragment$ProfileCategoryCall.doInBackground(InterestTabFragment.java:1)
08-28 11:15:38.140: E/AndroidRuntime(14310): at android.os.AsyncTask$2.call(AsyncTask.java:264)
08-28 11:15:38.140: E/AndroidRuntime(14310): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
08-28 11:15:38.140: E/AndroidRuntime(14310): ... 5 more
I have seen other similar questions, but answers were to remove code which is using UI from doInBackground() and I don't think I have any unnecessary code in it. So please tell me if I am wrong.
I'm getting an error in following code, calling asyn method for http request. It gives me a java.lang.RuntimeException error inside doInBackground() method.
_____________MAIN class____________
TextView testoInput = (TextView) findViewById(R.id.input);
final String località = testoInput.getText().toString();
bottone1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
TaskAsincrono nuovo = new TaskAsincrono();
nuovo.execute(località);
}
__________ASYNC Class________
public class TaskAsincrono extends AsyncTask > {
protected ArrayList<String> doInBackground(String...params) {
String s = params[0];
ArrayList<String> risultato =null;
//Inizio sessione di invio dati rest con sistema GET
DefaultHttpClient client = new DefaultHttpClient();
String url ="http://www.replycoupon.it/php/rest_Server/index.php?nome="+s;
try {
URI uri = new URI(url);
HttpGet get = new HttpGet(uri);
HttpResponse res = client.execute(get);
InputStream data = res.getEntity().getContent();
//Inizio l'operazione di buffering per la lettura
BufferedReader streamReader = new BufferedReader(new InputStreamReader(data));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr =null;
while ((inputStr = streamReader.readLine()) != null)
responseStrBuilder.append(inputStr);
JSONObject jObj = new JSONObject(responseStrBuilder.toString());
String clima = jObj.getString("clima");
String temperatura = jObj.getString("temperatura");
//Prima di inviare alla main metto il risultato in un arrylist
risultato.add(clima);
risultato.add(temperatura);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return risultato;
}
protected void onPostExecute(final ArrayList<String> risultato) {
final TextView testoClima = (TextView) findViewById(R.id.Output);
final TextView testoTemp = (TextView) findViewById(R.id.Output2);
testoClima.setText(risultato.get(0).toString());
testoTemp.setText(risultato.get(1).toString());
}
}
LOG
10-02 20:53:07.068: D/dalvikvm(4050): GC_FOR_ALLOC freed 234K, 4% free 7914K/8188K, paused 16ms, total 16ms
10-02 20:53:09.728: W/dalvikvm(4050): threadid=11: thread exiting with uncaught exception (group=0x41800ba8)
10-02 20:53:09.728: E/AndroidRuntime(4050): FATAL EXCEPTION: AsyncTask #1
10-02 20:53:09.728: E/AndroidRuntime(4050): Process: luca.tirocinio.client_json, PID: 4050
10-02 20:53:09.728: E/AndroidRuntime(4050): java.lang.RuntimeException: An error occured while executing doInBackground()
10-02 20:53:09.728: E/AndroidRuntime(4050): at android.os.AsyncTask$3.done(AsyncTask.java:300)
10-02 20:53:09.728: E/AndroidRuntime(4050): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
10-02 20:53:09.728: E/AndroidRuntime(4050): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
10-02 20:53:09.728: E/AndroidRuntime(4050): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
10-02 20:53:09.728: E/AndroidRuntime(4050): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
10-02 20:53:09.728: E/AndroidRuntime(4050): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
10-02 20:53:09.728: E/AndroidRuntime(4050): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
10-02 20:53:09.728: E/AndroidRuntime(4050): at java.lang.Thread.run(Thread.java:841)
10-02 20:53:09.728: E/AndroidRuntime(4050): Caused by: java.lang.NullPointerException
10-02 20:53:09.728: E/AndroidRuntime(4050): at luca.tirocinio.client_json.MainActivity$TaskAsincrono.doInBackground(MainActivity.java:117)
10-02 20:53:09.728: E/AndroidRuntime(4050): at luca.tirocinio.client_json.MainActivity$TaskAsincrono.doInBackground(MainActivity.java:1)
10-02 20:53:09.728: E/AndroidRuntime(4050): at android.os.AsyncTask$2.call(AsyncTask.java:288)
10-02 20:53:09.728: E/AndroidRuntime(4050): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
10-02 20:53:09.728: E/AndroidRuntime(4050): ... 4 more
10-02 20:53:13.768: I/Process(4050): Sending signal. PID: 4050 SIG: 9
You're trying to add results to ArrayList<String> risultato which is null. Just replace it with ArrayList<String> risultato = new ArrayList<String>();
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 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.