dongzhouji4021 2014-09-24 17:07
浏览 44

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

I've got a little problem with requesting to a PHP file from an Activity. It seems to retrieve the data normally from the JSON, but afterall, it shows the older data it was there. With this I mean, for example I do a request to get the name of all the rows in a table (MySQL). It charges in first instance without any error, but if I change the rows in the table, the JSON will still retrieve the old row data. I don't know, it seems like if it was saved somewhere in a caché, but I don't have any clue of what's going wrong.

This is one of my JSON requests in an activity (it happens in all the activities in which I use JSON), it has to return an Array of all the rows and make a list with them:

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

        }

    }
}

here's the PHP file:

<?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);
}
?>
  • 写回答

1条回答 默认 最新

  • doutui6241 2014-09-24 17:34
    关注

    Try this method that I use. I do not know how JSONObject json = jParser.makeHttpRequest(url_all_events, "GET", params); works.

    @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;
            }
    }
    

    Hope it helps

    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测