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

发布于 2024-12-02 16:41:44 字数 4178 浏览 1 评论 0原文

我对安卓很陌生。在这个程序中,我试图做到这样,当人们在编辑文本中输入名字时,它将在我已经创建的现有 MySQL 数据库中显示该人的信息。你能告诉我如何改进这个,而且我也不知道如何摆脱

更新*行“is”上的红色突出显示(有错误“'is'无法解析”),这就是我的代码的样子喜欢。 “无法解决”的问题就消失了。

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”下的代码据说是死代码...我应该在其中包含“is”的 try 语句中使用 if 语句吗?

I am very new to android. In this program, I'm trying to make it so that when one types a first name in the edit text it will show the information of the person in an existing MySQL database I made already. Can you tell me how to improve this and also I can't figure out how to get rid of the red highlight(has error "'is' cannot be resolved") on "is" at line

Updated* this is how my code looks like. The "cannot be resolved" problem is gone.

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

I don't have the else statement yet but then the code under the "if" is said to be a dead code... Should I use the if statement inside the try statments that have "is" in them?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

南风起 2024-12-09 16:41:45

问题是 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 块之外声明。不要忘记添加一些错误检查,至少在使用 is 的地方添加一个 if (is != null)

编辑 - 错误检查,我的意思是:避免这种情况如果错误没有得到处理,就会传给用户,这是不整洁、令人困惑的,最重要的是他们会购买你的竞争对手。无论哪里可能出错,你都应该做一些事情来保护用户,就像这样

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:你的 (is != 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;
            }
        });
    }
}

The problem is that is was declared inside the first try block, which limits its visibility to that block. Try this

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

This will work because is will be declared outside of the try-except block. Don't forget to add some error checking, at least an if (is != null) around where you use is

EDIT - Eror checking, what I mean: avoid that errors get to the user unhandled, it's untidy, confusing and the bottom line will be that they buy your competition. Whereever it can go wrong you should do something to shield the user, like this

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: your (is != null) check was at a very odd place. Moved it to a better spot, suggested in my original answer, see below.

And a last suggestion: no idea what editor you use, but indentation was a horrible mess, code is hard to read without reasonable indentation.

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;
            }
        });
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文