将JSON解析为listView

时间:2014-04-02 20:12:47

标签: android json listview android-listview

想在列表视图中获取我正在处理的内容。我从网上提取了一些JSON和一个位图,截至目前我已经拥有它,所以我可以点击一个按钮左右滚动它们,但是想把它们放在列表视图中。

我为列表视图创建了这个

的布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

<RelativeLayout 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="65dp"
        android:layout_height="65dp"
        android:layout_centerVertical="true"
        android:layout_margin="5dp"
        android:padding="3dp" 
        android:scaleType="fitXY"
        android:src="@drawable/generic" />

    <TextView
        android:id="@+id/Model"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dip"
        android:layout_toLeftOf="@+id/price"
        android:layout_toRightOf="@+id/imageView1"
        android:maxLines="1"
        android:text="title"
        android:textColor="@android:color/black"
        android:textSize="15dip"
        android:textStyle="bold" />
    <TextView
        android:id="@+id/Price"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginRight="10dp"
        android:layout_marginTop="5dip"
        android:text="$$$$"
        android:textColor="@android:color/holo_red_light"
        android:textSize="12dip" />
    <TextView
        android:id="@+id/Description"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/Model"
        android:layout_toRightOf="@+id/imageView1"
        android:ellipsize="end"
        android:maxLines="3"
        android:text="desc"
        android:textColor="@android:color/black"
        android:textSize="13dip" />



    </RelativeLayout>
</LinearLayout>

这就是我希望listView的每个部分都遵循的内容,我可以使用JSON信息以及Bitmap来填充它。

这里是主要的活动,我正在做这个全部:

package com.example.parsejson;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class ParseJSONActivity extends Activity {
    private static final String TAG = "ParseJSON";

    private static final String BikeInfo = "http://www.tetonsoftware.com/bikes/bikes.json";
    private static final String BikePic = "http://www.tetonsoftware.com/bikes/";
    public static final int MAX_LINES = 15;

    private TextView description;
    private TextView model;
    private TextView price;

    private TextView example;

    private ImageView bikePic;
    private Button bleft;
    private Button bright;
    JSONArray jsonArray;

    int numberentries = -1;
    int currententry = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        setContentView(R.layout.activity_parse_json);

        description = (TextView) findViewById(R.id.Description);
        model = (TextView) findViewById(R.id.Model);
        price = (TextView) findViewById(R.id.Price);
        bikePic = (ImageView) findViewById(R.id.imageView1);
        bleft = (Button) findViewById(R.id.bleft);
        bright = (Button) findViewById(R.id.bright);

        example = (TextView) findViewById(R.id.textView4);


        ConnectivityCheck myCheck = new ConnectivityCheck(this);
        if (myCheck.isNetworkReachableAlertUserIfNot()) {
            DownloadTask myTask = new DownloadTask(this);


            myTask.execute(BikeInfo);
        }
    }

    public void processJSON(String string) {
        try {
            JSONObject jsonobject = new JSONObject(string);

            //*********************************
            //magic number to make JSON indented
            final int INDENT =2;
            Log.d(TAG,jsonobject.toString(INDENT));     


            // you must know what the data format is, a bit brittle
            jsonArray = jsonobject.getJSONArray("Bikes");

            // how many entries
            numberentries = jsonArray.length();

            currententry = 0;
            setJSONUI(currententry); // parse out object currententry


            Log.i(TAG, "Number of entries " + numberentries);

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

    }


    private void setJSONUI(int i) {
        StringBuilder bikePicUrl = new StringBuilder(BikePic);

        if (jsonArray == null) {
            Log.e(TAG, "tried to dereference null jsonArray");
            return;
        }
        bikePicUrl.append( (i+1) + ".jpg");
        String bikeString = bikePicUrl.toString();

        example.setText(bikePicUrl);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();      
        StrictMode.setThreadPolicy(policy);     
        Bitmap bikeImage = getBitmapFromURL(bikeString);
        bikePic.setImageBitmap(bikeImage);

        // gotta wrap JSON in try catches cause it throws an exception if you
        // try to
        // get a value that does not exist
        try {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            description.setText(jsonObject.getString("Description"));
            model.setText(jsonObject.getString("Model"));
            price.setText(jsonObject.getString("Price"));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        setButtons();
    }

    private void setButtons() {
        // make sure that appropriate buttons enabled only
        bleft.setEnabled(numberentries != -1 && currententry != 0);
        bright.setEnabled(numberentries != -1
                && currententry != numberentries - 1);
    }

    public void doLeft(View v) {
        if (numberentries != -1 && currententry != 0) {
            currententry--;
            setJSONUI(currententry);
        }
    }

    public void doRight(View v) {
        if (numberentries != -1 && currententry != numberentries) {
            currententry++;
            setJSONUI(currententry);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_parse_json, menu);
        return true;
    }

    public Bitmap getBitmapFromURL(String imageUrl) {
        try {
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();
            Bitmap backgroundImage = BitmapFactory.decodeStream(input);
            return backgroundImage;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

}

我正在填写列表视图时遇到问题,任何帮助都会很棒!我尝试在列表视图上附上这一个教程,但由于这个类扩展了Activity,并且listView类扩展了ListActivity,我似乎无法使用任何东西!

1 个答案:

答案 0 :(得分:0)

您将要使用自定义适配器来显示数据。图像必须在后台完成,因为它们是从网上加载的。这是listview和适配器的深入教程

http://www.vogella.com/tutorials/AndroidListView/article.html

对于图片加载或“延迟加载”,有很多很棒的第三方库,例如Volley或我最喜欢的Universal Image Loader

相关问题