无法从android中的json.txt文件打印json数据

时间:2013-06-13 10:14:07

标签: android json

“brand_name”和“description”这些是以下json文件中的数据,我试图在textviews上打印。注意:JSON数据文件在res / raw / brand.txt下。

请帮我解决这个问题

非常感谢

以下是我的来源

public class Index_page extends TabActivity {

Button white_brand;

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

              t1 = (TextView)findViewById(R.id.txt_name);
    t2 = (TextView)findViewById(R.id.txt_des);

      white_brand = (Button)findViewById(R.id.btn_brand_white);
    white_brand.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            get_brands_data();
        }
    });

       protected void get_brands_data() {
    // TODO Auto-generated method stub

    InputStream inputStream = getResources().openRawResource(R.raw.brand);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    int prdct;
    try {
        prdct = inputStream.read();
        while (prdct != -1) {
            byteArrayOutputStream.write(prdct);
            prdct = inputStream.read();
        }
        inputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {

        // Parse the data into jsonobject to get original data in form of json.

        JSONObject jObject = new JSONObject(byteArrayOutputStream.toString());
        JSONObject jObjectResult = jObject.getJSONObject("Products");

        String br_name = "";
        String br_desc = "";
        System.out.println("------" br_name);
        System.out.println("------" br_desc);
        t1.setText(br_name);
        t2.setText(br_desc);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

JSON DATA

{
"PublicationID": 53,
"PublicationDate": "18/01/2013",
"Publicationbackgroundimage": null,
"Products": [
    {
        "SequenceKey": 1,
        "ProductID": 100630,
        "Brand_Name": "Lindauer",
        "Region": "",
        "Country_of_Origin": "New Zealand",
        "Description": "Lindauer, the country's most popular sparkling wine brand, started life as a bold statement about the quality of wine that can be created in New Zealand's cool-climate. Made from traditional champagne grape varieties, Chardonnay and Pinot Noir and more recently premium Marlborough Sauvignon Blanc grapes, it uses the authentic method of bottling the wine for its second fermentation, a technique that creates the sparkle and distinctive yeasty flavours, regularly outperforming more expensive wines. Wines in this range include Lindauer Brut NV, Lindauer Fraise, Lindauer Rose, Lindauer Sec and Lindauer Sauvignon Blanc."
    }
  ]
}

1 个答案:

答案 0 :(得分:1)

您无法在UI线程上执行任何I / O.您必须在单独的线程上调用get_brands_data();。你想使用AsyncTask。

相关问题