我目前正在开发一个Android应用程序。当我尝试登录时,我在日志猫中收到以下错误。
11-30 21:23:18.694: E/JSON Parser(1914): Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
11-30 21:23:18.923: W/dalvikvm(1914): threadid=10: thread exiting with uncaught exception (group=0xb3e56288)
11-29 22:23:17.329: E/AndroidRuntime(1858): FATAL EXCEPTION: AsyncTask #1
11-29 22:23:17.329: E/AndroidRuntime(1858): java.lang.RuntimeException: An error occured while executing doInBackground()
11-29 22:23:17.329: E/AndroidRuntime(1858): at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-29 22:23:17.329: E/AndroidRuntime(1858): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
11-29 22:23:17.329: E/AndroidRuntime(1858): at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
11-29 22:23:17.329: E/AndroidRuntime(1858): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
11-29 22:23:17.329: E/AndroidRuntime(1858): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-29 22:23:17.329: E/AndroidRuntime(1858): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-29 22:23:17.329: E/AndroidRuntime(1858): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
11-29 22:23:17.329: E/AndroidRuntime(1858): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
11-29 22:23:17.329: E/AndroidRuntime(1858): at java.lang.Thread.run(Thread.java:856)
11-29 22:23:17.329: E/AndroidRuntime(1858): Caused by: java.lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=localhost/BCASStudentInfo/login.php
11-29 22:23:17.329: E/AndroidRuntime(1858): at org.apache.http.impl.client.DefaultRequestDirector.determineRoute(DefaultRequestDirector.java:591)
11-29 22:23:17.329: E/AndroidRuntime(1858): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:293)
11-29 22:23:17.329: E/AndroidRuntime(1858): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
11-29 22:23:17.329: E/AndroidRuntime(1858): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
11-29 22:23:17.329: E/AndroidRuntime(1858): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
11-29 22:23:17.329: E/AndroidRuntime(1858): at com.bcas.bcasstudentinfo.JSONParser.makeHttpRequest(JSONParser.java:110)
11-29 22:23:17.329: E/AndroidRuntime(1858): at com.bcas.bcasstudentinfo.Login$TryLogin.doInBackground(Login.java:134)
11-29 22:23:17.329: E/AndroidRuntime(1858): at com.bcas.bcasstudentinfo.Login$TryLogin.doInBackground(Login.java:1)
11-29 22:23:17.329: E/AndroidRuntime(1858): at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-29 22:23:17.329: E/AndroidRuntime(1858): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
11-29 22:23:17.329: E/AndroidRuntime(1858): ... 5 more
11-29 22:23:22.417: E/WindowManager(1858): Activity com.bcas.bcasstudentinfo.Login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@b45b4a40 that was originally added here
11-29 22:23:22.417: E/WindowManager(1858): android.view.WindowLeaked: Activity com.bcas.bcasstudentinfo.Login has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@b45b4a40 that was originally added here
11-29 22:23:22.417: E/WindowManager(1858): at android.view.ViewRootImpl.<init>(ViewRootImpl.java:374)
11-29 22:23:22.417: E/WindowManager(1858): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:292)
11-29 22:23:22.417: E/WindowManager(1858): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
11-29 22:23:22.417: E/WindowManager(1858): at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
11-29 22:23:22.417: E/WindowManager(1858): at android.view.Window$LocalWindowManager.addView(Window.java:547)
11-29 22:23:22.417: E/WindowManager(1858): at android.app.Dialog.show(Dialog.java:277)
11-29 22:23:22.417: E/WindowManager(1858): at com.bcas.bcasstudentinfo.Login$TryLogin.onPreExecute(Login.java:119)
11-29 22:23:22.417: E/WindowManager(1858): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
11-29 22:23:22.417: E/WindowManager(1858): at android.os.AsyncTask.execute(AsyncTask.java:534)
11-29 22:23:22.417: E/WindowManager(1858): at com.bcas.bcasstudentinfo.Login$1.onClick(Login.java:70)
11-29 22:23:22.417: E/WindowManager(1858): at android.view.View.performClick(View.java:4084)
11-29 22:23:22.417: E/WindowManager(1858): at android.view.View$PerformClick.run(View.java:16966)
11-29 22:23:22.417: E/WindowManager(1858): at android.os.Handler.handleCallback(Handler.java:615)
11-29 22:23:22.417: E/WindowManager(1858): at android.os.Handler.dispatchMessage(Handler.java:92)
11-29 22:23:22.417: E/WindowManager(1858): at android.os.Looper.loop(Looper.java:137)
11-29 22:23:22.417: E/WindowManager(1858): at android.app.ActivityThread.main(ActivityThread.java:4745)
11-29 22:23:22.417: E/WindowManager(1858): at java.lang.reflect.Method.invokeNative(Native Method)
11-29 22:23:22.417: E/WindowManager(1858): at java.lang.reflect.Method.invoke(Method.java:511)
11-29 22:23:22.417: E/WindowManager(1858): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-29 22:23:22.417: E/WindowManager(1858): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-29 22:23:22.417: E/WindowManager(1858): at dalvik.system.NativeStart.main(Native Method)
我使用的代码包含在这里。
登录.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import com.bcas.bcasstudentinfo.R;
import com.example.bcasstudentinfo.student_home;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Login extends Activity {
private Button login;
private EditText user, pass;
private ProgressDialog dialog;
JSONParser jsonParser=new JSONParser();
//private static final String LOGIN_URL="http://10.0.2.2/BCASStudentInfo/login.php";
private static final String LOGIN_URL="localhost/BCASStudentInfo/login.php";
private static final String TAG_SUCCESS="success";
private static final String TAG_MESSAGE="message";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
assigncomponent();
try{
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
/*Thread log= new Thread(){
public void run(){
try{
Intent openHome=new Intent("com.bcas.bcasstudentinfo.STFHOME");
startActivity(openHome);
}catch(Exception e){
e.getMessage();
}
}
};
log.start();*/
new TryLogin().execute();
/*dialog= new ProgressDialog(Login.this);
dialog.setMessage("Attemting Login");
dialog.setIndeterminate(false);
dialog.setCancelable(true);
dialog.show();
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("Nusername", user.getText().toString()));
postParameters.add(new BasicNameValuePair("Npassword", pass.getText().toString()));
//String valid = "1";
String response = null;
try {
response = CustomHttpClient.executeHttpPost("http://localhost/BCASStudentInfo/login.php", postParameters);
String res=response.toString();
Log.d("res:", res);
// res = res.trim();
res= res.replaceAll("''s+","");
//error.setText(res);
if(res.equals("1")){
Intent openHome=new Intent("com.bcas.bcasstudentinfo.STFHOME");
startActivity(openHome);}
else{
dialog.setMessage("Sorry!! Incorrect Username or Password"); }
} catch (Exception e) {
e.printStackTrace();
}*/
}
}
);}catch(Exception e){
dialog.setMessage(e.getMessage());
}
}
class TryLogin extends AsyncTask<String, String, String>{
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog= new ProgressDialog(Login.this);
dialog.setMessage("Attemting Login");
dialog.setIndeterminate(false);
dialog.setCancelable(true);
dialog.show();
}
@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
int success;
String username=user.getText().toString();
String password=pass.getText().toString();
try{
List<NameValuePair> params= new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Nusername", username));
params.add(new BasicNameValuePair("Npassword", password));
Log.d("request!", "starting");
JSONObject json=jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);
Log.d("Login attempt", json.toString());
success=json.getInt(TAG_SUCCESS);
if(success==1){
Log.d("Login Successful!", json.toString());
// save user data
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(Login.this);
Editor edit = sp.edit();
edit.putString("username", username);
edit.commit();
Intent i=new Intent(Login.this,student_home.class);
finish();
startActivity(i);
return json.getString(TAG_MESSAGE);
}else{
Log.d("Login Failure", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
}catch(JSONException e){
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String file_url) {
// TODO Auto-generated method stub
dialog.dismiss();
if(file_url!=null){
Toast.makeText(Login.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
private void assigncomponent(){
login=(Button) findViewById(R.id.button_personal);
user=(EditText)findViewById(R.id.editText_user);
pass=(EditText)findViewById(R.id.editText_pass);
}
}
登录.php
<?php
//load and connect to MySQL database stuff
require("config.inc.php");
//$con = mysql_connect("localhost", "root", "") or die(mysql_error());
//mysql_select_db("bcasdb",$con);
if (!empty($_POST)) {
//gets user's info based off of a username.
$query = "
SELECT
`tbl_user_login`.`u_id`,
`tbl_user_login`.`u_username`,
`tbl_user_login`.`u_password`,
`tbl_user_login`.`u_privilege`,
`tbl_user_login`.`user_type`,
`tbl_user_login`.`u_user_reg_id`
FROM `bcasdb`.`tbl_user_login`;
WHERE `tbl_user_login`.`u_username` = :username
";
$query_params = array(
':username' => $_POST['Nusername']
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
// For testing, you could use a die and message.
//die("Failed to run query: " . $ex->getMessage());
//or just use this use this one to product JSON data:
$response["success"] = 0;
$response["message"] = "Database Error1. Please Try Again!";
die(json_encode($response));
}
$validated_info = FALSE;
$row = $stmt->fetch();
if ($row) {
if ($_POST['Npassword'] == $row['u_password']) {
$login_ok = TRUE;
}
}
if ($login_ok) {
$response["success"] = 1;
$response["message"] = "Login successful!";
die(json_encode($response));
} else {
$response["success"] = 0;
$response["message"] = "Invalid Credentials!";
die(json_encode($response));
}
} else {
echo "Empty Post";
}
header('Content-type=application/json; charset=utf-8');
?>
康菲克.php
<?php
$host = "localhost";
$dbname = "bcasdb";
$username = "root";
$password = "";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try
{
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
die("Failed to connect to the database: " . $ex->getMessage());
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
function undo_magic_quotes_gpc(&$array)
{
foreach($array as &$value)
{
if(is_array($value))
{
undo_magic_quotes_gpc($value);
}
else
{
$value = stripslashes($value);
}
}
}
undo_magic_quotes_gpc($_POST);
undo_magic_quotes_gpc($_GET);
undo_magic_quotes_gpc($_COOKIE);
}
header('Content-Type: text/html; charset=utf-8');
session_start();
?>
JSONParser类
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(final String url) {
// Making HTTP request
try {
// Construct the client and the HTTP request.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// Execute the POST request and store the response locally.
HttpResponse httpResponse = httpClient.execute(httpPost);
// Extract data from the response.
HttpEntity httpEntity = httpResponse.getEntity();
// Open an inputStream with the data content.
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Create a BufferedReader to parse through the inputStream.
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
// Declare a string builder to help with the parsing.
StringBuilder sb = new StringBuilder();
// Declare a string to store the JSON object data in string form.
String line = null;
// Build the string until null.
while ((line = reader.readLine()) != null) {
sb.append(line + "'n");
}
// Close the input stream.
is.close();
// Convert the string builder data to an actual string.
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// Try to parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// Return the JSON Object.
return jObj;
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
我无法弄清楚问题所在,有人可以帮忙吗?
供您参考:我正在使用 WAMP 服务器并使用 eclipse 中的模拟器进行测试。
您的登录网址应该是
http://localhost/BCASStudentInfo/login.php
而不是
localhost/BCASStudentInfo/login.php