Java/Android JSON 请求不更新收到的数据

标签 java php android mysql json

我在从 Activity 请求 PHP 文件时遇到了一些问题。 它似乎可以正常地从 JSON 检索数据,但毕竟,它显示了那里的旧数据。 我的意思是,例如,我请求获取表(MySQL)中所有行的名称。 它在第一个实例中收费,没有任何错误,但如果我更改表中的行,JSON 仍将检索旧的行数据。我不知道,好像它被保存在缓存中的某个地方,但我不知道出了什么问题。

这是我在 Activity 中的 JSON 请求之一(它发生在我使用 JSON 的所有 Activity 中),它必须返回所有行的数组并用它们创建一个列表:

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);
}
?>

最佳答案

试试我用的这个方法。我不知道 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;
        }
}

希望对你有帮助

关于Java/Android JSON 请求不更新收到的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26022654/

相关文章:

java - 定制标题栏

php - 检测哪个脚本导致服务器过载 - apache + php

php - Mysql删除行-安全问题

php - 完善我的 Eloquent 查询 (Laravel)

android - 如何更改 Android 模拟器的电池设置?

java - Python 客户端不接收来自 Spring websocket 服务器的消息

java - 如何在 Java 应用程序中设置菜单栏的键盘快捷键?

Java - 如何获得 K 小时偏移的时区?

android - 使用 aSmack 为 XMPP 群聊创建 MUC 房间时发生 ClassCastException

java - JAX RS 获取对象列表