我正在尝试向服务器发出POST HTTP请求,但每次我总是得到相同的json响应,就像服务器总是以相同的方式响应... 我有一个GET,它从服务器加载所有市政数据,然后是另一个活动,它取决于用户已选择的市政当局,并应返回适当的机构信息详细响应。但是我得到了什么?我在之前的活动中获得了之前的HTTP get请求的先前Json响应....这怎么可能?我甚至更改了URL并给它一个假名,但我得到的仍然是相同的GET响应......
我不知道为什么android或我的服务器表现得像这样。
这是第一项活动:
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 static final String JSON_DETAIL_NUMBER_LABEL =“number”;
// 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();
}
});
}
});
}
}
}
而不是获得正确的JSON Post响应,我获得了之前的GET ....即使我已经更改了.php脚本的名称,其中侦听器正在等待POST请求....
怎么可能???我无法相信自己...也许我错了...但是在.php AndroidListener2.php中我检查了那些变量:
if (isset($_POST['mun_name']) && isset($_POST['year']) && isset($_POST['versed_money']))
{
// recover the proper data and send the JSON response ...
}
有什么想法吗?
答案 0 :(得分:1)
在添加新数据之前,您必须擦除或清除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
}
答案 1 :(得分:0)
你可以试试这个。
首先将以下标志添加到您的意图“打开”
open.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
然后在你的其他Activity中放入你的代码的这部分
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();
时,它会检索用于启动Intent
的第一个Activity
,而不是新的Intent
。这使得它总是从使用的第一个{{1}}中检索数据,因此Extras总是相同的。