安卓设备总是发出相同的HTTP请求,还是服务器总是给出相同的响应?这怎么可能



我试图向服务器发出POST HTTP请求,但每次我都会得到相同的json响应,就像服务器总是以相同的方式响应一样
我有一个GET,它从服务器加载所有市政当局的数据,然后是另一个活动,它获取用户选择的市政当局,并且应该返回适当的机构信息详细响应。但我得到了什么?我在上一个活动中获得了上一个HTTP get请求的上一个Json响应。。。。这怎么可能???我甚至更改了URL并给它起了一个假名字,但我得到的仍然是相同的get响应。。。

我不知道为什么安卓或我的服务器会这样。

这是第一个活动:

public class IMieiDati extends ListActivity {
AutoCompleteTextView municipalityEditTxt;
EditText yearEditTxt;
EditText versed_moneyEditTxt;
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
List<HashMap<String, String>> ListaComuni;
List<String> Anni;
private static final String URL_ANDROID_APP_LISTENER = "http://xxx.xxx.xxx.xxx/android/AndroidAppListener.php";
// GET request infos
private static final String GET_QUERY_STRING[] = {"all_municipalities", "true"};
private static final String TAG_SUCCESS = "success";
private static final String TAG_COMUNI = "municipalities";
private static final String TAG_ANNI = "years";
private static final String TAG_COMUNE_NOME = "name";
private static final String TAG_PROVINCIA_NOME = "provinceName";
private static final String TAG_SIGLA_PROVINCIA = "sign";
private static final String TAG_REGIONE_NOME = "regionName";
// POST request infos to pass to the HomeComune Activity with the putExtra() Intent method
private static final String TAG_COMUNE = "mun_name";
private static final String TAG_ANNO = "year";
private static final String TAG_VERSED_MONEY = "versed_money";
// municipalities JSON Array
JSONArray Comuni = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_imiei_dati);
    // TxtViews
    municipalityEditTxt = (AutoCompleteTextView) findViewById(R.id.municipality);
    yearEditTxt = (EditText) findViewById(R.id.year);
    versed_moneyEditTxt = (EditText) findViewById(R.id.versed_money);
    // initializing empty collections
    ListaComuni = new ArrayList<HashMap<String, String>>();
    Anni = new ArrayList<String>();
    // checking whether the network is not available
    if (!isNetworkAvailable()) {
        Log.d("Message", "No network connection.");
        System.exit(1);
    }
    new LoadAllMunicipalitiesThread().execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.imiei_dati, menu);
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()) {
        case R.id.action_forward:
                municipalityHome();
                return true;
        case R.id.action_settings:
                openSettings();
                return true;
        default: 
                return super.onOptionsItemSelected(item);
    }
}
private void municipalityHome() {
    // Recovering the values of the EditText items
    String municipalityName = municipalityEditTxt.getText().toString();
    String year = yearEditTxt.getText().toString();
    String versedMoney = versed_moneyEditTxt.getText().toString();
    // Checking whether the user has compiled all the fields
    // 1) Municipality. At least 2 chars, should be in the ListaComuni
    if (municipalityName.length()<2) {
        Toast toast = Toast.makeText(this, "Inserisci un nome di comune valido.", Toast.LENGTH_SHORT);
        toast.show();
        return;
    }
    municipalityName = municipalityName.trim();
    boolean equals = false;
    for (HashMap<String, String> map : ListaComuni) {
        String pattern = map.get(TAG_COMUNE_NOME);
        if (pattern.equalsIgnoreCase(municipalityName)) {
            municipalityName = pattern;
            equals = true;
        }
    }
    if (!equals) {
        Toast toast = Toast.makeText(this, "Inserisci un nome di comune valido.", Toast.LENGTH_SHORT);
        toast.show();
        return;
    }
    // 2) Year. Must be selected from the pop up. Must be in the range of the selectable years
    try {
        int yearInt = Integer.parseInt(year);
        int yearIntBottom = Integer.parseInt(Anni.get(0).toString());
        int yearIntTop = Integer.parseInt(Anni.get(Anni.size()-1).toString());
        if (yearInt < yearIntBottom || yearInt > yearIntTop) {
            Toast toast = Toast.makeText(this, "Inserisci un anno valido.", Toast.LENGTH_LONG);
            toast.show();
            yearEditTxt.setText("");
            return;
        }
    } 
    catch (NumberFormatException e) {
        Toast toast = Toast.makeText(this, "Inserisci un anno valido.", Toast.LENGTH_SHORT);
        toast.show();
        yearEditTxt.setText("");
        return;
    }
    // 3) Versed Money. Must be at least bigger than 1.
    try {
        float versedMoneyFloat = Float.parseFloat(versedMoney);
        if (versedMoneyFloat < 1) {
            Toast toast = Toast.makeText(this, "Inserisci un importo valido." , Toast.LENGTH_SHORT);
            toast.show();
            return;
        }
    }
    catch (NumberFormatException e) {
        Toast toast = Toast.makeText(this, "Inserisci un importo valido.", Toast.LENGTH_SHORT);
        toast.show();
        return;
    }
    // defining the Intent  
    Intent open = new Intent(getApplicationContext(),HomeComune.class);  
    // put extra data
    open.putExtra(TAG_COMUNE, municipalityName);
    open.putExtra(TAG_ANNO, year);
    open.putExtra(TAG_VERSED_MONEY, versedMoney);
    startActivity(open);  
}
private void openSettings() {
    Toast toast = Toast.makeText(this, "Settings...", Toast.LENGTH_LONG);
    toast.show();
}

 // Background Async Task to Load all municipalities by making an HTTP GET Request
class LoadAllMunicipalitiesThread extends AsyncTask<String, String, String> {
    // Before starting background thread Show Progress Dialog
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(IMieiDati.this);
        pDialog.setMessage("Caricamento...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    protected String doInBackground(String... strings ){
        Log.d("ilMioComune", "Caricamento comuni");
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair(GET_QUERY_STRING[0], GET_QUERY_STRING[1]));
        JSONObject json = jParser.makeHttpRequest(URL_ANDROID_APP_LISTENER, "GET", params);
        Log.d("JSON GET comuni", json.toString());
        try {
            int success = json.getInt(TAG_SUCCESS);
            // getting all municipalities
            if (success == 1) {
                JSONArray JSONmunicipalities = json.getJSONArray(TAG_COMUNI);
                // foreach Municipality JSONObject
                for (int i = 0; i < JSONmunicipalities.length(); i++) {
                    JSONObject JSONmunicipality = JSONmunicipalities.getJSONObject(i);
                    HashMap<String, String> map = new HashMap<String, String>();
                    // foreach Municipality's attributes
                    Iterator<?> MunicipalityKeys = JSONmunicipality.keys();
                    while (MunicipalityKeys.hasNext()) {
                        String MunicipalityKey = (String)MunicipalityKeys.next();
                        String MunicipalityValue = JSONmunicipality.getString(MunicipalityKey);
                        map.put(MunicipalityKey, MunicipalityValue);
                    }
                    // add Municipality HashMap to ListaComuni
                    ListaComuni.add(map);
                }
                // getting all years
                JSONArray JSONyears = json.getJSONArray(TAG_ANNI);
                // foreach Year JSONArray
                for (int i = 0; i < JSONyears.length(); i++) {
                    Anni.add(JSONyears.getString(i));
                }
            }
            else {
                // no municipalities or years were found
            }
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
    protected void onPostExecute(String file_url) {
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        IMieiDati.this, ListaComuni,
                        R.layout.municipality_list_item, new String[] { 
                                TAG_COMUNE_NOME,
                                TAG_SIGLA_PROVINCIA,
                                TAG_PROVINCIA_NOME,
                                TAG_REGIONE_NOME
                                },
                        new int[] { R.id.name,
                                    R.id.sign,
                                    R.id.provinceName,
                                    R.id.regionName});
                // getting a years CharSequence array from Anni List.
                final CharSequence[] years = Anni.toArray(new CharSequence[Anni.size()]);
                // hide cursor in yearTxtView
                yearEditTxt.setCursorVisible(false);
                // yearTxtView onFocus Listener
                yearEditTxt.setOnTouchListener(new OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        yearEditTxt.requestFocus();
                        // Year pop up
                        AlertDialog.Builder builder = new AlertDialog.Builder(IMieiDati.this);
                        builder.setTitle("Seleziona un anno");
                        builder.setItems(years, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // the user clicked on years[which]
                                yearEditTxt.setText(years[which]);
                                // if you want the cursor at the end of the string:
                                // yearTxtView.setSelection(yearTxtView.length());
                            }
                        });
                        if (event.getAction() == MotionEvent.ACTION_UP) {
                            // what to if user touches/taps on the EditText box
                            builder.show();
                        }
                        return true;
                    }
                });
                // updating listview
                setListAdapter(adapter);
            }
        });
    }
}
private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

}

GET?all_municipalities=true按预期工作,我得到了JSON:

JSON GET municipalities (2592): {"success":1,"years":["2013","2014"],"municipalities":[{"regionName":"Emilia-Romagna","sign":"(FC)","provinceName":"Forlì-Cesena","name":"Cesena"},{"regionName":"Emilia-Romagna","sign":"(FC)","provinceName":"Forlì-Cesena","name":"Forlì"},{"regionName":"Emilia-Romagna","sign":"(PR)","provinceName":"Parma","name":"Parma"},{"regionName":"Emilia-Romagna","sign":"(RA)","provinceName":"Ravenna","name":"Ravenna"},{"regionName":"Emilia-Romagna","sign":"(RN)","provinceName":"Rimini","name":"Riccione"},{"regionName":"Emilia-Romagna","sign":"(RN)","provinceName":"Rimini","name":"Rimini"},{"regionName":"Emilia-Romagna","sign":"(RA)","provinceName":"Ravenna","name":"Russi"}]}

现在是第二个活动,当用户向服务器发送POST数据时:

public class HomeComune extends Activity {
// widgets 
Button infoListButton;
/////////////////////////////////////////////
List<String> masterList;
Map<String, List<String>> detailMap; 
ExpandableListView expListView;
String municipalityName;
String year;
String versedMoney;
private ProgressDialog pDialog;
JSONParser jParser = new JSONParser();
// the context of this activity. Will be used when creating the institutional info dialog
private Context thisContext = this; 
// POST request information
private static String url = "http://xxx.xxx.xxx.xxx/android/AndroidListener2.php";
private static final String TAG_COMUNE = "mun_name";
private static final String TAG_ANNO = "year";
private static final String TAG_VERSED_MONEY = "versed_money";
private static final String TAG_SUCCESS = "success";
// JSON data retrieving information
private static final String JSON_INSTITUTIONAL_INFOS_LABEL = "institutional_infos"; 
private static final String JSON_MASTER_LABEL = "master";
private static final String JSON_DETAIL_LABEL = "detail";
private static final String JSON_MASTER_DETAIL_NAME_LABEL = "name";

//private静态最终字符串JSON_DETAIL_NUMBER_LABEL="数字";

// institutional info JSON Array which will contain the Master and Detail data that will come from the POST request
JSONArray institutionalInfo = null;
// institutional info Hash Map for the Master and Detail Hash Map
HashMap<String, List<HashMap<String, String>>> institutionalInfoCollection;
@Override 
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home_comune);
    createGroupList();
    createCollection();

    Intent myDataIntent = this.getIntent();
    // getting the municipality name, the year and the versed money from the prev. intent
    this.municipalityName = myDataIntent.getStringExtra(TAG_COMUNE);
    this.year = myDataIntent.getStringExtra(TAG_ANNO);
    this.versedMoney = myDataIntent.getStringExtra(TAG_VERSED_MONEY);
    // POST request Async Task
    new LoadAllMunicipalityInfoThread().execute();
    infoListButton = (Button) findViewById(R.id.infoButton);
}
class LoadAllMunicipalityInfoThread extends AsyncTask<String, String, String> {
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(HomeComune.this);
        pDialog.setMessage("Caricamento...");
        pDialog.setIndeterminate(true);
        pDialog.setCancelable(false);
        pDialog.show();
    }
    protected String doInBackground(String... args) {
        Log.d("ilMioComune", "Caricamento Info Istituzionali");
        // building the HTTP POST request
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair(TAG_COMUNE, municipalityName));
        params.add(new BasicNameValuePair(TAG_ANNO, year));
        params.add(new BasicNameValuePair(TAG_VERSED_MONEY, versedMoney));
        JSONObject json = jParser.makeHttpRequest(url, "POST", params);
        Log.d("JSON POST info istituzionali", json.toString());
        try {
            int success = json.getInt(TAG_SUCCESS);
            // getting all institutional infos of a municipality
            if (success == 1) {
                institutionalInfo = json.getJSONArray(JSON_INSTITUTIONAL_INFOS_LABEL);
                // foreach institutional info JSONObject
                for (int i = 0; i<institutionalInfo.length(); i++) {
                    JSONObject JSONinstitutionalInfo = institutionalInfo.getJSONObject(i);
                    JSONObject JSONmasterEntry = JSONinstitutionalInfo.getJSONObject(JSON_MASTER_LABEL);
                    String masterEntryName = JSONmasterEntry.getString(JSON_MASTER_DETAIL_NAME_LABEL);
                    masterList.add(masterEntryName);
                    JSONArray JSONdetails = JSONmasterEntry.getJSONArray(JSON_DETAIL_LABEL);
                    List<String> detailNames = new ArrayList<String>();
                    // foreach detail in JSONdetails
                    for (int j = 0; j<JSONdetails.length(); j++) {
                        JSONObject JSONdetailEntry = JSONdetails.getJSONObject(j);
                        String detailEntryName = JSONdetailEntry.getString(JSON_MASTER_DETAIL_NAME_LABEL);
                    //  String detailEntryNumber = JSONdetailEntry.getString(JSON_DETAIL_NUMBER_LABEL);
                        detailNames.add(detailEntryName);
                    }
                    detailMap.put(masterEntryName, detailNames);
                }
            }
            else {
                // no institutional infos associated to the municipality in the selected year were found
            }
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
    protected void onPostExecute(String file_url) {
        pDialog.dismiss();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                infoListButton.setOnClickListener(new OnClickListener() {
                     @Override
                      public void onClick(View arg0) {
                        // custom dialog
                        final Dialog dialog = new Dialog(thisContext);
                        dialog.setContentView(R.layout.institutional_info_custom_list);
                        dialog.setTitle("Info");
                        // getting the window manager and changing the dialog position
                        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
                        params.gravity = Gravity.TOP | Gravity.LEFT;
                        params.y = 80;
                        dialog.getWindow().setAttributes(params);
                        // dialog width and height.
                        dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);   
                        // inflating the custom institutional expandable list layout
                        LayoutInflater li = (LayoutInflater) thisContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                        View v = li.inflate(R.layout.institutional_info_custom_list, null, false);
                        dialog.setContentView(v);
                        expListView = (ExpandableListView) v.findViewById(android.R.id.list);
                        final ExpandableListAdapter expListAdapter = new ExpandableListAdapter(HomeComune.this, masterList, detailMap);
                        expListView.setAdapter(expListAdapter);
                        dialog.show();
                      }
                });
            }
        });         
    }
}


 }

我没有得到正确的JSONPost响应,而是得到了前面的get。。。。即使我更改了侦听器正在等待POST请求的.php脚本的名称。。。。

这怎么可能???我简直不敢相信自己。。。也许我哪里错了。。。但在.php AndroidListener2.php中,我检查了这些变量:

if (isset($_POST['mun_name']) && isset($_POST['year']) && isset($_POST['versed_money']))
{
        // recover the proper data and send the JSON response ...
    }

知道吗?

在添加新数据之前,您必须擦除或清除Json和所有正在使用的ArrayLists中的所有数据。

你可以通过以下方法做到这一点:

protected void onPreExecute() {
        super.onPreExecute();
       json.clear();
       ListaComuni.clear();
       detailMap.clear();
     // and all the HashMap or ArrayLists you declared and want to put in them new data
    }

你可以试试这个。

首先,将以下标志添加到您的意图"打开">

open.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

然后在你的另一个活动中放入你的代码的这一部分

createGroupList();
createCollection();

Intent myDataIntent = this.getIntent();
// getting the municipality name, the year and the versed money from the prev. intent
this.municipalityName = myDataIntent.getStringExtra(TAG_COMUNE);
this.year = myDataIntent.getStringExtra(TAG_ANNO);
this.versedMoney = myDataIntent.getStringExtra(TAG_VERSED_MONEY);
// POST request Async Task
new LoadAllMunicipalityInfoThread().execute();
infoListButton = (Button) findViewById(R.id.infoButton);

内部一种新方法

@Override
protected void onNewIntent(Intent intent) {
}

问题是,当您使用this.getIntent();时,它会检索用于启动Activity的第一个Intent,而不是新的。这导致它总是从使用的第一个Intent中检索数据,因此Extras总是相同的。

最新更新