我遇到了一个非常奇怪的错误。仅当我定义nameValuePairs.add(new BasicNameValuePair("country", "USA")); 时,以下方法才能将数据发布到我的 PHP Web 服务并检索 JSON 编码数据。但是,如果我使用字符串变量 country 而不是“USA”,我将从我的 Web 服务中得到 null。我检查了字符串国家的值,它不为空。下面是我的代码
我的字符串国家在这里定义:
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;
}
当我使用字符串变量 country 而不是将数据“USA”直接传递到新的 BasicNameValuePair 时,responsStr 返回 null。
我尝试将new BasicNameValuePair("country", country)修改为new BasicNameValuePair("country", country.toString())以及new BasicNameValuePair("country", country + "") 但不幸的是,两者技巧没有奏效。
附加信息 如果我定义 String country = "USA",但是,在 onCreateView 中,值 "Japan" 实际上是通过 getArguments 分配给国家的。BasicNameValuePair("country", country) 将忽略值“Japan”,但使用原始值“USA”。
有人知道为什么会发生这种奇怪的事情吗?
提前致谢。