使用带有JSON数据的自定义布局行填充listview

时间:2016-05-20 08:14:29

标签: android json listview

  

您好我有困难在listView中填充自定义行   json数据。从Json获得的数据如果我放入log.V或a   textView与.setText(JsonData)的属性,它显示了corect   数据。问题是它没有填充listView行。它看起来   像这样

enter image description here

  

我看它看起来像这样   enter image description here

     

这是我的代码:

public class MainActivity extends AppCompatActivity {

private String currencyURL = "https://openexchangerates.org/api/latest.json?app_id=389cadf865504852b08a1759063621f5";
private String countryURL = "https://gist.githubusercontent.com/keeguon/2310008/raw/bdc2ce1c1e3f28f9cab5b4393c7549f38361be4e/countries.json";

private TextView currency, TXT;
private String TAG = "MainActivity::";

private ArrayList<Model> bucketCurrency = new ArrayList<>();
private ListView listView;
private ListViewAdapter listViewAdapter;

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

    listView = (ListView) findViewById(R.id.activity_main_listView);
    currency = (TextView) findViewById(R.id.activity_main_country_currency_text);
    TXT = (TextView) findViewById(R.id.editText);


    getJson(currencyURL, countryURL);

    listViewAdapter = new ListViewAdapter(MainActivity.this, R.layout.list_view_custom_row, bucketCurrency);
    listViewAdapter.notifyDataSetChanged();
    listView.setAdapter(listViewAdapter);

}
 private void getJson(String URL_1_CURRENCY, String URL_2_COUNTRY) {

    final Model model = new Model();

    JsonObjectRequest jsonObjectRequest1 = new JsonObjectRequest(Request.Method.GET, URL_1_CURRENCY, (JSONObject) null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {

                    try {

                        JSONObject ratesJsonObj = response.getJSONObject("rates");
                        String cursRon = ratesJsonObj.getString("RON");
                        String cursEuro = ratesJsonObj.getString("EUR");
                        String cursDolar = ratesJsonObj.getString("USD");

                        model.setCurrency(cursRon);
                        TXT.setText(cursRon);
                        Toast.makeText(MainActivity.this, "RON: " + cursRon, Toast.LENGTH_SHORT).show();

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

                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            error.getMessage();
        }
    });


    AppController.getInstance().addToRequestQueue(jsonObjectRequest1);

    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, URL_2_COUNTRY, (JSONObject) null, new Response.Listener<JSONArray>() {
        @Override
        public void onResponse(JSONArray response) {

            try {

                for (int i = 179; i < 185 ; i++) {

                    JSONObject jsonObjectCountry = response.getJSONObject(i);
                    String countryROM = jsonObjectCountry.getString("name");
                    String countryCODE = jsonObjectCountry.getString("code");

                    model.setCountry(countryROM);
                    model.setCountryCode(countryCODE);

                    Log.v(TAG, countryROM + " " + countryCODE);
                }

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

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });

    AppController.getInstance().addToRequestQueue(jsonArrayRequest);

    bucketCurrency.add(model);
}
  

AppController类:

    public class AppController extends Application {

    public static final String TAG = AppController.class
            .getSimpleName();

    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;

    private static AppController mInstance;

    @Override
    public void onCreate() {

        super.onCreate();

        mInstance = this;
    }

    public static synchronized AppController getInstance() {
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    public <T> void addToRequestQueueModified(Request<T> req_1, Request<T> req_2) {
        req_1.setTag(TAG);
        getRequestQueue().add(req_1);
        req_2.setTag(TAG);
        getRequestQueue().add(req_2);
    }

    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}
  

模型类:

public class Model {
private String country;
private String countryCode;
private String currency;
private ImageView countryFlagImage;

public String getCountry() {
    return country;
}

public void setCountry(String country) {
    this.country = country;
}

public String getCountryCode() {
    return countryCode;
}

public void setCountryCode(String countryCode) {
    this.countryCode = countryCode;
}

public ImageView getCountryFlagImage() {
    return countryFlagImage;
}

public void setCountryFlagImage(ImageView countryFlagImage) {
    this.countryFlagImage = countryFlagImage;
}

public String getCurrency() {
    return currency;
}

public void setCurrency(String currency) {
    this.currency = currency;
}

}

  

ListView适配器类:

public class ListViewAdapter extends ArrayAdapter<Model> {

Activity activity;
int layoutResource;
ArrayList<Model> newData = new ArrayList<>();

public ListViewAdapter(Activity act, int resource, ArrayList<Model> data) {
    super(act, resource, data);

    activity = act;
    layoutResource = resource;
    newData = data;
    notifyDataSetChanged();

}

@Override
public int getCount() {
    return newData.size();
}

@Override
public Model getItem(int position) {
    return newData.get(position);
}

@Override
public long getItemId(int position) {
    return super.getItemId(position);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View row = convertView;
    ViewHolder holder;

    if (row == null || (row.getTag()) == null){
        LayoutInflater inflater = LayoutInflater.from(activity);
        row = inflater.inflate(layoutResource, null);

        holder = new ViewHolder();

        holder.hCountry = (TextView) row.findViewById(R.id.custom_listview_country_text);
        holder.hCountryCode = (TextView) row.findViewById(R.id.custom_listview_country_code);
        holder.hCurrency = (TextView) row.findViewById(R.id.custom_listview_currency);
        holder.hFlag = (ImageView) row.findViewById(R.id.custom_listview_country_flag_image);

        row.setTag(holder);

    } else {
        holder = (ViewHolder) row.getTag();
    }

    holder.hModel = getItem(position);
    holder.hCountry.setText(holder.hModel.getCountry());
    holder.hCountryCode.setText(holder.hModel.getCountryCode());
    holder.hCurrency.setText(holder.hModel.getCurrency());


    return row;
}

public class ViewHolder {
    Model hModel;
    TextView hCountry;
    TextView hCountryCode;
    TextView hCurrency;
    ImageView hFlag;
}

}

  

XML自定义行

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
android:orientation="vertical">

<ImageView
    android:id="@+id/custom_listview_country_flag_image"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:background="@color/gray_300"
    android:layout_marginTop="5dp"
    android:layout_marginLeft="5dp"
    android:src="@mipmap/ic_launcher"/>

<TextView
    android:id="@+id/custom_listview_country_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/country"
    android:textSize="25dp"
    android:layout_toRightOf="@id/custom_listview_country_flag_image"
    android:layout_marginTop="5dp"
    android:layout_marginLeft="20dp"
    android:textStyle="bold"/>

<TextView
    android:id="@+id/custom_listview_country_code"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/country_code"
    android:textSize="15dp"
    android:layout_toRightOf="@id/custom_listview_country_flag_image"
    android:layout_below="@id/custom_listview_country_text"
    android:layout_marginTop="5dp"
    android:layout_marginLeft="20dp"
    android:textStyle="italic"/>

<TextView
    android:id="@+id/custom_listview_currency"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/country_currency"
    android:textSize="25dp"
    android:layout_toRightOf="@id/custom_listview_country_text"
    android:layout_marginTop="25dp"
    android:layout_marginLeft="40dp"
    android:textStyle="bold"/>

2 个答案:

答案 0 :(得分:1)

试试这个!!!

private String cursRon;

private void getJson(String URL_1_CURRENCY, String URL_2_COUNTRY) {

Model model = null;

JsonObjectRequest jsonObjectRequest1 = new JsonObjectRequest(Request.Method.GET, URL_1_CURRENCY, (JSONObject) null,
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {

                try {

                    JSONObject ratesJsonObj = response.getJSONObject("rates");
                    cursRon = ratesJsonObj.getString("RON");
                    String cursEuro = ratesJsonObj.getString("EUR");
                    String cursDolar = ratesJsonObj.getString("USD");


                    TXT.setText(cursRon);
                    Toast.makeText(MainActivity.this, "RON: " + cursRon, Toast.LENGTH_SHORT).show();

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

            }
        }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        error.getMessage();
    }
});


AppController.getInstance().addToRequestQueue(jsonObjectRequest1);

JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, URL_2_COUNTRY, (JSONObject) null, new Response.Listener<JSONArray>() {
    @Override
    public void onResponse(JSONArray response) {

        try {

            for (int i = 179; i < 185 ; i++) {
                model = new Model();
                JSONObject jsonObjectCountry = response.getJSONObject(i);
                String countryROM = jsonObjectCountry.getString("name");
                String countryCODE = jsonObjectCountry.getString("code");
                model.setCurrency(cursRon);
                model.setCountry(countryROM);
                model.setCountryCode(countryCODE);

                Log.v(TAG, countryROM + " " + countryCODE);
               bucketCurrency.add(model);
            }

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

    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {

    }
});

AppController.getInstance().addToRequestQueue(jsonArrayRequest);


}

答案 1 :(得分:0)

我认为您应该嵌套请求,然后在第二个请求的 onResponse 内移动 bucketCurrency.add(model); ,如下所示:

end if