【发布时间】:2015-03-26 17:14:17
【问题描述】:
我正在尝试制作一个连接到 MySQL 数据库并查询数据的应用程序。我不想插入任何数据,只需在给定条目中搜索关键字。我在谷歌上找到了几个教程,这个对我有用。
布局看起来不错,应用启动良好(我在实际的 Nexus 5 上测试了应用)。但是每次单击按钮时,无论文本框中是否有数据,它都会在吐司中显示“无效的IP地址”,我认为这是捕获的错误。我的 PHP 看起来像这样:
$host='*****';
$uname='*****';
$pwd='*****';
$db="*****";
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
$id=$_REQUEST['id'];
$r=mysql_query("select * from ***** where id='$id'",$con);
while($row=mysql_fetch_array($r))
{
$flag[name]=$row[name];
}
print(json_encode($flag));
mysql_close($con);
为什么会出现此错误?我如何让它发挥作用?可以提供所需的任何其他数据。
编辑
安卓代码
public class MainActivity extends Activity {
String id;
String name;
InputStream is=null;
String result=null;
String line=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText e_id=(EditText) findViewById(R.id.editText1);
Button select=(Button)findViewById(R.id.button1);
select.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
id=e_id.getText().toString();
select();
}
});
}
public void select()
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id",id));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://kanurajb.co.nf/php/search.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
try
{
JSONObject json_data = new JSONObject(result);
name=(json_data.getString("name"));
Toast.makeText(getBaseContext(), "Name : "+name,
Toast.LENGTH_SHORT).show();
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
【问题讨论】:
-
请也显示android代码..
-
hmmm,所以你在 android 平台上用 PHP 编码...有趣...
-
问题出在您的应用程序中。发布你的安卓代码。
-
我不能在这里发布我的 Java 代码。 这里就是。
-
又一个 NOMTException .... 不...不是“无效 IP ...”...您只是捕获随机异常并显示无关的 toast
catch(Exception e) { Log.e("Fail 1", e.toString()); Toast.makeText(getApplicationContext(), "Invalid IP Address", Toast.LENGTH_LONG).show(); }