我正在开发一个连接到mysql数据库的Android应用程序
这是我的错误日志的开始:
11-05 12:23:20.801 29175-29221/com.example.k12md02.ellieshotenchilada E/JSON Parser: Error parsing data org.json.JSONException: End of input at character 0 of
11-05 12:23:20.801 29175-29221/com.example.k12md02.ellieshotenchilada W/dalvikvm: threadid=11: thread exiting with uncaught exception (group=0x415c9d58)
11-05 12:23:20.801 29175-29221/com.example.k12md02.ellieshotenchilada E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
11-05 12:23:20.801 29175-29221/com.example.k12md02.ellieshotenchilada E/AndroidRuntime: Process: com.example.k12md02.ellieshotenchilada, PID: 29175
11-05 12:23:20.801 29175-29221/com.example.k12md02.ellieshotenchilada E/AndroidRuntime: java.lang.RuntimeException: An error occured while executing doInBackground()
11-05 12:23:20.801 29175-29221/com.example.k12md02.ellieshotenchilada E/AndroidRuntime: at android.os.AsyncTask$3.done(AsyncTask.java:300)
11-05 12:23:20.801 29175-29221/com.example.k12md02.ellieshotenchilada E/AndroidRuntime: at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
11-05 12:23:20.801 29175-29221/com.example.k12md02.ellieshotenchilada E/AndroidRuntime: at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
这是我使用的JSONParser类:
package com.example.k12md02.ellieshotenchilada;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
public class JSONParser {
String charset = "UTF-8";
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result = new StringBuilder();
URL urlObj;
JSONObject jObj = null;
StringBuilder sbParams;
String paramsString;
public JSONObject makeHttpRequest(String url, String method,
HashMap<String, String> params) {
sbParams = new StringBuilder();
int i = 0;
for (String key : params.keySet()) {
try {
if (i != 0){
sbParams.append("&");
}
sbParams.append(key).append("=")
.append(URLEncoder.encode(params.get(key), charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
if (method.equals("POST")) {
// request method is POST
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", charset);
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.connect();
paramsString = sbParams.toString();
wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(paramsString);
wr.flush();
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
else if(method.equals("GET")){
// request method is GET
if (sbParams.length() != 0) {
url += "?" + sbParams.toString();
}
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Charset", charset);
conn.setConnectTimeout(15000);
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
//Receive the response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.d("JSON Parser", "result: " + result.toString());
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
// try parse the string to a JSON object
try {
jObj = new JSONObject(result.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jObj;
}`enter code here`
}
这是以下活动:
package com.example.k12md02.ellieshotenchilada;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class AllProductsActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> menuList;
// url to get all products list
//private static String url_all_products = "http://localhost:8383/MENU_GET_ALL_PRODUCTS.php";
private static String url_all_products = "http://localhost:8383/MENU_GET_ALL_PRODUCTS.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_MENU = "menu";
private static final String TAG_PRICE = "price";
private static final String TAG_ITEM = "item";
// products JSONArray
JSONArray menu = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_see_menu);
// Hashmap for ListView
menuList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllmenu().execute();
// Get listview
ListView lv = getListView();
// on selecting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String price = ((TextView) view.findViewById(R.id.price)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PRICE, price);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllmenu extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
HashMap<String, String> params = new HashMap<String, String>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
Log.d("All Menu Items: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Menu items
menu = json.getJSONArray(TAG_MENU);
// looping through All Products
for (int i = 0; i < menu.length(); i++) {
JSONObject c = menu.getJSONObject(i);
// Storing each json item in variable
String price = c.getString(TAG_PRICE);
String item = c.getString(TAG_ITEM);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PRICE, price);
map.put(TAG_ITEM, item);
// adding HashList to ArrayList
menuList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
AddToMenuActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllProductsActivity.this, menuList,
R.layout.list_item, new String[] {TAG_ITEM, TAG_PRICE
},
new int[] {R.id.item, R.id.price });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
这是我正在使用的PHP文件:
<?php
/*
* Following code will list all the Menus
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/menu_db_connect.php';
// connecting to db
//$db = new DB_CONNECT();
// import database connection variables
require_once __DIR__ . '/menu_db_config.php';
$db = mysqli_connect(MENU_DB_SERVER, MENU_DB_USER, MENU_DB_PASSWORD) or die(mysqli_error());
mysqli_select_db($db, "ellieshotenchilada");
// get all Menus from Menu table
$sqlCommand= "SELECT * FROM menu";
$result = mysqli_query( $db, $sqlCommand) or die(mysqli_error());
// check for empty result
if (mysqli_num_rows($result) > 0) {
// looping through all results
// Menu node
$response["Menu"] = array();
while ($row = mysqli_fetch_array($result)) {
// temp user array
$Menu = array();
$Menu["Item"] = $row["Item"];
$Menu["Price"] = $row["Price"];
// $Menu["pid"] = $row["pid"];
// $Menu["created_at"] = $row["created_at"];
// $Menu["updated_at"] = $row["updated_at"];
// push single Menu into final response array
array_push($response["Menu"], $Menu);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);} else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";
// echo no users JSON
echo json_encode($response);
}
?>
我在网上发现了很多类似的错误,但它们都是关于一个与我类似的弃用教程,所以每次我尝试他们的解决方案时都会得到一个无关的错误。