0

我正在研究 JSON 数据解析,我是新手,因为我是第一次进行 JSON 解析。我尝试了这个链接中的一个例子。它运行良好。但是当我根据需要更改示例代码时出现错误。我更改的代码如下:

MainActivity.Java

public class MainActivity extends ListActivity {

private ProgressDialog pDialog;

// URL to get contacts JSON
private static String url = "https://123.xxx.x.xxx/DEMO/login_data.php";

// JSON Node names
private static final String TAG_STATUS = "Status";
private static final String TAG_USERNAME = "User Name";
private static final String TAG_PASSWORD = "Admin password";

// contacts JSONArray
JSONArray sampleData = null;

// Hashmap for ListView
ArrayList<HashMap<String, String>> userNamePass;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    userNamePass = new ArrayList<HashMap<String, String>>();

    ListView lv = getListView();

    // Listview on item click listener
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String name = ((TextView) view.findViewById(R.id.name))
                    .getText().toString();
            String cost = ((TextView) view.findViewById(R.id.password))
                    .getText().toString();

            // Starting single contact activity
            Intent in = new Intent(getApplicationContext(),SingleContactActivity.class);
            in.putExtra(TAG_USERNAME, name);
            in.putExtra(TAG_PASSWORD, cost);
            startActivity(in);

        }
    });

    // Calling async task to get json
    new GetContacts().execute();
}

/**
 * Async task class to get json by making HTTP call
 * */
private class GetContacts extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.POST);

        Log.d("Response: ", "> " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                sampleData = jsonObj.getJSONArray(TAG_STATUS);

                // looping through All Contacts
                for (int i = 0; i < sampleData.length(); i++) {
                    JSONObject c = sampleData.getJSONObject(i);

                    String name = c.getString(TAG_USERNAME);
                    String password = c.getString(TAG_PASSWORD);

                    // tmp hashmap for single contact
                    HashMap<String, String> contact = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    contact.put(TAG_USERNAME, name);
                    contact.put(TAG_PASSWORD, password);

                    // adding contact to contact list
                    userNamePass.add(contact);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**
         * Updating parsed JSON data into ListView
         * */
        ListAdapter adapter = new SimpleAdapter(
                MainActivity.this, userNamePass,
                R.layout.list_item, new String[] { TAG_USERNAME, TAG_PASSWORD }, new int[] { R.id.name,
                        R.id.password });

        setListAdapter(adapter);
    }

}
}

服务处理器.Java

public class ServiceHandler {

static String response = null;
public final static int GET = 1;
public final static int POST = 2;

public ServiceHandler() {

}

/*
 * Making service call
 * @url - url to make request
 * @method - http request method
 * */
public String makeServiceCall(String url, int method) {
    return this.makeServiceCall(url, method, null);
}

/*
 * Making service call
 * @url - url to make request
 * @method - http request method
 * @params - http request params
 * */
public String makeServiceCall(String url, int method,
        List<NameValuePair> params) {
    try {
        // http client
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpEntity httpEntity = null;
        HttpResponse httpResponse = null;

        // Checking http request method type
        if (method == POST) {
            HttpPost httpPost = new HttpPost(url);
            // adding post params
            if (params != null) {
                httpPost.setEntity(new UrlEncodedFormEntity(params));
            }

            httpResponse = httpClient.execute(httpPost);

        } else if (method == GET) {
            // appending params to url
            if (params != null) {
                String paramString = URLEncodedUtils
                        .format(params, "utf-8");
                url += "?" + paramString;
            }
            HttpGet httpGet = new HttpGet(url);

            httpResponse = httpClient.execute(httpGet);

        }
        httpEntity = httpResponse.getEntity();
        response = EntityUtils.toString(httpEntity);

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return response;

}
}

SingleContactActivity.Java

public class SingleContactActivity  extends Activity {

// JSON node keys
private static final String TAG_NAME = "name";
private static final String TAG_PASSWORD = "password";
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_single_contact);

    // getting intent data
    Intent in = getIntent();

    // Get JSON values from previous intent
    String name = in.getStringExtra(TAG_NAME);
    String password = in.getStringExtra(TAG_PASSWORD);

    // Displaying all values on the screen
    TextView lblName = (TextView) findViewById(R.id.name_label);
    TextView lblPassword = (TextView) findViewById(R.id.password_label);

    lblName.setText(name);
    lblPassword.setText(password);
}
}

我在运行时遇到的错误:

02-24 17:34:25.190: W/System.err(14285): org.apache.http.conn.ConnectTimeoutException: Connect to /123.xxx.x.xxx:443 timed out
02-24 17:34:25.190: W/System.err(14285):    at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:121)
02-24 17:34:25.190: W/System.err(14285):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:156)
02-24 17:34:25.195: W/System.err(14285):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
02-24 17:34:25.195: W/System.err(14285):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
02-24 17:34:25.195: W/System.err(14285):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:359)
02-24 17:34:25.195: W/System.err(14285):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
02-24 17:34:25.200: W/System.err(14285):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
02-24 17:34:25.200: W/System.err(14285):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
02-24 17:34:25.200: W/System.err(14285):    at com.oi.jsonparsingdemo.ServiceHandler.makeServiceCall(ServiceHandler.java:59)
02-24 17:34:25.205: W/System.err(14285):    at com.oi.jsonparsingdemo.ServiceHandler.makeServiceCall(ServiceHandler.java:34)
02-24 17:34:25.210: W/System.err(14285):    at com.oi.jsonparsingdemo.MainActivity$GetContacts.doInBackground(MainActivity.java:99)
02-24 17:34:25.210: W/System.err(14285):    at com.oi.jsonparsingdemo.MainActivity$GetContacts.doInBackground(MainActivity.java:1)
02-24 17:34:25.215: W/System.err(14285):    at android.os.AsyncTask$2.call(AsyncTask.java:185)
02-24 17:34:25.215: W/System.err(14285):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
02-24 17:34:25.215: W/System.err(14285):    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
02-24 17:34:25.220: W/System.err(14285):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
02-24 17:34:25.220: W/System.err(14285):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
02-24 17:34:25.220: W/System.err(14285):    at java.lang.Thread.run(Thread.java:1019)
02-24 17:34:25.220: D/Response:(14285): > null
02-24 17:34:25.220: E/ServiceHandler(14285): Couldn't get any data from the url
02-24 17:34:25.280: D/CLIPBOARD(14285): Hide Clipboard dialog at Starting input: finished by someone else... !

我在哪里错了,或者我应该遵循哪些步骤才能完成我的任务。请提出您宝贵的建议...

4

2 回答 2

1

您的网址很可能无效。将其更改为适当的 URL。

private static String url = "https://123.xxx.x.xxx/DEMO/login_data.php";

这看起来不像我见过的任何网址......

如果您为 SO 屏蔽了它,请确保通过在 Web 浏览器中键入相同的 URL(包括格式化的字符串)来获得某些信息。确保这一点的最佳方法是在使用它之前立即打印使用的 URL,以确保没有添加任何异常,并且 URL 完全按预期工作。

由于这是一个本地 URL,可能是您的设备未连接到适当的网络。尝试从您的手机 ping 本地 URL(有几个实用程序可以尝试此操作,只需环顾四周)。

于 2014-02-24T12:48:21.387 回答
0

确认您的网址是否正确。我遇到了同样的问题,因为我的 URL 是 http://,我以 https:// 访问它。

可能是您的网址是这样的:

// URL to get contacts JSON
private static String url = "http://123.xxx.x.xxx/DEMO/login_data.php";
于 2014-03-02T06:52:58.720 回答