Android应用程序:JSON数组从网页到列表视图

问题描述:

我只是试图让下面的格式简单的JSON数组:[COUNTRY2,COUNTRY3,国家1]从Web,然后使用该数组在我的Andr​​oid应用程序列表视图。我不是停留在如何让这个JSON数组,我是如何得到它变成在应用程序列表视图只是糊涂了。

I'm just trying to get a simple JSON array in the following format: ["Country1","Country2","Country3"] from the web and then use that array as a listview in my android app. I'm not stuck on how to make this JSON array, i'm just confused on how to get it into a listview in the app.

我已经尝试了一些不同的教程,但他们没有使用相同的布局,如我的。

I have tried a few different tutorials, but none of them are using the same layout as such as mine.

我的应用程序正在使用viewflipper,保持在视图中的tabbased布局在任何时候整个应用程序,因此没有教程似乎与我的布局中工作。

My app is using a viewflipper, to keep a tabbased layout in view at all times throughout the app, therefore none of the tutorials seem to be working with my layout.

任何帮助很多AP preciated。

Any help is much appreciated.

编辑:

下面是一些code,是的,我想从Web服务解析和列表视图中显示它。

Here's some code, yes i want to parse it from a web service and display it in a 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

}


}

更新:我仍然无法得到它的工作,任何想法在下面的code是错误的。

UPDATE: I still can't get it working, any ideas what's wrong in the code below?

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

}


}

更新,这里有jArray值由logcat的报道:

Update, here are the values of jArray as reported by Logcat:

16 08-26:49:07.246:VERBOSE /应用程序(472):jarray值:国家1,COUNTRY2,COUNTRY3]

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

这是正确的值!

这工作在一个简单的测试程序,我刚刚创建...

This works in a simple test app I just created...

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...
}