我有一个问题,我尝试在我的服务器中提取一个 php 的信息,但响应始终为空
我附上接下来使用的代码,我是 Android 新手,但我认为 PC 不会向应用程序发送任何内容
public class MainActivity extends Activity {
//URL to get JSON Array
private static String url = "http://10.69.44.108/odin/mobile/json/";
//JSON Node Names
private static final String TAG_USER = "user";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
JSONArray user = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Creating new JSON Parser
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting JSON Array
user = json.getJSONArray(TAG_USER);
JSONObject c = user.getJSONObject(0);
// Storing JSON item in a Variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
//Importing TextView
final TextView uid = (TextView)findViewById(R.id.uid);
final TextView name1 = (TextView)findViewById(R.id.name);
final TextView email1 = (TextView)findViewById(R.id.email);
//Set JSON Data in TextView
uid.setText(id);
name1.setText(name);
email1.setText(email);
} catch (JSONException e) {
e.printStackTrace();
}
}
最佳答案
在 android 中,不允许在主线程上执行网络操作:
你不能这样做:
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
在onCreate
中,您必须将其放入 asyncTask 中.
你可以像这样快速而肮脏地完成它(未经测试!):
//Importing TextView
final TextView uid = (TextView)findViewById(R.id.uid);
final TextView name1 = (TextView)findViewById(R.id.name);
final TextView email1 = (TextView)findViewById(R.id.email);
new AsyncTask<String, JSONObject, JSONObject>(){
@Override
protected JSONObject doInBackground(String ... Urls) {
// Creating new JSON Parser
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = new JSONObject();
try {
json = jParser.getJSONFromUrl(Urls[]);
} catch(JSONException e) {
// do somthing
return null
}
return json;
}
protected void onPostExecute(JSONObject json) {
try {
// Getting JSON Array
user = json.getJSONArray(TAG_USER);
JSONObject c = user.getJSONObject(0);
// Storing JSON item in a Variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String email = c.getString(TAG_EMAIL);
//Set JSON Data in TextView
uid.setText(id);
name1.setText(name);
email1.setText(email);
} catch (JSONException e) {
e.printStackTrace();
}
}
}.execute(url);
关于android - 向一个 url 发送咨询,但 JSON 返回始终为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21857133/