0

尝试登录时,我的 AsyncTask 代码返回 null。我很困惑,为什么在设备上它可以抛出吐司“return null ...”但在模拟器上它强制关闭,任何人请帮我解决这个问题。非常感谢您

登录.java

public class Login extends Activity {
    public Koneksi linkurl;
    String SERVER_URL;
    private Button login, register, setting;
    private EditText username, password;
    public ProgressDialog progressDialog;


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        setting = (Button)findViewById(R.id.bsetting);
        login = (Button) findViewById(R.id.login);
        register = (Button) findViewById(R.id.reg);
        username = (EditText) findViewById(R.id.uname);
        password = (EditText) findViewById(R.id.pass);

        setting.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intentSet = new Intent(Login.this, UrlSetting.class);
                startActivity(intentSet);
            }
        });

        register.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intentReg = new Intent(Login.this, Register.class);
                startActivity(intentReg);
            }
        });

        login.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

                // TODO Auto-generated method stub

               new LoginTask().execute();



            }
        });


    }
    protected String tryLogin(String mUsername, String mPassword)
    {           
      Log.d(" TryLoginCheck ","Here");
        HttpURLConnection connection;
       OutputStreamWriter request = null;

            URL url = null;
            String response = null;   
            String temp=null;
            String parameters = "username="+mUsername+"&password="+mPassword;   
            System.out.println("UserName"+mUsername+"\n"+"password"+mPassword);
            Log.d("Parameters",parameters);
            try
            {
                ;
                linkurl = new Koneksi(this);
                SERVER_URL = linkurl.getUrl();
                SERVER_URL += "/mobile/Login.php";
                url = new URL(SERVER_URL);
                connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                connection.setRequestMethod("POST");    

                request = new OutputStreamWriter(connection.getOutputStream());
                request.write(parameters);
                request.flush();
                request.close();            
                String line = "";               
                InputStreamReader isr = new InputStreamReader(connection.getInputStream());
                BufferedReader reader = new BufferedReader(isr);
                StringBuilder sb = new StringBuilder();
                while ((line = reader.readLine()) != null)
                {

                    sb.append(line + "\n");
                }
                temp=sb.toString();
                Log.d("Temp",temp);

                response = sb.toString();
                Log.d("Response",response);
               Log.d("Sb Value",sb.toString());
                isr.close();
                reader.close();


            }
            catch(IOException e)
            {
                e.printStackTrace();
                Log.d("Error",e.getMessage());
                return null;
            }

            return response;
    }

    public class LoginTask extends AsyncTask<String, String, String> {

        String response = null;

        @Override
        protected void onPreExecute()
        {

        }
        @Override
        protected String doInBackground(String... arg0)
        {
            String mUsername = username.getText().toString();
               String mPassword = password.getText().toString();          
               return tryLogin(mUsername, mPassword);
        }
      protected void onPostExecute(String result){
          super.onPostExecute(result);
          if(result==null)
          {
              Toast.makeText(Login.this,"result is null- an error occured",Toast.LENGTH_SHORT).show();
            } 
          else{

              result = result.trim();
         Log.d("Check","Here");
            Log.d("Response",response);
         if(response.toLowerCase().contains("berhasil"))
                {
                    String nama = username.getText().toString();
                    Intent newIntent = new Intent(Login.this, MainPage.class);

                    Bundle bundle = new Bundle();

                    bundle.putString("nama", nama);

                    newIntent.putExtras(bundle);
                    startActivityForResult(newIntent, 0);
                }
                else
                {
                    //Optional
                    //Kalau bisa dibuat constant untuk menghindari salah penulisan
                    String RoleError = "ROLE SALAH";
                    String UserError = "USER SALAH";

                    createDialog("Maaf", response.equals(RoleError) ? "Role Anda bukan Student!" : "Username Atau Password Salah!");
                }
          }
      }
    }
    private void createDialog(String title, String text) {
        AlertDialog ad = new AlertDialog.Builder(this)
        .setPositiveButton("Ok", null)
        .setTitle(title)
        .setMessage(text)
        .create();
        ad.show();
    }
}

Logcat - 当我在设备中测试时

06-10 17:34:43.715: D/TextLayoutCache(13251): Using debug level: 0 - Debug Enabled: 0
06-10 17:34:43.786: D/libEGL(13251): loaded /vendor/lib/egl/libEGL_POWERVR_SGX540_120.so
06-10 17:34:43.793: D/libEGL(13251): loaded /vendor/lib/egl/libGLESv1_CM_POWERVR_SGX540_120.so
06-10 17:34:43.801: D/libEGL(13251): loaded /vendor/lib/egl/libGLESv2_POWERVR_SGX540_120.so
06-10 17:34:43.918: D/OpenGLRenderer(13251): Enabling debug mode 0
06-10 17:34:45.090: D/TryLoginCheck(13251): Here
06-10 17:34:45.098: I/System.out(13251): UserName
06-10 17:34:45.098: I/System.out(13251): password
06-10 17:34:45.098: D/Parameters(13251): username=&password=

logcat-wen 我在模拟器上测试

06-10 17:37:34.375: I/Process(451): Sending signal. PID: 451 SIG: 9
06-10 17:43:06.032: W/KeyCharacterMap(488): No keyboard for id 0
06-10 17:43:06.032: W/KeyCharacterMap(488): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
06-10 17:43:19.961: D/TryLoginCheck(488): Here
06-10 17:43:19.963: I/System.out(488): UserNametes
06-10 17:43:19.963: I/System.out(488): passwordTes12345*
06-10 17:43:19.963: D/Parameters(488): username=tes&password=Tes12345*
06-10 17:43:20.343: D/Temp(488): Login Berhasil dengan userid='3'
06-10 17:43:20.343: D/Response(488): Login Berhasil dengan userid='3'
06-10 17:43:20.343: D/Sb Value(488): Login Berhasil dengan userid='3'
06-10 17:43:20.343: D/Check(488): Here
06-10 17:43:20.343: D/AndroidRuntime(488): Shutting down VM
06-10 17:43:20.343: W/dalvikvm(488): threadid=1: thread exiting with uncaught exception (group=0x40015560)
06-10 17:43:20.363: E/AndroidRuntime(488): FATAL EXCEPTION: main
06-10 17:43:20.363: E/AndroidRuntime(488): java.lang.NullPointerException: println needs a message
06-10 17:43:20.363: E/AndroidRuntime(488):  at android.util.Log.println_native(Native Method)
06-10 17:43:20.363: E/AndroidRuntime(488):  at android.util.Log.d(Log.java:137)
06-10 17:43:20.363: E/AndroidRuntime(488):  at com.karismaelearning.Login$LoginTask.onPostExecute(Login.java:163)
06-10 17:43:20.363: E/AndroidRuntime(488):  at com.karismaelearning.Login$LoginTask.onPostExecute(Login.java:1)
06-10 17:43:20.363: E/AndroidRuntime(488):  at android.os.AsyncTask.finish(AsyncTask.java:417)
06-10 17:43:20.363: E/AndroidRuntime(488):  at android.os.AsyncTask.access$300(AsyncTask.java:127)
06-10 17:43:20.363: E/AndroidRuntime(488):  at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
06-10 17:43:20.363: E/AndroidRuntime(488):  at android.os.Handler.dispatchMessage(Handler.java:99)
06-10 17:43:20.363: E/AndroidRuntime(488):  at android.os.Looper.loop(Looper.java:123)
06-10 17:43:20.363: E/AndroidRuntime(488):  at android.app.ActivityThread.main(ActivityThread.java:3683)
06-10 17:43:20.363: E/AndroidRuntime(488):  at java.lang.reflect.Method.invokeNative(Native Method)
06-10 17:43:20.363: E/AndroidRuntime(488):  at java.lang.reflect.Method.invoke(Method.java:507)
06-10 17:43:20.363: E/AndroidRuntime(488):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
06-10 17:43:20.363: E/AndroidRuntime(488):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
06-10 17:43:20.363: E/AndroidRuntime(488):  at dalvik.system.NativeStart.main(Native Method)
4

2 回答 2

2

您将“响应”与“结果”混淆了。在 onPostExecute(String result) 中,“结果”是您在 doInBackground() 中异步执行的结果。LoginTask 的响应成员变量从未使用过,我根本不明白您为什么想要它。删除它并使用“结果”。

于 2013-06-10T10:55:23.860 回答
0
Log.d("Response",response); response is null. 

在 tryLogin 中,如果出现异常,您将返回 NULL。尝试将其更改为某个值并再次测试。

catch(IOException e)
{
     e.printStackTrace();
      Log.d("Error",e.getMessage());
      return null;
 }
于 2013-06-10T10:49:58.677 回答