【问题标题】:I am dealing with my web service while getting response -how to get response from server side?我正在处理我的 Web 服务,同时获得响应 - 如何从服务器端获得响应?
【发布时间】:2013-09-04 05:00:10
【问题描述】:

我使用 post 方法调用 web 服务并在调用 web 服务时出错。

Logcat:

09-04 04:58:56.437: E/AndroidRuntime(803): FATAL EXCEPTION: AsyncTask #1
09-04 04:58:56.437: E/AndroidRuntime(803): java.lang.RuntimeException: An error occure while executing doInBackground()

我正在使用的网络服务是 类 AttemptLogin 扩展 AsyncTask {

     /**
     * Before starting background thread Show Progress Dialog
     * */
    boolean failure = false;

    @Override
    protected void onPreExecute() {
         String username = user.getText().toString();
         String password = pass.getText().toString();
        super.onPreExecute(); 

        pDialog = new ProgressDialog(Loginpage.this);
        pDialog.setMessage("Attempting login...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();

    }

    @Override
    protected String doInBackground(String... args) {
        // TODO Auto-generated method stub
         // Check for success tag
        String username=args [0];
        String password=args[1];
        int success;

        try {
            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();


            params.add(new BasicNameValuePair("username", username));
            params.add(new BasicNameValuePair("password", password));

            Log.d("request!", "starting");
            // getting product details by making HTTP request
            JSONObject json = jsonParser.makeHttpRequest(
                   LOGIN_URL, "POST", params);

            // check your log for json response
            Log.d("Login attempt", json.toString());

            // json success tag
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                Log.d("Login Successful!", json.toString());
                Intent i = new Intent(Loginpage.this, Propertyapp.class);
                finish();
                startActivity(i);
                return json.getString(TAG_MESSAGE);
            }else{
                Log.d("Login Failure!", json.getString(TAG_MESSAGE));
                return json.getString(TAG_MESSAGE);

            }
        } catch (JSONException e) {
            e.printStackTrace();
        } 
        return null;            
    }
    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog once product deleted
        pDialog.dismiss();
        if (file_url != null){
            Toast.makeText(Loginpage.this, file_url, Toast.LENGTH_LONG).show();
        }

    }

}

public JSONObject makeHttpRequest(String url, String 方法, 列出参数){

    // Making HTTP request
    try {

        // check for request method
        if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }           

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

【问题讨论】:

    标签: android web-services post httpclient


    【解决方案1】:

    String username = user.getText().toString();在onPreExecute方法中移动这一行..u在doInBackground方法中无法处理Ui

    【讨论】:

    • 当我改变这个时,我在 doinbackground 中遇到错误,这个语句 params.add(new BasicNameValuePair("username", username));
    • 其实我的意思是你应该在 onPreexecute meyhod 中进行 ui 相关的初始化
    • 是的,您应该在类中声明该变量,以便后台方法中的 do 可以访问该 avriable
    • 在声明你在课堂上所说的方法后,我收到了这个错误 09-04 05:14:13.167: E/AndroidRuntime(999): java.lang.RuntimeException: Unable to instance activity ComponentInfo{com .example.vinnipostpropertyapp/com.example.vinnipostpropertyapp.Loginpage}:java.lang.NullPointerException
    • 是的,因为你的变量是空的,它不包含任何东西。你把 user.getText.tioString();预执行方法中的行?
    【解决方案2】:

    我认为线条 String username = user.getText().toString(); String password = pass.getText().toString(); 导致问题。

    您无法访问或修改 AsyncTask 中的 UI。

    您可以在 onPreExecute() 之前执行此操作 (更喜欢全局声明变量)

    或在调用.execute("") 并将用户名和密码作为参数传递之前,即.execute(username,password);。然后在 doInBackground 里面,你可以得到它作为 args[0] 和 args[1]。

    【讨论】:

      【解决方案3】:
      Hope this might help you.
       int sucess;//declare in global
       @Override
      
       protected String doInBackground(String... args)
         {
      
          // TODO Auto-generated method stub
           // Check for success tag
      
           String username = user.getText().toString();
           String password = pass.getText().toString();
      
              // Building Parameters
              List<NameValuePair> params = new ArrayList<NameValuePair>();
              params.add(new BasicNameValuePair("username", username));
              params.add(new BasicNameValuePair("password", password));
              // getting product details by making HTTP request
              JSONObject json = jsonParser.makeHttpRequest(
                     LOGIN_URL, "POST", params);
              try
              {
              success = json.getInt(TAG_SUCCESS);
              }
              catch (Exception e) 
              {
          e.printStackTrace();
          }
              return null;
              }
              protected void onPostExecute(String file_url) {
          pDialog.dismiss();//progress dialog pDialog
              if (success == 1) {    
                  Intent i = new Intent(Loginpage.this, Propertyapp.class);
                  startActivity(i);
                 finish();
              }
          } 
      
      }
      

      【讨论】:

        【解决方案4】:

        全局声明意图并在 oncreate() 中初始化,

        Intent i ;
        
        i= new Intent(Loginpage.this, Propertyapp.class);
        

        根据您的要求使用它

                    startActivity(i);
        

        【讨论】:

          【解决方案5】:

          你的问题

          String username = user.getText().toString();
          String password = pass.getText().toString();
          

          您不能在后台线程中执行 UI 更新。将它们移出。
          您可以为此使用 onPreExecute() 方法,或者只是将用户名和密码传递给 AsyncTask()。

          public class YourAsyncTask extends AsyncTask<String, Integer, String>{
          
                  @Override
                  protected String doInBackground(String... params) {
                      String username = params[0];
                      String password = params[1];
                                   ....
                   }
          }
          

          【讨论】:

          • 是 09-05 10:07:03.257:E/AndroidRuntime(18239):致命异常:AsyncTask #1 09-05 10:07:03.257:E/AndroidRuntime(18239):java.lang .RuntimeException: 执行 doInBackground() 09-05 10:07:03.257: E/AndroidRuntime(18239): at android.os.AsyncTask$3.done(AsyncTask.java:299) 09-05 10:07 时发生错误: 03.257: E/AndroidRuntime(18239): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352) 按下按钮后我想登录并显示另一个相应的页面
          • 尝试移动 startActivity(i);在 onPostExecute() 方法中!
          • 在单击登录按钮时添加 mu 用户名和密码时出现此错误 09-05 10:35:15.817: E/WindowManager(21519): Activity com.example.vinnipostpropertyapp.Loginpage已泄露窗口 com.android.internal.policy.impl.PhoneWindow$DecorView{40d3f0d8 VE.... R.....ID 0,0-228,72} 最初在 09-05 10:35 此处添加: 15.817: E/WindowManager(21519): android.view.WindowLeaked: Activity com.example.vinnipostpropertyapp.Loginpage 已泄露窗口 com.android.internal.policy.impl.PhoneWindow$DecorView{40d3f0d8 VE.... R... ..ID 0,0-228,72}
          猜你喜欢
          • 1970-01-01
          • 2019-09-11
          • 2015-11-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-03-25
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多