2011-09-03 43 views
0

我對android非常陌生。在這個程序中,我試圖做到這一點,當在編輯文本中輸入名字時,它會顯示我已經創建的現有MySQL數據庫中的人員信息。你能告訴我如何改善這一點,也無法弄清楚如何擺脫紅色突出顯示(有錯誤''是'無法解決')在「是」在線通過Android向MySql發送和接收數據需要幫助

更新*這是我的代碼是怎樣的。 「無法解決」的問題消失了。

public class PS extends Activity { 

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


     final EditText et_Text = (EditText) findViewById(R.id.et_Text); 

     //add new KeyListener Callback (to record key input) 
     et_Text.setOnKeyListener(new OnKeyListener() { 
      //function to invoke when a key is pressed 

      public boolean onKey(View v, int keyCode, KeyEvent event) { 
       //check if there is 
       if (event.getAction() == KeyEvent.ACTION_DOWN) { 
        //check if the right key was pressed 
        if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { 

         InputStream is = null; 
         String result = ""; 


         //the name data to send 
         ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
         nameValuePairs.add(new BasicNameValuePair("name", et_Text.getText().toString())); 

         //http post 
         if (is != null) { 
          try { 

           HttpClient httpclient = new DefaultHttpClient(); 
           HttpPost httppost = new HttpPost("http://******/sampleDB/testSend.php"); 
           httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
           HttpResponse response = httpclient.execute(httppost); 
           HttpEntity entity = response.getEntity(); 
           is = entity.getContent(); 
          } catch (Exception e) { 
           Log.e("log_tag", "Error in http connection " + e.toString()); 
          } 
          //convert response to string 
          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(); 

           result = sb.toString(); 
          } catch (Exception e) { 
           Log.e("log_tag", "Error converting result " + e.toString()); 
          } 

          //parse json data 
          try { 
           JSONArray jArray = new JSONArray(result); 
           for (int i = 0; i < jArray.length(); i++) { 
            JSONObject json_data = jArray.getJSONObject(i); 
            Log.i("log_tag", "PersonID: " + json_data.getInt("PersonID") 
              + ", FirstName: " + json_data.getString("FirstName") 
              + ", LastName: " + json_data.getString("LastName") 
              + ", Age: " + json_data.getInt("Age")); 

           } 

          } catch (JSONException e) { 
           Log.e("log_tag", "Error parsing data " + e.toString()); 
          } 
          ; 
         } 
         et_Text.setText(""); 
         //and clear the EditText control 

        } 
        return true; 
       } 

       return false; 
      } 
     }); 
    } 
} 

我沒有else語句但後來在代碼中的「如果」被說成是一個死代碼...我應該使用if語句有嘗試statments內「是」在他們中?

回答

0

問題是is在第一個try塊內部被聲明,這限制了它對該塊的可見性。試試這個

// move is declaration before the try-catch 
InputStream is = null; 
try{ 
    .... 
    // just use it here 
    is = entity.getContent(); 
}catch(Exception e){ 
    Log.e("log_tag", "Error in http connection "+e.toString()); 
} 
// it will still be available here. 

這將工作,因爲是將在try-except塊之外聲明。不要忘記添加一些錯誤檢查,至少if (is != null)圍繞在您使用is

編輯 - Eror檢查,我的意思是:避免的錯誤讓用戶未處理的,這是不整潔,混亂和底線會是因爲他們購買了你的比賽。徘徊無論它可以去錯了,你應該做些什麼來保護用戶,這樣

if (is != null) { 
    // wrapped in if because this code assumes is exists 
    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(); 
} else { 
    // do whatever you have to do to signal to the user that something went wrong. 
} 

EDIT2:你的(是!= NULL)檢查是在一個非常奇怪的地方。把它移到一個更好的位置,在我原來的答案中建議,見下文。

最後一個建議:不知道你使用的編輯器,但縮進是一個可怕的混亂,代碼很難閱讀沒有合理的縮進。

public class PS extends Activity { 

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


     final EditText et_Text = (EditText) findViewById(R.id.et_Text); 

     //add new KeyListener Callback (to record key input) 
     et_Text.setOnKeyListener(new OnKeyListener() { 
      //function to invoke when a key is pressed 

      public boolean onKey(View v, int keyCode, KeyEvent event) { 
       //check if there is 
       if (event.getAction() == KeyEvent.ACTION_DOWN) { 
        //check if the right key was pressed 
        if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { 

         InputStream is = null; 
         String result = ""; 


         //the name data to send 
         ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
         nameValuePairs.add(new BasicNameValuePair("name", et_Text.getText().toString())); 

         //http post 

         try { 

          HttpClient httpclient = new DefaultHttpClient(); 
          HttpPost httppost = new HttpPost("http://******/sampleDB/testSend.php"); 
          httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
          HttpResponse response = httpclient.execute(httppost); 
          HttpEntity entity = response.getEntity(); 
          is = entity.getContent(); 
         } catch (Exception e) { 
          Log.e("log_tag", "Error in http connection " + e.toString()); 
         } 

         // At this point is should be set, if it isn't, tell user what went wrong 
         if (is != null) { 
          //convert response to string 
          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(); 

           result = sb.toString(); 
          } catch (Exception e) { 
           Log.e("log_tag", "Error converting result " + e.toString()); 
          } 

          //parse json data 
          try { 
           JSONArray jArray = new JSONArray(result); 
           for (int i = 0; i < jArray.length(); i++) { 
            JSONObject json_data = jArray.getJSONObject(i); 
            Log.i("log_tag", "PersonID: " + json_data.getInt("PersonID") 
              + ", FirstName: " + json_data.getString("FirstName") 
              + ", LastName: " + json_data.getString("LastName") 
              + ", Age: " + json_data.getInt("Age")); 

           } 

          } catch (JSONException e) { 
           Log.e("log_tag", "Error parsing data " + e.toString()); 
          } 

          et_Text.setText(""); 
          //and clear the EditText control 
         } else { 
          // Hey user, this went horribly wrong 

         } 
        } 
        return true; 
       } 

       return false; 
      } 
     }); 
    } 
} 
+0

你能給我何時以及如何使用,如果一個例子(是!= NULL),請? – Eric

+0

@Eric我必須說這個評論問題讓我感到驚訝,但請參閱編輯。如果這個答案有助於你不要忘記投票/接受它。 – fvu

+0

不幸的是,如果我使用if!= null,它會說我必須改用「try/catch」語句。 – Eric