2014-09-24 53 views
0

我从一个活动请求PHP文件时遇到了一些问题。 它似乎通常从JSON中检索数据,但是最终它会显示旧数据。 有了这个我的意思是,例如我做了一个请求来获取表(MySQL)中的所有行的名称。 它在第一次没有任何错误的情况下收费,但如果我更改表中的行,JSON仍然会检索旧的行数据。我不知道,看起来好像它被保存在某个地方,但我不知道发生了什么问题。Java/Android JSON请求没有更新收到的数据

这是一个活动我的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

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

希望它可以帮助