繁体   English   中英

从 PHP json 中提取数据以在 android 中使用

[英]extract data from PHP json to use in android

我正在使用此代码从 PHP 文件中获取一些数据并将一些数据提取到我的 android 应用程序中。 此代码提取每个产品的名称、价格和可用性,并将每个产品放入一个字符串中。 现在我需要在 Java 中有产品数组,其中包含每个产品的名称、价格和可用性,并将它们命名为 product1 product2 product3,这样我就可以基于此编写其余代码。 我怎样才能做到这一点 ?

public class MainActivity extends Activity {
    private String jsonResult;
    private String url = "xxxx/get_all_products.php";
    private ListView listView;

    private static final String TAG_PRODUCTS = "products";
    private static final String TAG_PID = "pid";
    private static final String TAG_NAME = "name";
    private static final String TAG_PRICE = "price";
    private static final String TAG_FOUND = "found";
    private static final String TAG_DESCRIPTION = "description";

    ArrayList<HashMap<String, String>> productList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView) findViewById(R.id.listView1);
        productList = new ArrayList<HashMap<String, String>>();

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                String selval = ((TextView) view.findViewById(R.id.name)).getText().toString();
                String selval1 = ((TextView) view.findViewById(R.id.price)).getText().toString();
                String selval2 = ((TextView) view.findViewById(R.id.found)).getText().toString();
                // Also I've found a solution on SO that a guy solved this problem doing soemthing like this :
                // TextView txt = (TextView) parent.getChildAt(position - listview.firstVisiblePosition()).findViewById(R.id.sometextview);
                // String keyword = txt.getText().toString();
                Intent intnt = new Intent(getApplicationContext(), SingleListItem.class);
                intnt.putExtra("selval", selval);
                intnt.putExtra("selval1", selval1);
                intnt.putExtra("selval2", selval2);

                startActivity(intnt);
 }
    });

        accessWebService();

    }

    // Async Task to access the web
    private class JsonReadTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(params[0]);
            try {
                HttpResponse response = httpclient.execute(httppost);
                jsonResult = inputStreamToString(
                        response.getEntity().getContent()).toString();
            }

            catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        private StringBuilder inputStreamToString(InputStream is) {
            String rLine = "";
            StringBuilder answer = new StringBuilder();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));

            try {
                while ((rLine = rd.readLine()) != null) {
                    answer.append(rLine);
                }
            }

            catch (IOException e) {
                // e.printStackTrace();
                Toast.makeText(getApplicationContext(),
                        "Error..." + e.toString(), Toast.LENGTH_LONG).show();
            }
            return answer;
        }

        @Override
        protected void onPostExecute(String result) {
            ListDrwaer();
        }
    }// end async task

    public void accessWebService() {
        JsonReadTask task = new JsonReadTask();
        // passes values for the urls string array
        task.execute(new String[]{url});
    }

    // build hash set for list view
    public void ListDrwaer() {
        List<Map<String, String>> productList = new ArrayList<Map<String, String>>();

        try {
            JSONObject jsonResponse = new JSONObject(jsonResult);
            JSONArray jsonMainNode = jsonResponse.optJSONArray("products");

            for (int i = 0; i < jsonMainNode.length(); i++) {
                JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                String name = jsonChildNode.optString("name");
                String price = jsonChildNode.optString("price");
                    String found = jsonChildNode.optString("found");
                //    String outPut = name + "-" + number;
           //     String outPut = name + "-" + price + "-" + found;
           //     productList.add(createProduct("products", outPut));
                HashMap<String, String> product = new HashMap<String, String>();

                product.put(TAG_NAME, name);
                product.put(TAG_FOUND, found);
                product.put(TAG_PRICE, price);

               productList.add(product);
            }
        } catch (JSONException e) {
            Toast.makeText(getApplicationContext(), "Error" + e.toString(),
                    Toast.LENGTH_SHORT).show();
        }

        SimpleAdapter simpleAdapter = new SimpleAdapter(this, productList,
                R.layout.list_item, new String[] { TAG_NAME, TAG_PRICE,
                TAG_FOUND }, new int[] { R.id.name,
                R.id.price, R.id.found });
        listView.setAdapter(simpleAdapter);

        }
        }

它非常简单,通过在 for 循环之外使用此代码

JSONObject pro1 = jsonMainNode.getJSONObject(0);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM