我正在尝试从 json 中获取数据。实际上它正在工作,但我的 listview 有问题。我收到错误。
这是代码; 主 Activity .java
public class MainActivity extends AppCompatActivity {
TextView txt;
Places places=new Places();
ListView listView;
List<Places> PlacesList=new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt= (TextView) findViewById(R.id.text);
listView= (ListView) findViewById(R.id.listView);
listView.setBackgroundColor(Color.BLACK);
new getData().execute("https://api.foursquare.com/v2/venues/search?ll=41,29&oauth_token=01ZV1VDLE41USSRAYJUXOWNJ2MXYCAVN1I2PQFLFBCD40XYI&v=20160304");
}
public class getData extends AsyncTask<String,String,List <Places>> {
HttpURLConnection conn=null;
URL url=null;
BufferedReader bReader=null;
String name=null;
@Override
protected List<Places> doInBackground(String... params) {
try {
//BURADA URL'E BAGLANDIK
url=new URL(params[0]);
conn= (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
//VERİ OKUMAK İÇİN STREAM KULLANACAZ
InputStream istream=conn.getInputStream();
bReader= new BufferedReader(new InputStreamReader(istream));
//VERİ DEPOLAMAK İÇİN StringBuffer
StringBuffer sBuffer=new StringBuffer();
String line="";
while((line=bReader.readLine())!=null){
sBuffer.append(line);
}
String JSONFinal=sBuffer.toString();
JSONObject jsonObject=new JSONObject(JSONFinal);
JSONArray jsonArray=jsonObject.getJSONObject("response").getJSONArray("venues");
StringBuffer finalBuffer=new StringBuffer();
for(int i=0;i<jsonArray.length();i++) {
JSONObject finalJsonObject = jsonArray.getJSONObject(i);
name = finalJsonObject.getString("name");
places.setName(name);
PlacesList.add(places);
}
return PlacesList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
finally {
conn.disconnect();
}
return null;
}
@Override
protected void onPostExecute( List<Places> PlacesList) {
super.onPostExecute(PlacesList);
ArrayAdapter adapter= new ArrayAdapter<Places>(getApplicationContext(),android.R.layout.simple_list_item_1,PlacesList);
listView.setAdapter(adapter);
}
}
Places.java
public class Places {
int id,lat,lng;
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
那么问题是什么?
最佳答案
之所以这样显示,是因为您已将 Places
对象传递给您的 ListView ,并且您没有提供要从 Places
对象显示在 ListView 中的字段,你可能应该在你的 Places
对象中提供 toString()
方法来查看你的名称列表,或者你应该创建你自己的适配器实现
查看带有名称的 ListView
将此添加到您的 Places
类中
public void toString(){
return name;
}
关于java - 数组列表和 ListView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35817595/