向一个URL发送咨询,但JSON返回始终为null

时间:2014-02-18 14:43:04

标签: android mysql json

我有一个问题,我尝试在我的服务器中提取一个PHP的信息,但响应始终为null

我附上我接下来使用的代码,我是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();
}



}

1 个答案:

答案 0 :(得分:0)

在android中,不允许在主线程上执行网络操作:

你不能这样做:

// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
<{1>}中的

,您必须将其放在asyncTask


你可以像这样快速而肮脏(未经过测试!):

onCreate