【问题标题】:Moving to a new activity based upon response from web service根据来自 Web 服务的响应移动到新活动
【发布时间】:2011-10-28 13:32:18
【问题描述】:

我正在实现一个代码,该代码基于来自 Web 服务的特定响应调用我项目中的下一个活动。我面临一些与导致 NullPointerException 相同的问题

这是我的 Android 代码:

           package com.example;
           import java.net.SocketException;
           import org.ksoap2.SoapEnvelope;
           import org.ksoap2.serialization.SoapObject;
           import org.ksoap2.serialization.SoapPrimitive;
           import org.ksoap2.serialization.SoapSerializationEnvelope;
           import org.ksoap2.transport.HttpTransportSE;
           import android.app.Activity; 
           import android.app.ProgressDialog;
           import android.content.Intent;
           import android.os.AsyncTask;
           import android.os.Bundle;
           import android.util.Log;
           import android.view.View; 
           import android.view.View.OnClickListener;
           import android.widget.Button;
           import android.widget.EditText;

     public class TeacherLogin2Activity extends Activity
        {
    private final String NAMESPACE = "http://tempuri.org/";
    private final String URL = "http://10.0.2.2/loginteacher/Service1.asmx";

    String t_id;
    String password;
    String ahead;
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            Button signin = (Button) findViewById(R.id.regsubmitbtn);

            signin.setOnClickListener(new OnClickListener() {
                    public void onClick(View v) {


                            EditText etxt_user = (EditText) findViewById(R.id.usereditlog);
                            t_id = etxt_user.getText().toString();
                            EditText etxt_password = (EditText) findViewById(R.id.pwdeditlog);
                            password = etxt_password.getText().toString();


                            new LoginTask().execute();

                    }
            });   
    }

    private String doLogin(String t_id, String password) {

       String res=null;
       final String SOAP_ACTION = "http://tempuri.org/GetLogin";
       final String METHOD_NAME = "GetLogin";     
       SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

       request.addProperty("teacherid", t_id);
       request.addProperty("password",password);
       SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
       envelope.dotNet = true; // Set this variable to true for
                                                               // compatibility with what seems to be the
                                                               // default encoding for .Net-Services.
       envelope.setOutputSoapObject(request);

       System.out.println(request);

       HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);


       try {
              androidHttpTransport.call(SOAP_ACTION, envelope);
              SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
              Log.i("myApp", response.toString());
              System.out.println("response" +response);
              res=response.toString(); 
              System.out.println(res);


         }catch(SocketException ex)
          {
           Log.e("Error : " , "Error on soapPrimitiveData() " + ex.getMessage());
           ex.printStackTrace();
       }
       catch (Exception e) {
           Log.e("Error : " , "Error on soapPrimitiveData() " + e.getMessage());
               e.printStackTrace();
       }

       return res;

       }


        private class LoginTask extends AsyncTask<Void, String, String> {

        private final ProgressDialog dialog = new ProgressDialog(
                TeacherLogin2Activity.this);

        protected void onPreExecute() {

                this.dialog.setMessage("Logging in...");
                this.dialog.show();

        }


        protected String doInBackground(final Void... unused) {

            String auth=doLogin(t_id,password);
            System.out.println(auth);

            return null; // don't interact with the ui!
        }


        protected void onPostExecute(String result) 
        {

                  ahead=result;
                if(result.equals("Welcome to this activity")){
                   Intent showContent = new Intent(getApplicationContext(),newscreen.class);
                    startActivity(showContent);
                }
                if (this.dialog.isShowing()) {
                this.dialog.dismiss();
                                             }
          }

        }

         } 

更新的 Logcat 也显示了运行时异常:

                10-28 19:40:00.099: ERROR/AndroidRuntime(1001): FATAL EXCEPTION: main
               10-28 19:40:00.099: ERROR/AndroidRuntime(1001): java.lang.RuntimeException:  Unable to start activity ComponentInfo{com.example/com.example.newscreen}: java.lang.NullPointerException
               10-28 19:40:00.099: ERROR/AndroidRuntime(1001):     at  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
               10-28 19:40:00.099: ERROR/AndroidRuntime(1001):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
               10-28 19:40:00.099: ERROR/AndroidRuntime(1001):     at android.app.ActivityThread.access$2300(ActivityThread.java:125)
               10-28 19:40:00.099: ERROR/AndroidRuntime(1001):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
               10-28 19:40:00.099: ERROR/AndroidRuntime(1001):     at android.os.Handler.dispatchMessage(Handler.java:99)
               10-28 19:40:00.099: ERROR/AndroidRuntime(1001):     at android.os.Looper.loop(Looper.java:123)
               10-28 19:40:00.099: ERROR/AndroidRuntime(1001):     at android.app.ActivityThread.main(ActivityThread.java:4627)
               10-28 19:40:00.099: ERROR/AndroidRuntime(1001):     at java.lang.reflect.Method.invokeNative(Native Method)
               10-28 19:40:00.099: ERROR/AndroidRuntime(1001):     at java.lang.reflect.Method.invoke(Method.java:521)
               10-28 19:40:00.099: ERROR/AndroidRuntime(1001):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
               10-28 19:40:00.099: ERROR/AndroidRuntime(1001):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
               10-28 19:40:00.099: ERROR/AndroidRuntime(1001):     at dalvik.system.NativeStart.main(Native Method)
               10-28 19:40:00.099: ERROR/AndroidRuntime(1001): Caused by: java.lang.NullPointerException
               10-28 19:40:00.099: ERROR/AndroidRuntime(1001):     at com.example.newscreen.onCreate(newscreen.java:25)
               10-28 19:40:00.099: ERROR/AndroidRuntime(1001):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
               10-28 19:40:00.099: ERROR/AndroidRuntime(1001):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
               10-28 19:40:00.099: ERROR/AndroidRuntime(1001):     ... 11 more

我已将所有必需的 Internet 权限放入我的 AndroidManifest.xml 文件中。有人可以帮助解决我的问题吗?

【问题讨论】:

  • @Venky: 这一行 --> if(result.equals("Welcome to this activity"))
  • 在 Log 中打印结果.. 结果为 Null,因此它抛出空指针
  • 将执行后的结果存储在字符串变量中,然后如果结果等于“欢迎来到此活动”,然后导航到其他页面,它可以工作
  • @Venky:结果是正确的..在我在 if(result.equals(...) ) 行之前写了 System.out.println(result) 之后,它给了我“欢迎参加这个活动”
  • @Raghav:我可以在最初的 if 块之后在 onPostExecute 中写这个吗:String next= result; if(next.equals("Welcome to this activity")) { \\do something}

标签: android web-services android-asynctask android-ksoap2 android-activity


【解决方案1】:

resultNull 的形式出现,因此它正在抛出 Null Pointer Exception ,尝试打印结果并使用 Log 检查即将发生的情况。

将结果存储在全局变量中并在 Asyn 任务中访问它。

例如:将变量声明为String final_result before of Activity,并将结果存储为final_result=result

然后比较final_result.equalsIgnoreCase("BLA BLA BLA");

public class Articles extends Activity {
     String res=null;
     @Override
    protected void onCreate(Bundle savedInstanceState) {
       // TODO Auto-generated method stub
       super.onCreate(savedInstanceState);
       setContentView(R.layout.articles_list);
       new LoginTask().execute(t_id,password);
     }
   }

public class Articles_Asyn_Task extends AsyncTask<String, Void, Void> { 
    // can use UI thread here
    protected void onPreExecute() {
        progress_dialog_async_task = ProgressDialog.show(getParent(), "Loading...","Please wait...");
    }
    @Override
    protected Void doInBackground(String... params) {
    String t_id,password;
    try{
        t_id=params[0];
        password=params[1];
    }catch(Exception e){}

    final String SOAP_ACTION = "http://tempuri.org/GetLogin";
   final String METHOD_NAME = "GetLogin";     
   SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

   request.addProperty("teacherid", t_id);
   request.addProperty("password",password);
   SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
   envelope.dotNet = true; // Set this variable to true for
                                                           // compatibility with what seems to be the
                                                           // default encoding for .Net-Services.
   envelope.setOutputSoapObject(request);

   System.out.println(request);

   HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
   try {
          androidHttpTransport.call(SOAP_ACTION, envelope);
          SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
          Log.i("myApp", response.toString());
          System.out.println("response" +response);
          res=response.toString(); 
          System.out.println(res);


     }catch(SocketException ex)
      {
       Log.e("Error : " , "Error on soapPrimitiveData() " + ex.getMessage());
       ex.printStackTrace();
   }
   catch (Exception e) {
       Log.e("Error : " , "Error on soapPrimitiveData() " + e.getMessage());
           e.printStackTrace();
   }
        return null;
    }   
    protected void onPostExecute(Void result) {
        if(res.equalsIgnoreCase("BLA BLA BLA")){
        startActivity(new Intent(Main.this,Main_1.class));
        }

        if (progress_dialog_async_task.isShowing()) {
            progress_dialog_async_task.dismiss();
        }
    }
}

【讨论】:

  • 你做了那个改变,我应该在 doInBackground 方法中做什么......我应该这样写:protected String doInBackground(final Void...unused) { String auth=doLogin(t_id,password) ; System.out.println(auth);返回授权; // 不要与 ui 交互! }
  • 你说字符串 final_result 应该在导入之后声明为 TeacherLogin2Activity 之外的外部活动,对吗?所以我需要这样写: String final_result;在活动之前..我说得对吗?
  • 我必须在 Android Manifest 中添加: 对吗?
  • 你的代码:protected void onPostExecute(Void result) { if(res.equalsIgnoreCase("BLA BLA BLA")){ startActivity(new Intent(Main.this,Main_1.class));在这为什么无效的结果?在我的情况下,Main.this 和 Main_1 是什么?
  • @Parth_90 和你做的一样 new Intent(getApplicationContext(),newscreen.class)
【解决方案2】:

问题在于doInBackground的返回值,即null。 在onPostExecute中,调用null的equals方法...

protected String doInBackground(final Void... unused) {

    String auth=doLogin(t_id,password);
    System.out.println(auth);

    return null; //it is passed as argument to onPostExecute
}

protected void onPostExecute(String result) {
    (...)
    if(result.equals("Welcome to this activity")){ // crashes
        // null.equals(...) ...
        Intent showContent = new Intent(getApplicationContext(),newscreen.class);
        startActivity(showContent);
    }
    (...)
}

以这种方式编辑您的代码:

protected String doInBackground(final Void... unused) {

    String auth=doLogin(t_id,password);
    System.out.println(auth);

    return auth;
}

protected void onPostExecute(String result) {
    if (this.dialog.isShowing()) {
        this.dialog.dismiss();
    } 

    if(result.equals("Welcome to this activity")) {
        Intent showContent = new Intent(getApplicationContext(),newscreen.class);
        startActivity(showContent);
    }
}

【讨论】:

  • 我应该返回“auth”吗?
  • 是的,如果你想控制它
  • 我是否需要对 doInBackground() 和 onPostExecute() 方法的参数以及返回类型进行任何更改?
  • 不,他们没问题。我认为另一个问题是您必须在开始新活动之前关闭对话框,正如 Venky 在他的回答中所写的那样
  • 先让代码工作,然后我会接受..我正在处理它
猜你喜欢
  • 1970-01-01
  • 2015-06-13
  • 1970-01-01
  • 1970-01-01
  • 2013-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多