[英]Post data from Android app to PHP web service
我遇到了一個非常奇怪的錯誤。 僅當我定義nameValuePairs.add(new BasicNameValuePair(“ country”,“ USA”))時,下面的方法才能夠將數據發布到我的PHP Web服務並檢索JSON編碼的數據。 但是,如果我使用String變量country而不是“ USA”,那么我將從Web服務中獲取null。 我檢查了String country的值,它不為null。 下面是我的代碼
我的String國家在這里定義:
public class Countries extends SupportMapFragment implements
LocationListener, LocationSource
{
private GoogleMap map;
private OnLocationChangedListener mListener;
private LocationManager locationManager;
double mLatitude = 0;
double mLongitude = 0;
String country = "";
.......
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
.......
}
字符串國家/地區通過Bundle對象從先前的活動中獲取價值。 該值不為空
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View root = super.onCreateView(inflater, container, savedInstanceState);
Bundle bundle = new Bundle();
bundle = getArguments();
if(bundle == null)
Toast.makeText(getActivity(), "Country is NULL",
Toast.LENGTH_LONG).show();
else
{
country = getArguments().getString("countryName");
}
map = getMap();
return root;
}
這是我的Post數據方法。
private String postCountryType()
{
String responseStr = "";
try
{
// url where the data will be posted
String postReceiverUrl = "http://.../country.php";
// HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
// add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("country", country));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
if(resEntity != null)
{
responseStr = EntityUtils.toString(resEntity).trim();
// you can add an if statement here and do other actions based
// on the response
}
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return responseStr;
}
當我使用String變量country而不是將數據“ USA”直接傳遞到新的BasicNameValuePair中時,responsStr返回我為null。
我嘗試將新的BasicNameValuePair(“ country”,country)修改為新的BasicNameValuePair(“ country”,country.toString())以及new BasicNameValuePair(“ country”,country +“”),但是不幸的是,兩者技巧不起作用。
其他信息如果我定義String country =“ USA”,但是,在onCreateView內,實際上通過getArguments將值“ Japan”分配給了國家。 BasicNameValuePair(“ country”,country)將忽略值“ Japan”,但使用原始值“ USA”。
任何人都知道為什么會發生這種奇怪的事情嗎?
提前致謝。
country
可能不是null,但是您是否檢查了它是否為空字符串""
? 這就是在Countries
類中初始化的內容。 我將執行Log.d("debugging", country)
,並檢查LogCat以查看在創建NameValuePair
國家/地區實際存在的內容。
問題解決了。 我用onActivityCreated()代替了onCreate()。 根據片段的生命周期,將在片段onActivityCreated()之前檢索String country的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.