如何解决执行doInBackground()时发生的java.lang.RuntimeException错误?

时间:2013-04-11 10:12:56

标签: android android-service android-handler android-internet

我是android开发的初学者,我在下面的代码中遇到错误。我正在调用http请求的asyn方法,在此之前我正在检查Wifi或移动网络是否可用。当Internet连接可用时我的服务正常运行但在离线模式下我遇到这种类型的错误: “java.lang.RuntimeException:执行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)

下面是MyServiceProfile代码。在这段代码中我首先检查互联网连接,如果用户离线,数据保存在本地数据库和Internet连接期间自动更新我们的服务器

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);
    }
}

}

我的服务器Http链接代码更新如下:

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;
}

}

有时它工作正常但突然我的应用程序已经崩溃,而wifi或移动互联网连接已连接,我认为当时服务运行不正常。 :( 等待你的建议,解决方案和你的想法。 感谢名单。

2 个答案:

答案 0 :(得分:1)

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)

根据这2行,你的代码第129行有一个Null指针。

转到该行,检查正在执行的操作,找到null的对象并进行修复。 那是调试101。

答案 1 :(得分:0)

 @Override
  public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
 mTimerTask = new TimerTask() {
    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); //

}

删除服务中的handler()..您不会再次收到此错误..请在代码中进行如下更改。