gpt4 book ai didi

安卓应用 : JSON array from web to listview

转载 作者:太空狗 更新时间:2023-10-29 16:09:13 24 4
gpt4 key购买 nike

我只是想从网络上获取以下格式的简单 JSON 数组:["Country1","Country2","Country3"],然后将该数组用作我的 Android 应用程序中的 ListView 。我没有纠结于如何制作这个 JSON 数组,我只是对如何将它放入应用程序的 ListView 中感到困惑。

我试过几个不同的教程,但没有一个使用与我相同的布局。

我的应用程序正在使用 viewflipper,以在整个应用程序中始终保持基于选项卡的布局可见,因此似乎没有任何教程适用于我的布局。

非常感谢任何帮助。

编辑:

这是一些代码,是的,我想从网络服务中解析它并将其显示在 ListView 中。

public class Activity extends TabActivity implements OnClickListener {

Button doSomething;
TabHost tabHost;
ViewFlipper flipper;
ListView listview;


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



doSomething = (Button) findViewById(R.id.btn_do_something);
doSomething.setOnClickListener(this);

flipper = (ViewFlipper) findViewById(R.id.layout_tab_one);

listview = (ListView) findViewById(R.id.listview);

@SuppressWarnings("unchecked")
ListAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,fetchTwitterPublicTimeline());


//ListAdapter adapter = new SimpleAdapter(this, this.fetchTwitterPublicTimeline() , R.layout.main, new int[] { R.id.item_title, R.id.item_subtitle });


listview.setAdapter(adapter);

flipper.setOnClickListener(this);

String tabname1 = getString(R.string.tabexample_tab1);
String tabname2 = getString(R.string.tabexample_tab2);
String tabname3 = getString(R.string.tabexample_tab3);
String tabname4 = getString(R.string.tabexample_tab4);

tabHost = getTabHost();
tabHost.addTab(tabHost.newTabSpec("tab1").setContent(R.id.layout_tab_one).setIndicator(tabname1));
tabHost.addTab(tabHost.newTabSpec("tab2").setContent(R.id.layout_tab_two).setIndicator(tabname2));
tabHost.addTab(tabHost.newTabSpec("tab3").setContent(R.id.layout_tab_three).setIndicator(tabname3));
tabHost.addTab(tabHost.newTabSpec("tab4").setContent(R.id.layout_tab_four).setIndicator(tabname4));

tabHost.setCurrentTab(0);




listview.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
flipper.showNext();


}});




}


public ArrayList<String> fetchTwitterPublicTimeline()
{
ArrayList<String> listItems = new ArrayList<String>();

try {
URL twitter = new URL(
"JSON.php");
URLConnection tc = twitter.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));

String line;
while ((line = in.readLine()) != null) {
JSONArray ja = new JSONArray(line);

for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
listItems.add(jo.getString(""));
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listItems;
}


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

}


}

更新:我仍然无法让它工作,知道下面的代码有什么问题吗?

public class Activity extends TabActivity implements OnClickListener {

Button doSomething;
TabHost tabHost;
ViewFlipper flipper;
ListView listview;
HttpResponse re;
String json;
JSONObject j;



@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
//final String TAG = "MainActivity";
//final String URL = "JSON.php";

super.onCreate(savedInstanceState);



setContentView(R.layout.tablayout_1);



final String[] listItems = new String[] { };



/*========================================


// JSON object to hold the information, which is sent to the server
JSONObject jsonObjSend = new JSONObject();

try {
// Add key/value pairs
jsonObjSend.put("key_1", "value_1");
jsonObjSend.put("key_2", "value_2");

// Add a nested JSONObject (e.g. for header information)
JSONObject header = new JSONObject();
header.put("deviceType","Android"); // Device type
header.put("deviceVersion","2.0"); // Device OS version
header.put("language", "es-es"); // Language of the Android client
jsonObjSend.put("header", header);

// Output the JSON object we're sending to Logcat:
Log.i(TAG, jsonObjSend.toString(2));

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

// Send the HttpPostRequest and receive a JSONObject in return
JSONObject jsonObjRecv = HTTPClient.SendHttpPost(URL, jsonObjSend);
String temp = jsonObjRecv.toString();


/*==============================================*/



doSomething = (Button) findViewById(R.id.btn_do_something);
doSomething.setOnClickListener(this);

flipper = (ViewFlipper) findViewById(R.id.layout_tab_one);

listview = (ListView) findViewById(R.id.listview);







/* try {

JSONArray array = jsonObjRecv.getJSONArray(""); //(JSONArray) new JSONTokener(json).nextValue();

String[] stringarray = new String[array.length()];
for (int i = 0; i < array.length(); i++) {
stringarray[i] = array.getString(i);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, stringarray);
listview.setAdapter(adapter);
} catch (JSONException e) {
// handle JSON parsing exceptions...
}*/


//@SuppressWarnings("unchecked")
ListAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,fetchTwitterPublicTimeline());


//ListAdapter adapter = new SimpleAdapter(this, this.fetchTwitterPublicTimeline() , R.layout.main, new int[] { R.id.item_title, R.id.item_subtitle });


listview.setAdapter(adapter);

flipper.setOnClickListener(this);

String tabname1 = getString(R.string.tabexample_tab1);
String tabname2 = getString(R.string.tabexample_tab2);
String tabname3 = getString(R.string.tabexample_tab3);
String tabname4 = getString(R.string.tabexample_tab4);

tabHost = getTabHost();
tabHost.addTab(tabHost.newTabSpec("tab1").setContent(R.id.layout_tab_one).setIndicator(tabname1));
tabHost.addTab(tabHost.newTabSpec("tab2").setContent(R.id.layout_tab_two).setIndicator(tabname2));
tabHost.addTab(tabHost.newTabSpec("tab3").setContent(R.id.layout_tab_three).setIndicator(tabname3));
tabHost.addTab(tabHost.newTabSpec("tab4").setContent(R.id.layout_tab_four).setIndicator(tabname4));

tabHost.setCurrentTab(0);




listview.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
flipper.showNext();


}});




}



public ArrayList<String> fetchTwitterPublicTimeline()
{
ArrayList<String> listItems = new ArrayList<String>();

try {
URL twitter = new URL(
"JSON.php");
URLConnection tc = twitter.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));


String line = null;

//make sure youe String line is completely filled after that..
if (!line.equals(null) && !line.equals("") && line.startsWith("["))
{
JSONArray jArray = new JSONArray(line);
for (int i = 0; i < jArray.length(); i++)
{
JSONObject jobj = jArray.getJSONObject(i);
// also make sure you get the value from the jsonObject using some key
// like, jobj.getString("country");

listItems.add(jobj.getString(""));
}
}



} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listItems;
}



/* public ArrayList<String> fetchTwitterPublicTimeline()
{
ArrayList<String> listItems = new ArrayList<String>();

try {
URL twitter = new URL(
"JSON.php");
URLConnection tc = twitter.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));



//make sure youe String line is completely filled after that..
if (!line.equals(null) && !line.equals("") && line.startsWith("["))
{
JSONArray jArray = new JSONArray(line);
for (int i = 0; i < jArray.length(); i++)
{
JSONObject jobj = jArray.getJSONObject(i);
// also make sure you get the value from the jsonObject using some key
// like, jobj.getString("country");

listItems.add(jobj.getString(""));
}
}




/* String line;
while ((line = in.readLine()) != null) {
JSONArray ja = new JSONArray(line);

for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
listItems.add(jo.getString(""));
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return listItems;
}*/


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

}


}

更新,这是 Logcat 报告的 jArray 的值:

08-26 16:49:07.246: VERBOSE/app(472): jarray 值:["Country1","Country2","Country3"]

这些是正确的值!

最佳答案

这适用于我刚刚创建的一个简单的测试应用程序......

ListView list = (ListView) findViewById(...);
String json = "[\"Country1\",\"Country2\",\"Country3\"]";
try {
JSONArray array = (JSONArray) new JSONTokener(json).nextValue();

String[] stringarray = new String[array.length()];
for (int i = 0; i < array.length(); i++) {
stringarray[i] = array.getString(i);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, stringarray);
list.setAdapter(adapter);
} catch (JSONException e) {
// handle JSON parsing exceptions...
}

关于安卓应用 : JSON array from web to listview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7164963/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com