为什么AsyncTask总是返回相同的响应?

时间:2014-09-05 20:57:12

标签: php android listview android-asynctask

我有这个代码调用一个用json回复的php脚本。 json用于显示为listview。 问题是,即使这些数据在php脚本连接的数据库中不再存在,下面的代码总是给我相同的json。

我遵循了本指南 http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/

但我无法弄清楚运行时会发生什么。 我希望有人可以帮助我。

public class ShiftListFragment extends ListFragment {

// Progress Dialog
private static ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> productsList;

// url to get all products list
private static String url_all_products = "http://www.changeshifts.netsons.org/android_connect/get_all_shifts.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_AVAILABLE_SHIFTS = "Available shifts";
private static final String TAG_IDSHIFT = "shift id";
private static final String TAG_DATE = "date";
private static final String TAG_SHIFT = "shift";
private static final String TAG_START_LOCATION = "start location";
private static final String TAG_BEGIN = "begin";
private static final String TAG_END = "end";
private static final String TAG_IDENTIFICATION_NUMBER = "identification number";

// products JSONArray
JSONArray products = null;
// Custom adapter to view list of shifts
private CustomAdapter adapter;

/**
 * The serialization (saved instance state) Bundle key representing the
 * activated item position. Only used on tablets.
 */
private static final String STATE_ACTIVATED_POSITION = "activated_position";

/**
 * The fragment's current callback object, which is notified of list item
 * clicks.
 */
private Callbacks mCallbacks = sDummyCallbacks;

/**
 * The current activated item position. Only used on tablets.
 */
private int mActivatedPosition = ListView.INVALID_POSITION;

/**
 * A callback interface that all activities containing this fragment must
 * implement. This mechanism allows activities to be notified of item
 * selections.
 */
public interface Callbacks {
    /**
     * Callback for when an item has been selected.
     */
    public void onItemSelected(String id);
}

/**
 * A dummy implementation of the {@link Callbacks} interface that does
 * nothing. Used only when this fragment is not attached to an activity.
 */
private static Callbacks sDummyCallbacks = new Callbacks() {
    @Override
    public void onItemSelected(String id) {
    }
};

/**
 * Mandatory empty constructor for the fragment manager to instantiate the
 * fragment (e.g. upon screen orientation changes).
 */
public ShiftListFragment() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Hashmap for ListView
    productsList = new ArrayList<HashMap<String, String>>();
 // Loading products in Background Thread
    new LoadAllProducts().execute();



}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    // Restore the previously serialized activated item position.
    if (savedInstanceState != null
            && savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) {
        setActivatedPosition(savedInstanceState
                .getInt(STATE_ACTIVATED_POSITION));
    }
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    // Activities containing this fragment must implement its callbacks.
    if (!(activity instanceof Callbacks)) {
        throw new IllegalStateException(
                "Activity must implement fragment's callbacks.");
    }

    mCallbacks = (Callbacks) activity;
}

@Override
public void onDetach() {
    super.onDetach();

    // Reset the active callbacks interface to the dummy implementation.
    mCallbacks = sDummyCallbacks;
}

@Override
public void onListItemClick(ListView listView, View view, int position,
        long id) {
    super.onListItemClick(listView, view, position, id);

    // Notify the active callbacks interface (the activity, if the
    // fragment is attached to one) that an item has been selected.
    mCallbacks.onItemSelected(productsList.get(position).get(TAG_IDSHIFT));
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    if (mActivatedPosition != ListView.INVALID_POSITION) {
        // Serialize and persist the activated item position.
        outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition);
    }
}

/**
 * Turns on activate-on-click mode. When this mode is on, list items will be
 * given the 'activated' state when touched.
 */
public void setActivateOnItemClick(boolean activateOnItemClick) {
    // When setting CHOICE_MODE_SINGLE, ListView will automatically
    // give items the 'activated' state when touched.
    getListView().setChoiceMode(
            activateOnItemClick ? ListView.CHOICE_MODE_SINGLE
                    : ListView.CHOICE_MODE_NONE);
}

private void setActivatedPosition(int position) {
    if (position == ListView.INVALID_POSITION) {
        getListView().setItemChecked(mActivatedPosition, false);
    } else {
        getListView().setItemChecked(position, true);
    }

    mActivatedPosition = position;
}

/**
 * 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(getActivity());
        pDialog.setMessage("Loading Shifts. 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_all_products, "GET", params);

        // Check your log cat for JSON reponse
        Log.d("All Products: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // products found
                // Getting Array of Products
                products = json.getJSONArray(TAG_AVAILABLE_SHIFTS);
                productsList = new ArrayList<HashMap<String,String>>();

                // looping through All Products
                for (int i = 0; i < products.length(); i++) {
                    JSONObject c = products.getJSONObject(i);

                    // Storing each json item in variable
                    // String idShift = c.getString(TAG_IDSHIFT);
                    String date = c.getString(TAG_DATE);
                    String shift = c.getString(TAG_SHIFT);
                    String location = c.getString(TAG_START_LOCATION);
                    String begin = c.getString(TAG_BEGIN);
                    String end = c.getString(TAG_END);
                    String sn = c.getString(TAG_IDENTIFICATION_NUMBER);

                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    // map.put(TAG_IDSHIFT, idShift);
                    map.put(TAG_DATE, date);
                    map.put(TAG_SHIFT, shift);
                    map.put(TAG_START_LOCATION, location);
                    map.put(TAG_BEGIN, begin);
                    map.put(TAG_END, end);
                    map.put(TAG_IDENTIFICATION_NUMBER, sn);

                    // adding HashList to ArrayList
                    productsList.add(map);
                }
            } else {
                // no Shifts found
                // Launch Add New product Activity
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        super.onPostExecute(file_url);
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread            
        getActivity().runOnUiThread(new Runnable(){
            public void run(){
                /**
                 * Updating parsed JSON data into ListView
                 * */

                adapter = new CustomAdapter(getActivity(), R.layout.list_item, productsList);
                setListAdapter(adapter);


            }   

        });

    }

}

}

0 个答案:

没有答案