从Android上的URL解析JSON并显示在listview中

时间:2016-04-02 08:35:34

标签: android json

我正在尝试从Android应用中的网址解析JSON结果。 我在互联网上尝试了一些例子,但无法让它发挥作用。

获取URL并解析JSON数据的最简单方法是在listview中显示它

Json数据:

  

[{ “MEMBERID”: “1”, “用户名”: “weerachai”, “密码”: “12345”, “名称”:“Weerachai   Nukitram “ ”联系电话“: ”0819876107“, ”电子邮件“: ”weerachai@gmail.com“},{ ”成员“: ”2“, ”用户名“: ”adisorn“, ”密码“: ”ac143“,”名称 “:” Adisorn   Bunsong “ ”联系电话“: ”021978032“, ”电子邮件“: ”adisorn@gmail.com“},{ ”成员“: ”3“, ”用户名“: ”surachai“, ”密码“: ”gg111“,”名称 “:” Surachai   Sirisart”, “电话”: “0876543210”, “电子邮件”: “surachai@gmail.com”}]

Android代码:

public class MainActivity extends AppCompatActivity {
    ArrayList<HashMap<String, String>> MyArrList;
    @SuppressLint("NewApi")


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

        // Permission StrictMode
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);

        }

        ShowData();

        // btnSearch
        final Button btnSearch = (Button) findViewById(R.id.btnSearch);
        //btnSearch.setBackgroundColor(Color.TRANSPARENT);
        // Perform action on click
        btnSearch.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                ShowData();
            }
        });
    }

    public void ShowData()
    {
        // listView1
        final ListView lisView1 = (ListView)findViewById(R.id.listView1);
        // keySearch
        EditText strKeySearch = (EditText)findViewById(R.id.txtKeySearch);
        // Disbled Keyboard auto focus
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);imm.hideSoftInputFromWindow(strKeySearch.getWindowToken(), 0);



        String url = "http:...............php";

        // Paste Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("txtKeyword", strKeySearch.getText().toString()));

        try {
            JSONArray data = new JSONArray(getJSONUrl(url,params));
            MyArrList = new ArrayList<HashMap<String, String>>();
            HashMap<String, String> map;

            for(int i = 0; i < data.length(); i++){
                JSONObject c = data.getJSONObject(i);

                map = new HashMap<String, String>();
                map.put("MemberID", c.getString("MemberID"));
                map.put("Username", c.getString("Username"));
                map.put("Password", c.getString("Password"));
                map.put("Name", c.getString("Name"));
                map.put("Email", c.getString("Email"));
                map.put("Tel", c.getString("Tel"));
                MyArrList.add(map);

            }

            lisView1.setAdapter(new ImageAdapter(this));

            // OnClick Item
            lisView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                public void onItemClick(AdapterView<?> myAdapter, View myView, int position, long mylng) {

                    String sMemberID = MyArrList.get(position).get("MemberID").toString();
                    String sName = MyArrList.get(position).get("Name").toString();
                    String sTel = MyArrList.get(position).get("Tel").toString();

                    Intent newActivity = new Intent(MainActivity.this,DetailActivity.class);
                    newActivity.putExtra("MemberID", sMemberID);
                    startActivity(newActivity);

                }
            });

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public class ImageAdapter extends BaseAdapter
    {

        private Context context;

        public ImageAdapter(Context c)
        {
            // TODO Auto-generated method stub
            context = c;
        }

        public int getCount() {
            // TODO Auto-generated method stub
            return MyArrList.size();
        }

        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        public View getView(final int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.activity_column, null);
            }

            // ColMemberID
            TextView txtMemberID = (TextView) convertView.findViewById(R.id.ColMemberID);
            txtMemberID.setPadding(10, 0, 0, 0);
            txtMemberID.setText(MyArrList.get(position).get("MemberID") +".");

            // R.id.ColName
            TextView txtName = (TextView) convertView.findViewById(R.id.ColName);
            txtName.setPadding(5, 0, 0, 0);
            txtName.setText(MyArrList.get(position).get("Name"));

            // R.id.ColTel
            TextView txtTel = (TextView) convertView.findViewById(R.id.ColTel);
            txtTel.setPadding(5, 0, 0, 0);
            txtTel.setText(MyArrList.get(position).get("Tel"));
            return convertView;
        }
    }

    public String getJSONUrl(String url,List<NameValuePair> params) {
        StringBuilder str = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        try {
            httpPost.setEntity(new UrlEncodedFormEntity(params));
            HttpResponse response = client.execute(httpPost);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) { // Download OK
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    str.append(line);
                }
            } else {
                Log.e("Log", "Failed to download result..");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str.toString();
    }
}

0 个答案:

没有答案