1

我是 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 连接,然后如果用户离线,则数据保存在本地数据库中并在 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或移动互联网连接时突然我的应用程序崩溃了,我认为当时服务没有正常运行。:( 等待您的建议、解决方案和您的想法。谢谢。

4

2 回答 2

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)

根据这两行,您在代码的第 129 行有一个 Null 指针。

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

于 2013-04-11T10:21:25.163 回答
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() ..您将不会再次收到此错误..请在您的代码中进行如下更改。

于 2013-04-11T10:43:04.583 回答