需要有关通过Android向MySql发送和接收数据的帮助

时间:2011-09-03 15:45:41

标签: android mysql database database-connection

我对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”下的代码被认为是死代码...我应该在try语句中使用if语句吗? / p>

1 个答案:

答案 0 :(得分:0)

问题是在第一个try块中声明了is,这限制了它对该块的可见性。试试这个

 // 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

编辑 - 错误检查,我的意思是:避免错误导致用户未处理,不整洁,令人困惑,最重要的是他们会购买你的竞争对手。如果出现问题,你应该采取措施保护用户,比如

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;
            }
        });
    }
}