簡體   English   中英

Android App:從網絡到列表視圖的JSON數組

[英]Android App: JSON array from web to listview

我只是想從網絡中獲取以下格式的簡單JSON數組:[“ Country1”,“ Country2”,“ Country3”],然后將該數組用作我的android應用程序中的列表視圖。 我對如何制作此JSON數組並不拘泥,只是對如何將其放入應用程序的列表視圖中感到困惑。

我嘗試了一些不同的教程,但沒有一個使用與我相同的布局。

我的應用程序正在使用Viewflipper,以便始終在整個應用程序中查看基於選項卡的布局,因此,所有教程似乎都無法使用我的布局。

任何幫助深表感謝。

編輯:

這是一些代碼,是的,我想從Web服務中解析它並將其顯示在列表視圖中。

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):行列值:[“ 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...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM