我正在使用PHP& amp;从我的Android应用程序连接到外部数据库JSON。 它是一个简单的登录系统,如果用户名和密码存在于数据库上,它会进入Main2activity但是如果不同的用户并通过它会显示错误消息 我成功连接到数据库并在浏览器中获得结果,但是虽然来到android我没有得到任何结果它显示: 错误解析数据org.json.JSONException:类型java.lang.String的值无法转换为JSONArray。 以下是我的代码:
MainActivity.java:
package com.example.hussienalrubaye.mysqlsystemlogin;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void bulogin(View view) {
//get user name and password
EditText txtusername=(EditText)findViewById(R.id.etusername);
EditText txtpassword=(EditText)findViewById(R.id.etpassword);
new MyAsyncTaskresources().execute("http://l3pfe.byethost33.com/db.php?username="+txtusername.getText().toString()+"&password=" +txtpassword.getText().toString());
}
String result = "";
public class MyAsyncTaskresources extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
}
@Override
protected String doInBackground(String... params) {
InputStream isr = null;
try{
String URL=params[0];
URL url = new URL( URL);
URLConnection urlConnection = url.openConnection();
isr = new BufferedInputStream(urlConnection.getInputStream());
}
catch(Exception e){
Log.e("log_tag", "Error in http connection " + e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result " + e.toString());
}
//parse json data
return null;
}
protected void onPostExecute(String result2){
try {
String s = "";
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json = jArray.getJSONObject(i);
s = s + "login info : " + json.getString("id") + " " + json.getString("username") + " " + json.getString("password");
break;}
if(s.length()>0){
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
Intent in=new Intent(getApplicationContext(),Main2Activity.class);
startActivity(in);}
else
Toast.makeText(getApplicationContext(),"user name or password isnot correct",Toast.LENGTH_LONG).show();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data "+e.toString());
}
}
}
}
Main2Activity.java:
package com.example.hussienalrubaye.mysqlsystemlogin;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
public class Main2Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal">
<EditText
android:hint="Enter user name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="@+id/etusername" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"></LinearLayout>
<EditText
android:hint="Enter password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="@+id/etpassword" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login"
android:id="@+id/button"
android:onClick="bulogin" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
activity_main2.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:fitsSystemWindows="true"
tools:context="com.example.hussienalrubaye.mysqlsystemlogin.Main2Activity">
<android.support.design.widget.AppBarLayout android:layout_height="wrap_content"
android:layout_width="match_parent" android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar android:id="@+id/toolbar"
android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="@layout/content_main2" />
<android.support.design.widget.FloatingActionButton android:id="@+id/fab"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="bottom|end" android:layout_margin="@dimen/fab_margin"
android:src="@android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
***content_main2.xml :***
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:showIn="@layout/activity_main2"
tools:context="com.example.hussienalrubaye.mysqlsystemlogin.Main2Activity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="my control pannel"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
db.php:
<?php
mysql_connect("sql306.byethost33.com","b33_19513012","loool");//change server name //pass username according your settings
mysql_select_db("b33_19513012_pfe");// also chang the Mysql database name
$sql1=mysql_query("select * from admins WHERE username ='" . $_GET['username'] . "' and password='" . $_GET['password'] ."'"); //querstirng
if (!$sql1) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
while($row=mysql_fetch_assoc($sql1))
$output[]=$row;
print(json_encode($output));// this will print the output in json
mysql_close();
?>
答案 0 :(得分:0)
我很乐意警告你,mysql_connect已被弃用,PHP 7再也没有mysql_connect。请改用mysqli。
正如mysql_connect doc所说,您应该指定连接链接。检查$link
变量。
$link = mysql_connect("sql306.byethost33.com", "b33_19513012", "loool");//change server name //pass username according your settings
mysql_select_db("b33_19513012_pfe", $link);// also chang the Mysql database name
$sql1 = mysql_query("select * from admins WHERE username ='" . $_GET['username'] . "' and password='" . $_GET['password'] . "'", $link); //querstirng
if (!$sql1) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error($link);
exit;
}
while ($row = mysql_fetch_assoc($sql1)) {
$output[] = $row;
}
print(json_encode($output));// this will print the output in json
mysql_close($link);
祝你好运!