Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a problem with AsyncTask in android. I have a NullPointerException at this line

  ConnectivityManager conMgr = (ConnectivityManager)  
  context.getSystemService(Context.CONNECTIVITY_SERVICE);

in this method

public static boolean checkRete(Context context) {
    ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo infos[] = conMgr.getAllNetworkInfo();
    for (NetworkInfo info : infos) {
        if (info.getState() == State.CONNECTED)
            return true;
    }
    return false;
}

This error causes a Runtime Exception while executing doInBackground() part of AsyncTask class.

protected ArrayList<ObjDb> doInBackground(Void... params) {
    return Functions.query(act, "http://www.unishare.it/tutored/" + url);
}

This is the entire log of error:

04-06 18:06:40.082  25316-25365/it.polimi.mobilecourse.expenses E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #3
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:278)
            at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
            at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
            at java.util.concurrent.FutureTask.run(FutureTask.java:137)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
            at java.lang.Thread.run(Thread.java:864)
     Caused by: java.lang.NullPointerException
            at it.polimi.mobilecourse.expenses.Functions.checkRete(Functions.java:36)
            at it.polimi.mobilecourse.expenses.Functions.query(Functions.java:27)
            at it.polimi.mobilecourse.expenses.RequestFtp.doInBackground(RequestFtp.java:33)
            at it.polimi.mobilecourse.expenses.RequestFtp.doInBackground(RequestFtp.java:14)
            at android.os.AsyncTask$2.call(AsyncTask.java:264)
            at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
????????????at java.util.concurrent.FutureTask.run(FutureTask.java:137)
????????????at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
????????????at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
????????????at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
????????????at java.lang.Thread.run(Thread.java:864)

and these are other methods. The method checkRete() is called by:

 static ArrayList<ObjDb> query(Context context, String url) {
    System.out.println(url);
    if(!checkRete(context)) {
        System.out.println("Problema rete");
        return null;
    }

that is called by doInBackground(). I have already set the permission in Manifest for WiFi and 3g connection. Why I found this error? Please,help me!

Edit: context comes from this:

         new RequestFtp().setParameters(activity, url, "controlloFB", LandingFragment.this).execute();

where setParameters sets context to activity that is a simple Activity.

Edit 2:

   public class RequestFtp extends AsyncTask<Void,ArrayList<ObjDb>,ArrayList<ObjDb>> {

private String url;
private Fragment fragment;
private String op;
private HelpActivity act;

public RequestFtp setParameters(HelpActivity activity, String url,String op, Fragment fragment) {
    this.url = url;
    this.op=op;
    this.act=activity;
    this.fragment = fragment;
    return this;
}


/** The system calls this to perform work in a worker thread and
 * delivers it the parameters given to AsyncTask.execute() */
protected ArrayList<ObjDb> doInBackground(Void... params) {
    return Functions.query(act, "http://www.unishare.it/tutored/" + url);
}
/** The system calls this to perform work in the UI thread and delivers
 * the result from doInBackground() */
protected void onPostExecute(ArrayList<ObjDb> result) {
    if(result == null) {
        Toast.makeText(act.getApplicationContext(),R.string.error_connection,Toast.LENGTH_SHORT).show();
        return;
    }
    act.handleResult(result,op,fragment);

}

}

Fragment:

        public class LandingFragment extends Fragment {

private View view;
private LandingActivity activity;
private String str;


int id;
String nome;

@Override
public void onCreate(Bundle savedInstanceState) {


    super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    view = inflater.inflate(R.layout.landing_fragment, container, false);
    buttonsActions();

    return view;
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);


    this.activity = (LandingActivity) activity;
}

public void buttonsActions() {

    Button butS = (Button) view.findViewById(R.id.buttonStudente);
    butS.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent myintent = new Intent(v.getContext(), LoginStudente.class);
            startActivity(myintent);

        }
    });

    Button butT = (Button) view.findViewById(R.id.buttonTutor);
    butT.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent myintent = new Intent(v.getContext(), LoginTutor.class);
            startActivity(myintent);

        }
    });


}

private void buttonsSActions() {

    Button butS = (Button) view.findViewById(R.id.buttonStudente);
    butS.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent myintent = new Intent(v.getContext(), DataActivityStudent.class);
            Bundle mBundle = new Bundle();
            mBundle.putString("Nome", nome);
            mBundle.putInt("Id", id);
            myintent.putExtras(mBundle);
            startActivity(myintent);

        }
    });

    Button butT = (Button) view.findViewById(R.id.buttonTutor);
    butT.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent myintent = new Intent(v.getContext(), LoginTutor.class);
            startActivity(myintent);

        }
    });
    try {
        ((manageListener) activity).manageButton();
    }
    catch(ClassCastException cce){

    }


}

private void buttonsTActions() {

    Button butS = (Button) view.findViewById(R.id.buttonStudente);
    butS.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent myintent = new Intent(v.getContext(), LoginStudente.class);
            startActivity(myintent);

        }
    });

    Button butT = (Button) view.findViewById(R.id.buttonTutor);
    butT.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent myintent = new Intent(v.getContext(), DataActivityTutor.class);
            startActivity(myintent);

        }
    });
    try {
        ((manageListener) activity).manageButton();
    }
    catch(ClassCastException cce){

    }


}


public void ftpControl(String url) {

    new RequestFtp().setParameters(activity, url, "controlloFB", LandingFragment.this).execute();
}


private void setNomeWelcome(String nome) {
    WelcomeFragment wf = activity.getWf();
    wf.setText(nome);
}


public void control(ArrayList<ObjDb> result) {

    ObjDb res = result.get(0);
    String response = res.get("Response");
    //System.out.println("Response "+response);
    if (response.compareTo("S") == 0) {

        str = "S";
        String id_utente = res.get("id_utente");
        nome = res.get("nome");
        //System.out.println("nome "+nome);
        id = Integer.parseInt(id_utente);
        buttonsSActions();


    }
    if (response.compareTo("T") == 0) {

        str = "T";
        String id_utente = res.get("id_utente");
        nome = res.get("nome");
        id = Integer.parseInt(id_utente);
        buttonsTActions();


    }
    if (nome.compareTo("") != 0) {
        setNomeWelcome(nome);
    }


}


public interface manageListener{

    public void manageButton();
}

}

Activity:

       public class LandingActivity extends HelpActivity implements LandingFragment.manageListener {


private LandingFragment lf;
private WelcomeFragment wf;
private ProgressBar progressView;


private UiLifecycleHelper uiHelper;
private Session.StatusCallback callback;

String nome;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setLanding();
    progress(true);
    showWelcome();
    manageSession(savedInstanceState);




}

private void manageSession(Bundle savedInstanceState){

    callback=new Session.StatusCallback(){
        @Override
        public void call(final Session session,final SessionState state,final Exception exception){



            onSessionStateChange(session, state, exception);






        }
    };
    uiHelper = new UiLifecycleHelper(this,callback);
    uiHelper.onCreate(savedInstanceState);
    Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
    Session session=Session.getActiveSession();
    if(session.getPermissions().isEmpty()){
        System.out.println("logged false");

        FragmentManager fragMan = getFragmentManager();
        FragmentTransaction fragTrans=fragMan.beginTransaction();
        fragTrans.replace(R.id.fragreplace,lf).commit();
        progress(false);

    }


}

private void setLanding(){
    setContentView(R.layout.landing_activity);

    progressView=(ProgressBar)findViewById(R.id.progressBarRS);
    lf=new LandingFragment();

    wf=new WelcomeFragment();
}

@Override
public void onActivityResult(int requestCode,int resultCode,Intent data){
    super.onActivityResult(requestCode,resultCode,data);
    uiHelper.onActivityResult(requestCode,resultCode,data);
}

@Override
public void handleResult(ArrayList<ObjDb> result,String op,Fragment fragment){


    if(result==null){
        progress(false);
    }

    if(op=="controlloFB"){
        LandingFragment lfr=(LandingFragment) fragment;
        lfr.control(result);
    }


}

private void onSessionStateChange(Session session, SessionState state, Exception exception) {



    if(session==null || session.isClosed()){
        Log.i("LandingActivity", "session nulla...");



    }


    if(session!=null && session.isOpened()){

        Log.i("LandingActivity", "session not null...");



        System.out.println(session.getPermissions());

        new Request(session,"me",null, HttpMethod.GET,new Request.Callback(){
            public void onCompleted(Response response){
                String us=null;
                try {
                us=response.getGraphObject().getProperty("email").toString();
                nome=response.getGraphObject()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
125 views
Welcome To Ask or Share your Answers For Others

1 Answer

The problem is with the Context object. It's null.

In android the context is very important to know which page is being considered to refresh with the corresponding changes.

When you call this method:

checkRete(Context context)

make sure that context is not null.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...