使用asynctask执行注销时的Android问题

时间:2013-10-05 17:41:44

标签: java android eclipse android-asynctask logout

我是新来的。一周前我开始使用Java和Android进行编程,我有使用PHP的经验,但这个Java对我来说是新的。

到目前为止,我已经完成了登录,创建共享偏好和使用导航抽屉的应用程序。

现在我正试图在没有运气的情况下实现用户注销。

我在这里发布代码,希望你能帮助我。从昨晚开始,它让我疯狂:

public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;

//private CharSequence mDrawerTitle;

// private CharSequence mTitle;     private String [] mPlanetTitles;

public static String usuarioID;
public static String dispositivo;

public static SessionManager session;
ConnectionDetector cd;
static Httppostaux post;
static String URL_connect="http://www.myserver.net/api/logout.php";
TextView dispo;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);

   // mTitle = mDrawerTitle = getTitle();
    mPlanetTitles = getResources().getStringArray(R.array.planets_array);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.left_drawer);
    cd = new ConnectionDetector(getApplicationContext());
    session = new SessionManager(getApplicationContext());
    session.checkLogin();

    dispo=(TextView)findViewById(R.id.dispositivo);

     HashMap<String, String> usuario = session.getUserDetails();

        usuarioID = usuario.get(SessionManager.KEY_USER_ID);

    // set a custom shadow that overlays the main content when the drawer opens
    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
    // set up the drawer's list view with items and click listener
    mDrawerList.setAdapter(new ArrayAdapter<String>(this,
            R.layout.drawer_list_item, mPlanetTitles));
    mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

    // enable ActionBar app icon to behave as action to toggle nav drawer
   // getActionBar().setDisplayHomeAsUpEnabled(true);
   // getActionBar().setHomeButtonEnabled(true);

    // ActionBarDrawerToggle ties together the the proper interactions
    // between the sliding drawer and the action bar app icon
    mDrawerToggle = new ActionBarDrawerToggle(
            this,                  /* host Activity */
            mDrawerLayout,         /* DrawerLayout object */
            R.drawable.ic_drawer,  /* nav drawer image to replace 'Up' caret */
            R.string.drawer_open,  /* "open drawer" description for accessibility */
            R.string.drawer_close  /* "close drawer" description for accessibility */
            ) {
        public void onDrawerClosed(View view) {
            //getActionBar().setTitle(mTitle);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }

        public void onDrawerOpened(View drawerView) {
            //getActionBar().setTitle(mDrawerTitle);
            invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    if (savedInstanceState == null) {
        selectItem(0);
    }
}



@Override
public void onBackPressed() {
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    startActivity(intent);
} 

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);
    return super.onCreateOptionsMenu(menu);
}

/* Called whenever we call invalidateOptionsMenu() */


@Override
public boolean onOptionsItemSelected(MenuItem item) {
     // The action bar home/up action should open or close the drawer.
     // ActionBarDrawerToggle will take care of this.
    if (mDrawerToggle.onOptionsItemSelected(item)) {
        return true;
    }
    // Handle action buttons

    switch(item.getItemId()) {

    default:
        return super.onOptionsItemSelected(item);
    }

}

/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        selectItem(position);
    }
}

private void selectItem(int position) {
    // update the main content by replacing fragments
    Fragment fragment = new PlanetFragment();
    Bundle args = new Bundle();
    args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
    fragment.setArguments(args);

    FragmentManager fragmentManager = getFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

    // update selected item and title, then close the drawer
    mDrawerList.setItemChecked(position, true);
    setTitle(mPlanetTitles[position]);
    mDrawerLayout.closeDrawer(mDrawerList);
}

@Override
public void setTitle(CharSequence title) {
    //mTitle = title;
    //getActionBar().setTitle(mTitle);
}

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);

    mDrawerToggle.syncState();
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    mDrawerToggle.onConfigurationChanged(newConfig);
}
public static class PlanetFragment extends Fragment {
    public static final String ARG_PLANET_NUMBER = "planet_number";

    public PlanetFragment() {
        // Empty constructor required for fragment subclasses
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
        int i = getArguments().getInt(ARG_PLANET_NUMBER);
        String secciones = getResources().getStringArray(R.array.planets_array)[i];
        if (i == 6){
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setMessage("Esta acción cerrará su sesión y lo desconectará de nuestro sistema.")
                   .setCancelable(false)
                   .setPositiveButton("Si", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int id) {
                           new asynclogout().execute(usuarioID); 

                       }
                   })
                   .setNegativeButton("No", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                       }
                   });
            AlertDialog alert = builder.create();
            alert.show();
        }
        return rootView;
    } 

    public boolean loginstatus(String usuarioID ) {
        String logstatus="0";


        ArrayList<NameValuePair> postparameters2send= new ArrayList<NameValuePair>();

                    postparameters2send.add(new BasicNameValuePair("usuario",usuarioID));

           //realizamos una peticion y como respuesta obtenes un array JSON
            JSONArray jdata=post.getserverdata(postparameters2send, URL_connect);

                if (jdata!=null && jdata.length() > 0){

                    JSONObject json_data; //creamos un objeto JSON
                    try {
                        json_data = jdata.getJSONObject(0); //leemos el primer segmento en nuestro caso el unico
                         logstatus=json_data.getString("logstatus");
                         Log.e("loginstatus","logstatus= "+logstatus);//muestro por log que obtuvimos
                    } catch (JSONException e) {

                        e.printStackTrace();
                    }                   

                    //validamos el valor obtenido
                     if (logstatus=="0"){// [{"logstatus":"0"}] 
                         Log.e("loginstatus ", "invalido");
                         return false;
                     }else
                     {
                         Log.e("loginstatus", "valido");
                         return true;
                     }

              }else{    
                         Log.e("JSON  ", "ERROR");
                        return false;
              }

    }


    //validamos si no hay ningun campo en blanco
    public boolean checklogindata(String username ,String password ){

    if  (username.equals("") || password.equals("")){
        Log.e("Login ui", "checklogindata user or pass error");
    return false;

    }else{

        return true;
    }

}           

    class asynclogout extends AsyncTask< String, String, String > {

        String usuarioID;

        protected String doInBackground(String... params) {
            //obtnemos usr y pass
            usuarioID=params[0];
            //enviamos y recibimos y analizamos los datos en segundo plano.
            if (loginstatus(usuarioID)==true){                      
                return "ok"; //login valido
            }else{          
                return "err"; //login invalido                    
            }

        }



        protected void onPostExecute(String result) {

           Log.e("onPostExecute=",""+result);

           if (result.equals("ok")){
               session.logoutUser();
            }

                                                    }

        }

}

}

问题是当我尝试注销用户时,logcat给了我这个错误:

10-05 13:09:36.060: E/AndroidRuntime(756): FATAL EXCEPTION: AsyncTask #1
10-05 13:09:36.060: E/AndroidRuntime(756): java.lang.RuntimeException: An error occured while executing doInBackground()
10-05 13:09:36.060: E/AndroidRuntime(756):  at android.os.AsyncTask$3.done(AsyncTask.java:299)
10-05 13:09:36.060: E/AndroidRuntime(756):  at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
10-05 13:09:36.060: E/AndroidRuntime(756):  at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
10-05 13:09:36.060: E/AndroidRuntime(756):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
10-05 13:09:36.060: E/AndroidRuntime(756):  at java.util.concurrent.FutureTask.run(FutureTask.java:137)
10-05 13:09:36.060: E/AndroidRuntime(756):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
10-05 13:09:36.060: E/AndroidRuntime(756):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
10-05 13:09:36.060: E/AndroidRuntime(756):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
10-05 13:09:36.060: E/AndroidRuntime(756):  at java.lang.Thread.run(Thread.java:856)
10-05 13:09:36.060: E/AndroidRuntime(756): Caused by: java.lang.NullPointerException
10-05 13:09:36.060: E/AndroidRuntime(756):  at com.gettford.community.MainActivity$PlanetFragment.loginstatus(MainActivity.java:252)
10-05 13:09:36.060: E/AndroidRuntime(756):  at com.gettford.community.MainActivity$PlanetFragment$asynclogout.doInBackground(MainActivity.java:322)
10-05 13:09:36.060: E/AndroidRuntime(756):  at com.gettford.community.MainActivity$PlanetFragment$asynclogout.doInBackground(MainActivity.java:1)
10-05 13:09:36.060: E/AndroidRuntime(756):  at android.os.AsyncTask$2.call(AsyncTask.java:287)
10-05 13:09:36.060: E/AndroidRuntime(756):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
10-05 13:09:36.060: E/AndroidRuntime(756):  ... 5 more

然后应用程序崩溃。

1 个答案:

答案 0 :(得分:0)

您尚未初始化post。因此,你得到NullPointerException。初始化post

  post=  new Httppostaux();