I am beginner in android development, I am getting error in following code. I am calling asyn method for http request, before that I am checking Wifi or Mobile Network is available or not. When Internet connection is available My Service is running fine but when in off line mode I ma getting this type of error: " java.lang.RuntimeException: An error occured while executing doInBackground()"
04-09 19:44:33.057: E/AndroidRuntime(3127): FATAL EXCEPTION: AsyncTask #1
04-09 19:44:33.057: E/AndroidRuntime(3127): java.lang.RuntimeException: An error occured while executing doInBackground()
04-09 19:44:33.057: E/AndroidRuntime(3127): at android.os.AsyncTask$3.done(AsyncTask.java:278)
04-09 19:44:33.057: E/AndroidRuntime(3127): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
04-09 19:44:33.057: E/AndroidRuntime(3127): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
04-09 19:44:33.057: E/AndroidRuntime(3127): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
04-09 19:44:33.057: E/AndroidRuntime(3127): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
04-09 19:44:33.057: E/AndroidRuntime(3127): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
04-09 19:44:33.057: E/AndroidRuntime(3127): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
04-09 19:44:33.057: E/AndroidRuntime(3127): at java.lang.Thread.run(Thread.java:856)
04-09 19:44:33.057: E/AndroidRuntime(3127): Caused by: java.lang.NullPointerException
04-09 19:44:33.057: E/AndroidRuntime(3127): at com.zoomi_zdc.SERVICES.MyServiceProf$myPostData.doInBackground(MyServiceProf.java:129)
04-09 19:44:33.057: E/AndroidRuntime(3127): at com.zoomi_zdc.SERVICES.MyServiceProf$myPostData.doInBackground(MyServiceProf.java:1)
04-09 19:44:33.057: E/AndroidRuntime(3127): at android.os.AsyncTask$2.call(AsyncTask.java:264)
04-09 19:44:33.057: E/AndroidRuntime(3127): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
Below is MyServiceProfile code. In this code first I am checking Internet connectivity and aftr tht If User is offline, data saved in local database and during Internet Connection automatically Update on our server
public class MyServiceProf extends Service {
Timer t = new Timer();
public TimerTask mTimerTask;
private ConnectivityManager connectivityManager;
final Handler handler = new Handler();
private int nCounter = 0;
Context context = this;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public void onCreate() {
}
@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
mTimerTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
nCounter++;
connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isAvailable()) {
mTimerTask.cancel();
try{
new myPostData().execute();
}catch (Exception e) {
// TODO: handle exception
}
} else if (mobile.isAvailable()) {
mTimerTask.cancel();
try{
new myPostData().execute();
}catch (Exception e) {
// TODO: handle exception
}
} else {
// Toast.makeText(getBaseContext(),"You are trying to access online content but Internet Connection has been disconnected!!!",Toast.LENGTH_SHORT).show();
}
}
});
Log.d("TIMER", "TimerTask run");
}
};
// public void schedule (TimerTask task, long delay, long period)
t.schedule(mTimerTask, 0, 10000); //
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
try {
t.cancel();
handler.removeCallbacks(mTimerTask);
} catch (Exception e) {
// TODO: handle exception
}
// Toast.makeText(getApplicationContext(), " Stopped", Toast.LENGTH_SHORT).show();
}
public class myPostData extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
HttpProfilePost proupdate = new HttpProfilePost();
String mMyprofileImagename[] = DatabaseHalper.mStudentImgNm.get(0).split("/");
File sdcardPathofprofileimg = new File(Environment.getExternalStorageDirectory()+"/data/.System/MProfile/" +mMyprofileImagename[1]);
Bitmap mBitmapimageofMyProfilepic = BitmapFactory.decodeFile(sdcardPathofprofileimg.getAbsolutePath());
DatabaseHalper dbhelper = new DatabaseHalper(getBaseContext());
dbhelper.Get_ZoomiProfile_Data();
proupdate.HttpClient_Profile_Post(context,DatabaseHalper.mStudentRollNo.get(0),
DatabaseHalper.mStudentName.get(0),
DatabaseHalper.mStudentAddress.get(0),
DatabaseHalper.mStudentEmrg_Person.get(0),
DatabaseHalper.mStudentEmrg_No.get(0),
DatabaseHalper.mStudentEmail.get(0),
DatabaseHalper.mStudentBloodGrp.get(0),
DatabaseHalper.mStudentMobileno.get(0),
mBitmapimageofMyProfilepic);
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
}
My Update on server Http link code is below:
public class HttpProfilePost {
private JSONObject jsonResponse;
private Bitmap myPic;
private ByteArrayOutputStream bos;
private byte[] data;
/*private ByteArrayBody bab;
private MultipartEntity reqEntity;*/
private InputStream is;
private SharedPreferences mPref;
private SharedPreferences.Editor mEditor;
private Context mContext;
private HttpResponse httpResp;
List<String> a;
private String image1,image2,image3,image4,image5,image6,image7,image8,image9,image10;
//private String WEBSERVICE_NAME = "Profile_post.aspx";
public JSONObject HttpClient_Profile_Post(Context c,String stud_rollno, String stud_name,String stud_address, String stud_emrgperson, String stud_emrgcontact, String stud_email, String stud_bloodgrp, String stud_mobileno, Bitmap myPhoto){
mContext=c;
mPref = PreferenceManager.getDefaultSharedPreferences(mContext);
HttpClient httpClient = new DefaultHttpClient();
String mStudentUserid= mPref.getString("Userid", "" );
String myImage[] = DatabaseHalper.mStudentImgNm.get(0).split("/");
String profileimagepath = myImage[0];
stud_name = URLEncoder.encode(stud_name);
stud_address = URLEncoder.encode(stud_address);
stud_emrgperson = URLEncoder.encode(stud_emrgperson);
stud_emrgcontact = URLEncoder.encode(stud_emrgcontact);
stud_email = URLEncoder.encode(stud_email);
stud_bloodgrp = URLEncoder.encode(stud_bloodgrp);
// HttpPost mURL = new HttpPost("http://10.160.0.18:86/Service.svc/testpersondatapost?uid="+mStudentUserid+"&stdname="+stud_name+"&stdmail="+stud_email+"&Add="+stud_address+"&Qual=xyz&Qual_add=abc&pro_expert=abc&achieve=abc&Cont_no="+stud_mobileno+"&othr1=abc&othr2=abc&othr3=abc&proimgpath="+profileimagepath+"&UT=Student&Emer_ContPer="+stud_emrgperson+"&Emer_Cont_no="+stud_emrgcontact+"&Bld_Grp="+stud_bloodgrp+"&Addi_Notes"+;
String mURL = "http://webservice.zoomi.in/Service.svc/testpersondatapost?uid="+mStudentUserid+"&stdname="+stud_name+"&stdmail="+stud_email+"&Add="+stud_address+"&Qual=xyz&Qual_add=abc&pro_expert=abc&achieve=abc&Cont_no="+stud_mobileno+"&othr1=abc&othr2=abc&othr3=abc&proimgpath="+profileimagepath+"&UT=Student&Emer_ContPer="+stud_emrgperson+"&Emer_Cont_no="+stud_emrgcontact+"&Bld_Grp="+stud_bloodgrp+"&Addi_Notes=abc";
// String mURL = "http://webservice.zoomi.in/Service.svc/testpersondatapost?uid="+mStudentUserid+"&stdname="+stud_name+"&stdmail="+stud_email+"&Add="+stud_address+"&Qual=xyz&Qual_add=abc&pro_expert=abc&achieve=abc&Cont_no="+stud_mobileno+"&othr1=abc&othr2=abc&othr3=abc&proimgpath="+profileimagepath+"&UT=Student&Emer_ContPer="+stud_emrgperson+"&Emer_Cont_no="+stud_emrgcontact+"&Bld_Grp="+stud_bloodgrp+"";
// String mURL = "http://10.160.0.18:86/Service.svc/testpersondatapost?uid="+mStudentUserid+"&stdname="+stud_name+"&stdmail="+stud_email+"&Add="+stud_address+"&Qual=xyz&Qual_add=abc&pro_expert=abc&achieve=abc&Cont_no="+stud_mobileno+"&othr1=abc&othr2=abc&othr3=abc&proimgpath="+profileimagepath+"&UT=Student&Emer_ContPer="+stud_emrgperson+"&Emer_Cont_no="+stud_emrgcontact+"&Bld_Grp="+stud_bloodgrp+"";
HttpPost postrequest = new HttpPost(mURL);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody fileBody = new FileBody(new File(Environment.getExternalStorageDirectory()+"/data/.System/MProfile/", myImage[1]));// ,"application/octet-stream");
reqEntity.addPart("fileContents", fileBody);
try {
postrequest.setEntity(reqEntity);
// Execute the request "POST"
httpResp = httpClient.execute(postrequest);
/*HttpResponse response = null;*/
// Check the status code, in this case "created"
//Log.v("App", "Created");
int code = httpResp.getStatusLine().getStatusCode();
System.out.println("Response Code : "+code);
/*if (((HttpResponse) response).getStatusLine().getStatusCode() == HttpStatus.SC_CREATED)
{
}*/
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
int responcecode = httpResp.getStatusLine().getStatusCode();
if(responcecode==200)
{
Intent stopserviceintnet = new Intent(mContext,MyServiceProf.class);
mContext.stopService(stopserviceintnet);
System.out.print("Your service is stopped...");
try{
MyclassFragment.mbtn_SaveMyProfile.setEnabled(true);
}
catch (Exception e) {
// TODO: handle exception
}
try{
QuickaccessFragment.mbtn_SaveMyProfile.setEnabled(true);
}
catch (Exception e) {
// TODO: handle exception
}
}else
{
System.out.print("Your service is running...");
}
System.out.println(jsonResponse);
return jsonResponse;
}
}
Sometimes It works properly but suddenly my apps has been Crashed while wifi or Mobile Internet connection is connected, I think at that time service did not run properly. :( Waiting for your suggestion, solution and your ideas. Thanx.
04-09 19:44:33.057: E/AndroidRuntime(3127): Caused by: java.lang.NullPointerException
04-09 19:44:33.057: E/AndroidRuntime(3127): at com.zoomi_zdc.SERVICES.MyServiceProf$myPostData.doInBackground(MyServiceProf.java:129)
according to those 2 lines you have a Null pointer at line 129 of your code.
Go to that line, check what is being done, find the object that is null and fix it. That's debugging 101.