【发布时间】:2016-10-19 14:57:15
【问题描述】:
下午好,
我正在尝试使用 Singleton 来检索和填充 Android 应用程序的 ListView,该应用程序使用带有最新版本 Volley 的 Android Studio,当我必须显示信息时遇到问题。
我从服务器获取的 JSON 很好,当我创建产品时一切都很好,但是 ListView 没有填充。
你能给我点灯吗?我已经尝试了很多教程和示例,但我不知道我的 ListView 仍然是空的,因为我已经检查过产品是在我的函数中创建的。
这是我的代码:
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ListadoProductos extends Activity {
// URL of object to be parsed
String url = "https://www.mywebsite.com/products.json";
// Key JSON
String key = "lista_productos";
// Map
List<Map<String,String>> productoList = new ArrayList<Map<String,String>>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.products);
// Get the latest products
initJSON();
// Show the information
ListView listView = (ListView) findViewById(R.id.listv);
SimpleAdapter simpleAdapter = new SimpleAdapter(this, productoList, android.R.layout.simple_list_item_1, new String[] {key}, new int[] {android.R.id.text1});
listView.setAdapter(simpleAdapter);
}
private HashMap<String, String> createProducto(String nameTitle, String name){
HashMap<String, String> employeeNameNo = new HashMap<String, String>();
employeeNameNo.put(nameTitle, name);
return employeeNameNo;
}
private void initJSON(){
JsonObjectRequest jsObjRequest = new JsonObjectRequest (Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try{
JSONObject jsonResponse = new JSONObject(response.toString());
JSONArray jsonMainNode = jsonResponse.optJSONArray(key);
// Show 10 products
for(int i = 0; i<10;i++){
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.getString("nombre");
String outPut = name;
productoList.add(createProducto(key, outPut));
}
}
catch(JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(), Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
Log.d("Error", error.toString());
}
});
// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(jsObjRequest);
}
}
非常感谢。
【问题讨论】:
标签: android json listview android-volley