您好我的Android应用程序有问题。我尝试从我在SQL查询中使用变量的php文件解析JSON响应。我在浏览器中得到了正确的响应,但我的Android应用程序中出现错误,无法解析。如果我在没有变量的情况下运行它,我的Android中不会出现任何错误,但我无法执行我想要的搜索。我向你展示了php和Android文件。
get_all_products.php
<?php
//Used to compress Errors about old version of PHP!!!!!!!!!!!!!!!!!!!
error_reporting(E_ALL ^ E_DEPRECATED);// To be changed
//Used to compress Errors about old version of PHP!!!!!!!!!!!!!!!!!!!
/*
* The following code will list all the MuseumItems
*/
//Array for JSON responce
$responce = array();
//Include db connect class
require_once __DIR__.'/db_connect.php';
//Connection to db
$db = new DB_CONNECT();
//Variable for search strings
//$item_name = $_POST['ItemName'];
//$item_type = $_POST['ItemType'];
//$item_historic_period = $_POST['ItemHistoricPeriod'];
//Get all Items from museumItem table
//$result = mysql_query("SELECT * FROM museumItems WHERE "
// . "ItemName = '{$_POST['itemName']}'"
// . "OR ItemType = '{$_GET['itemType']}' "
// . "OR ItemHistoricPeriod = '{$_GET['itemHistoricPeriod']}' ")
//or die(mysql_error());
$query = "SELECT * FROM museumItems";
$itemName = $_GET["ItemName"];
$itemType = $_GET["ItemType"];
$itemHistoricPeriod = $_GET["ItemHistoricPeriod"];
$wherestr = "";
if ($itemName)
{
if (strlen($wherestr) > 0) $wherestr .= " OR ";
$wherestr .= "ItemName LIKE '%{$itemName}%'";
}
if ($itemType)
{
if (strlen($wherestr) > 0) $wherestr .= " OR ";
$wherestr .= "ItemType LIKE '%{$itemType}%'";
}
if ($itemHistoricPeriod)
{
if (strlen($wherestr) > 0) $wherestr .= " OR ";
$wherestr .= "ItemHistoricPeriod LIKE '%{$itemHistoricPeriod}%'";
}
//var_dump($wherestr);
if (strlen($wherestr) > 0){
$query .= " WHERE {$wherestr}";
}
//var_dump($query);
//3. EXECUTE QUERY
$result=mysql_query($query) or die(mysql_error());;
//echo $query;
//Check for empty result
if (mysql_num_rows($result) > 0)
{
//Looping trough all results
//museumItems node
$responce["museumItems"] = array();
while ($row = mysql_fetch_array($result))
{
//Temp user array
$museum_item = array();
$museum_item["id"] = $row["ID"];
$museum_item["itemName"] = $row["ItemName"];
$museum_item["artistName"] = $row["ArtistName"];
$museum_item["itemLocation"] = $row["ItemLocation"];
$museum_item["itemHistoricPeriod"] = $row["ItemHistoricPeriod"];
$museum_item["itemType"] = $row["ItemType"];
$museum_item["itemDescription"] = $row["ItemDescription"];
$museum_item["itemURL"] = $row["ItemURL"];
$museum_item["itemImage"] = $row["ItemImage"];
//Push single item into final responce array
array_push($responce["museumItems"], $museum_item);
}
//Success
$responce["success"] = 1;
//Echoing JSON responce
echo json_encode($responce);
}else
{
//No items found
$responce["success"] = 0;
$responce["message"] = "No products found";
//Echo no users JSON
echo json_encode($responce);
}
?>
MainActivity.java
package com.cloudlionheart.museumsearchapplication;
import android.content.Intent;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity
{
static String nameSearchCriteria;
static String typeSearchCriteria;
static String historicalPeriodCriteria;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getSupportActionBar();
actionBar.setLogo(R.drawable.ic_launcher);
actionBar.setDisplayUseLogoEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
/** Called when the user clicks the Send button */
public void goToSearchActivity(View view)
{
Intent intent = new Intent(this, DisplaySearchResultsActivity.class);
startActivity(intent);
EditText nameSearchCriteriaEditText =
(EditText)findViewById(R.id.searchActivityQueryByNameEditText);
nameSearchCriteria = nameSearchCriteriaEditText.getText().toString();
EditText typeSearchCriteriaEditText =
(EditText)findViewById(R.id.searchActivityQueryByTypeEditText);
typeSearchCriteria = typeSearchCriteriaEditText.getText().toString();
EditText historicalPeriodCriteriaEditText =
(EditText)findViewById(R.id.searchActivityQueryByHistoricPeriodEditText);
historicalPeriodCriteria = historicalPeriodCriteriaEditText.getText().toString();
System.out.printf(nameSearchCriteria);
}
}
DisplaySearchResultActivity.java
package com.cloudlionheart.museumsearchapplication;
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.TextView;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class DisplaySearchResultsActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> museumItemsList;
// url to get all products list
private static String url_search_results = "http://10.0.3.2/android_connect/get_all_products.php";
// JSON Node names
static final String TAG_SUCCESS = "success";
static final String TAG_MUSEUM_ITEMS = "museumItems";
static final String TAG_MUSEUM_ITEM_ID = "id";
static final String TAG_MUSEUM_ITEM_NAME = "itemName";
static final String TAG_MUSEUM_ITEM_ARTIST = "artistName";
static final String TAG_MUSEUM_ITEM_LOCATION = "itemLocation";
static final String TAG_MUSEUM_ITEM_HISTORICAL_PERIOD = "itemHistoricalPeriod";
static final String TAG_MUSEUM_ITEM_TYPE = "itemType";
static final String TAG_MUSEUM_ITEM_DESCRIPTION = "itemDescription";
static final String TAG_MUSEUM_ITEM_ITEM_URL = "itemURL";
static final String TAG_MUSEUM_ITEM_IMAGE = "itemImage";
// products JSONArray
JSONArray museumItems = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_search_resaults);
// Hashmap for ListView
museumItemsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
//OnItemClick implementation
ListView lv = getListView();
lv = getListView();
// ListView on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String singleItemName = ((TextView) view.findViewById(R.id.museum_item_name))
.getText().toString();
String singleItemArtist = ((TextView) view.findViewById(R.id.museum_item_artist))
.getText().toString();
String singleItemLocation = ((TextView) view.findViewById(R.id.museum_item_location))
.getText().toString();
String singleItemHistoricPeriod = ((TextView) view.findViewById(R.id.museum_item_historic_period))
.getText().toString();
//String singleItemType = ((TextView) view.findViewById(R.id.museum_item_historic_period))
// .getText().toString();
String singleItemDescription = ((TextView) view.findViewById(R.id.single_item_description))
.getText().toString();
String singleItemURL = ((TextView) view.findViewById(R.id.museum_item_URL))
.getText().toString();
String singleItemImage = ((TextView) view.findViewById(R.id.single_item_image_link))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(), SingleItemActivity.class);
in.putExtra(TAG_MUSEUM_ITEM_NAME, singleItemName);
in.putExtra(TAG_MUSEUM_ITEM_ARTIST, singleItemArtist);
in.putExtra(TAG_MUSEUM_ITEM_LOCATION, singleItemLocation);
in.putExtra(TAG_MUSEUM_ITEM_HISTORICAL_PERIOD, singleItemHistoricPeriod);
//in.putExtra(TAG_MUSEUM_ITEM_TYPE, singleItemType);
in.putExtra(TAG_MUSEUM_ITEM_DESCRIPTION, singleItemDescription);
in.putExtra(TAG_MUSEUM_ITEM_ITEM_URL, singleItemURL);
in.putExtra(TAG_MUSEUM_ITEM_IMAGE, singleItemImage);
startActivity(in);
}
});
}
/**
* Background Async Task to Load all product by making HTTP Request
*/
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(DisplaySearchResultsActivity.this);
pDialog.setMessage("Loading Museum Items. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
*/
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_search_results, "GET", params);
// Check your log cat for JSON response
Log.d("All Museum Items: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
museumItems = json.getJSONArray(TAG_MUSEUM_ITEMS);
// looping through All Products
for (int i = 0; i < museumItems.length(); i++) {
JSONObject c = museumItems.getJSONObject(i);
// Storing each json item in variable
String item_id = c.getString(TAG_MUSEUM_ITEM_ID);
String item_name = c.getString(TAG_MUSEUM_ITEM_NAME);
String item_artist = c.getString(TAG_MUSEUM_ITEM_ARTIST);
String item_historic_period = c.getString(TAG_MUSEUM_ITEM_HISTORICAL_PERIOD);
String item_location = c.getString(TAG_MUSEUM_ITEM_LOCATION);
String item_type = c.getString(TAG_MUSEUM_ITEM_TYPE);
String item_description = c.getString(TAG_MUSEUM_ITEM_DESCRIPTION);
String item_URL = c.getString(TAG_MUSEUM_ITEM_ITEM_URL);
String list_image = c.getString(TAG_MUSEUM_ITEM_IMAGE);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_MUSEUM_ITEM_ID, item_id);
map.put(TAG_MUSEUM_ITEM_NAME, item_name);
map.put(TAG_MUSEUM_ITEM_ARTIST, item_artist);
map.put(TAG_MUSEUM_ITEM_HISTORICAL_PERIOD, item_historic_period);
map.put(TAG_MUSEUM_ITEM_LOCATION, item_location);
map.put(TAG_MUSEUM_ITEM_TYPE, item_type);
map.put(TAG_MUSEUM_ITEM_DESCRIPTION, item_description);
map.put(TAG_MUSEUM_ITEM_ITEM_URL,item_URL);
map.put(TAG_MUSEUM_ITEM_IMAGE, list_image);
// adding HashList to ArrayList
museumItemsList.add(map);
}
}
} 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 MyAdapter(DisplaySearchResultsActivity.this, museumItemsList);
setListAdapter(adapter);
}
});
}
}
}
网址
http://localhost/android_connect/get_all_products.php?ItemName=Mona%20Lisa&ItemHistoricPeriod=1889&ItemType=Painting
我的JSON回复:
{"museumItems":[{"id":"1","itemName":"Mona Lisa","artistName":"Leonardo da Vinci","itemLocation":"Louvre Museum, Paris","itemHistoricPeriod":"1503 - 1506","itemType":"Painting","itemDescription":"The Mona Lisa (Monna Lisa or La Gioconda in Italian; La Joconde in French) is a half-length portrait of a woman by the Italian artist Leonardo da Vinci, which has been acclaimed as \"the best known, the most visited, the most written about, the most sung about, the most parodied work of art in the world\"","itemURL":"http:\/\/www.louvre.fr\/en\/oeuvre-notices\/mona-lisa-%E2%80%93-portrait-lisa-gherardini-wife-francesco-del-giocondo","itemImage":"http:\/\/10.0.3.2\/image_folder\/mona_lisa.png"},{"id":"2","itemName":"The Scream","artistName":"Edvard Munch","itemLocation":"National Gallery, Oslo, Norway","itemHistoricPeriod":"1893","itemType":"Painting","itemDescription":"The Scream (Norwegian: Skrik) is the popular name given to each of four versions of a composition, created as both paintings and pastels, by the Expressionist artist Edvard Munch between 1893 and 1910. Der Schrei der Natur (The Scream of Nature) is the title Munch gave to these works, all of which show a figure with an agonized expression against a landscape with a tumultuous orange sky. Arthur Lubow has described The Scream as \"an icon of modern art, a Mona Lisa for our time.\"","itemURL":"http:\/\/www.edvardmunch.org\/the-scream.jsp","itemImage":"http:\/\/10.0.3.2\/image_folder\/The_Scream.png"},{"id":"3","itemName":"The Starry Night","artistName":"Vincent van Gogh","itemLocation":"Museum of Modern Art, New York City","itemHistoricPeriod":"1889","itemType":"Painting","itemDescription":"The Starry Night is an oil on canvas by the Dutch post-impressionist painter Vincent van Gogh. Painted in June, 1889, it depicts the view from the east-facing window of his asylum room at Saint-R?my-de-Provence, just before sunrise, with the addition of an idealized village.It has been in the permanent collection of the Museum of Modern Art in New York City since 1941, acquired through the Lillie P. Bliss Bequest. It is regarded as among Van Gogh's finest works, and one of the most recognized monuments in the history of Western culture.","itemURL":"http:\/\/www.moma.org\/collection\/object.php?object_id=79802","itemImage":"http:\/\/10.0.3.2\/image_folder\/Night.png"},{"id":"4","itemName":"The Last Supper","artistName":"Leonardo da Vinci","itemLocation":"Santa Maria delle Grazie, Milan","itemHistoricPeriod":"1494 - 1499","itemType":"Painting","itemDescription":"The Last Supper (Italian: Il Cenacolo or L'Ultima Cena) is a late 15th-century mural painting by Leonardo da Vinci in the refectory of the Convent of Santa Maria delle Grazie, Milan. It is one of the world's most famous paintings, and one of the most studied, scrutinized, and satirized.","itemURL":"http:\/\/milan.arounder.com\/en\/churches\/santa-maria-delle-grazie-church","itemImage":"http:\/\/10.0.3.2\/image_folder\/The_Last_Supper.png"},{"id":"5","itemName":"Guernica","artistName":"Pablo Picasso","itemLocation":"Museo Reina Sofia, Madrid, Spain","itemHistoricPeriod":"1937","itemType":"Painting","itemDescription":"Guernica is a mural-sized oil painting on canvas by Spanish artist Pablo Picasso completed by June 1937.The painting, which uses a palette of gray, black, and white, is known as one of the most moving and powerful anti-war paintings in history.Standing at 3.49 metres (11 ft 5 in) tall and 7.76 metres (25 ft 6 in) wide, the large mural shows the suffering of people, animals, and buildings wrenched by violence and chaos.","itemURL":"http:\/\/www.pablopicasso.org\/guernica.jsp","itemImage":"http:\/\/10.0.3.2\/image_folder\/Guernica.png"}],"success":1}
记录Cat错误:
05-25 07:03:18.036 1249-1264/com.cloudlionheart.museumsearchapplication E/JSON Parser﹕ Error parsing data org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
05-25 07:03:18.052 1249-1264/com.cloudlionheart.museumsearchapplication E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.NullPointerException
at com.cloudlionheart.museumsearchapplication.DisplaySearchResultsActivity$LoadAllProducts.doInBackground(DisplaySearchResultsActivity.java:146)
at com.cloudlionheart.museumsearchapplication.DisplaySearchResultsActivity$LoadAllProducts.doInBackground(DisplaySearchResultsActivity.java:121)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:856)
05-25 07:03:18.648 1249-1249/com.cloudlionheart.museumsearchapplication E/WindowManager﹕ Activity com.cloudlionheart.museumsearchapplication.DisplaySearchResultsActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{5354cb68 V.E..... R......D 0,0-729,192} that was originally added here
android.view.WindowLeaked: Activity com.cloudlionheart.museumsearchapplication.DisplaySearchResultsActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{5354cb68 V.E..... R......D 0,0-729,192} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:354)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:216)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:281)
at com.cloudlionheart.museumsearchapplication.DisplaySearchResultsActivity$LoadAllProducts.onPreExecute(DisplaySearchResultsActivity.java:133)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at com.cloudlionheart.museumsearchapplication.DisplaySearchResultsActivity.onCreate(DisplaySearchResultsActivity.java:64)
at android.app.Activity.performCreate(Activity.java:5104)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:0)
问题是你正在使用itemHistoricalPeriod,因为它是itemHistoricPeriod