我从一个Activity请求一个PHP文件时遇到了一些问题。 它似乎通常从JSON检索数据,但毕竟它显示了那里的旧数据。 我的意思是,例如,我请求获取表中所有行的名称(MySQL)。 它在第一个实例中收费没有任何错误,但如果我更改表中的行,JSON仍将检索旧的行数据。我不知道,似乎它被保存在caché的某个地方,但我不知道出了什么问题。
这是我在活动中的一个JSON请求(它发生在我使用JSON的所有活动中),它必须返回所有行的数组并用它们创建一个列表:
public class EventsListActivity extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> EventsList;
// url to get all products list
final private static String url_all_events = "http://easee.es/android_test/get_event_list.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_EVENTS = "events";
private static final String TAG_ID_CAT = "id_cat";
private static final String TAG_TITLE = "title";
private static final String TAG_FINISHED = "finished";
private static final String TAG_NUM_PPL = "num_ppl";
// products JSONArray
JSONArray events = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_list);
// Hashmap for ListView
EventsList = new ArrayList<HashMap<String, String>>();
// Cargando eventos en el background
new LoadAllEvents().execute();
//Click en el botón add_event
ImageView add_event = (ImageView) findViewById(R.id.add_event);
add_event.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Si presionamos el botón añadir...
Intent i = new Intent(getApplicationContext(), Add_EventActivity.class);
startActivity(i);
}
});
// Cargar listview
ListView lv = getListView();
// Al seleccionar un evento
//Abrir el evento...
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String id_cat = ((TextView) view.findViewById(R.id.id_cat)).getText()
.toString();
String num_ppl = ((TextView) view.findViewById(R.id.num_ppl)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
Event_Details.class);
// sending pid to next activity
in.putExtra(TAG_ID_CAT, id_cat);
in.putExtra(TAG_NUM_PPL, num_ppl);
// 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 LoadAllEvents extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EventsListActivity.this);
pDialog.setMessage(getString(R.string.LoadingData_Events));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_events, "GET", params);
// Check your log cat for JSON reponse
Log.d("Todos los eventos: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Events
events = json.getJSONArray(TAG_EVENTS);
// looping through All Events
for (int i = 0; i < events.length(); i++) {
JSONObject c = events.getJSONObject(i);
// Storing each json item in variable
String id_cat = c.getString(TAG_ID_CAT);
String title = c.getString(TAG_TITLE);
String finished = c.getString(TAG_FINISHED);
String num_ppl = c.getString(TAG_NUM_PPL)+" "+ getString(R.string.People_Attending);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID_CAT, id_cat);
map.put(TAG_TITLE, title);
map.put(TAG_FINISHED, finished);
map.put(TAG_NUM_PPL, num_ppl);
// adding HashList to ArrayList
EventsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
/*
Intent i = new Intent(getApplicationContext(),
NewProductActivity.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 events
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
EventsListActivity.this, EventsList,
R.layout.event_row, new String[] { TAG_ID_CAT, TAG_TITLE, TAG_NUM_PPL },
new int[] { R.id.id_cat, R.id.title, R.id.num_ppl });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
这是PHP文件:
<?php
// Incluir la conexión:
require_once 'db_connect.php';
// Creamos el array que pasaremos por JSON
$response = array();
// Obtenemos todos los eventos de la tabla "eventos"
$result = $con->query('SELECT * FROM events');
$num_rows = mysqli_num_rows($result);
// Comprobamos si existe (hay al menos un resultado)
if (mysqli_num_rows($result) > 0) {
// El array donde almacenaremos los datos del evento
$response['events'] = array();
// Creamos un bucle mientras hayan resultados, es decir, eventos disponibles.
while ($row = mysqli_fetch_array($result)) {
// Datos sobre el evento para la Aplicación
$event = array();
$event['id_cat'] = $row['id_cat'];
$event['title'] = $row['title'];
$event['finished'] = $row['finished'];
$event['group_id'] = $row['group_id'];
$event['num_ppl'] = $row['num_ppl'];
// Obtener el número de participantes
$search_group = mysqli_fetch_array($con->query("SELECT *FROM groups WHERE `group_id` =
'".$event['group_id']."'"));;
$participantes = explode(",", $search_group['participants']);
$event["num_ppl"] = count($participantes);
// Crear el array
array_push($response['events'], $event);
}
// Exito
$response['success'] = 1;
// Enviamos la respuesta por JSON
echo json_encode($response);
} else {
// No se ha encontrado ningún evento.
$response['success'] = 0;
$response['message'] = "Todavía no has creado ningún evento.";
// Devolvemos el error por JSON
echo json_encode($response);
}
?>
答案 0 :(得分:0)
尝试我使用的这种方法。我不知道JSONObject json = jParser.makeHttpRequest(url_all_events, "GET", params);
是如何运作的。
@Override
protected Void doInBackground(String... params) {
HttpPost postMethod = new HttpPost("http://easee.es/android_test/get_event_list.php");
String response;
try {
response = new DefaultHttpClient().execute(postMethod, new BasicResponseHandler());
} catch (ClientProtocolException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
JSONArray jsonArray;
try {
jsonArray = new JSONArray(response);
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
希望有所帮助