[英]org.jsonexception value of type org.jsonobject cannot be converted to jsonarray
[英]Android: org.JSONException “String cannot be converted to JSONObject”
您好,我是Android的新手,尤其是JSon。 我正在嘗試將我的android應用程序與連接到WAMP的php文件連接起來。 但是我得到“字符串不能轉換為JSONObject。這是我的php代碼:
if(isset($_POST['check'])){
$name = $_POST['txtuser'];
$pass = $_POST['txtpass'];
$sql = "Select * from tbluser where username = '".$name."' and password = '".$pass."'";
$query = mysql_query($sql, $conn);
$result = mysql_fetch_array($query);
$flag['code'] = 0;
if(mysql_num_rows($query) > 0){
$flag['code'] = 1;
echo '<script type="text/javascript">alert("Hello");</script>';
json_encode($flag);
}
這是我的Android代碼:
public void select()
{
ArrayList<NameValuePair> userpass = new ArrayList<NameValuePair>();
String x = txtname.getText().toString();
String y = txtpass.getText().toString();
userpass.add(new BasicNameValuePair("user", x));
userpass.add(new BasicNameValuePair("pass",y));
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.254.100/adphptest/index.php");
httppost.setEntity(new UrlEncodedFormEntity(userpass));
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();
json = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
try
{
JSONObject json_data = new JSONObject(json);
code=(json_data.getInt("code"));
if(code==1)
{
Toast.makeText(getBaseContext(), "User verified!",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Invalid!",
Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
}
轉到c:\\ wamp \\ alias \\ phpmyadmin.conf並更改它
<Directory "c:/wamp/apps/phpmyadmin3.4.5/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
</Directory>
至
<Directory "c:/wamp/apps/phpmyadmin3.4.5/">
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Order Deny,Allow
Allow from all
</Directory>
除非我錯過了一些明顯的問題,否則問題是在輸出json對象之前,您的php文件將在此行中回顯非json字符串
echo '<script type="text/javascript">alert("Hello");</script>';
這是您的Android json解析代碼看到的第一件事,因此失敗了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.