【问题标题】:How to change listview items?如何更改列表视图项目?
【发布时间】:2012-03-21 16:58:43
【问题描述】:

我从 HttpGet 获取字符串,我想将它们放入列表视图中。我怎么能这样做?我在任何地方都找不到关于它的任何信息。在运动中,我只有一些测试数据。

例如。

“测试1”

但我希望它是动态的,从电话从 HttpGet 获取的字符串。

谢谢。

到目前为止我的代码:(对于代码混乱,我会尽快重写它!)

public class ChatService extends Activity {
    /** Called when the activity is first created. */


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chatservice);
        try {
            ContactsandIm();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        CheckLogin();


        ListView list = (ListView) findViewById(R.id.ListView01);
        list.setClickable(true);

        final List<PhoneBook> listOfPhonebook = new ArrayList<PhoneBook>();
        listOfPhonebook.add(new PhoneBook("a", "9981728", "test@test.com"));
        listOfPhonebook
                .add(new PhoneBook("Test1", "1234455", "test1@test.com"));
        listOfPhonebook.add(new PhoneBook("Test2", "00000", "test2@test.com"));

        PhonebookAdapter adapter = new PhonebookAdapter(this, listOfPhonebook);

        list.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View view,
                    int position, long index) {
                System.out.println("sadsfsf");
                showToast(listOfPhonebook.get(position).getName());
            }
        });

        list.setAdapter(adapter);
    }

    private void CheckLogin() {
        // TODO Auto-generated method stub
        // Create a new HttpClient and Post Header
                HttpClient httpclient = new DefaultHttpClient();

                /* login.php returns true if username and password is equal to saranga */
                HttpPost httppost = new HttpPost("http://gta5news.com/login.php");

                try {

                    // Execute HTTP Post Request
                    Log.w("HttpPost", "Execute HTTP Post Request");
                    HttpResponse response = httpclient.execute(httppost);

                    String str = inputStreamToString(response.getEntity().getContent())
                            .toString();
                    Log.w("HttpPost", str);

                    if (str.toString().equalsIgnoreCase("true")) {
                        Log.w("HttpPost", "TRUE");
                        try {Thread.sleep(250);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                        //put intent here(21/3/12); 

                    } else {
                        Log.w("HttpPost", "FALSE");

                    }

                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            private StringBuilder inputStreamToString(InputStream is) {
                String line = "";
                StringBuilder total = new StringBuilder();
                // Wrap a BufferedReader around the InputStream
                BufferedReader rd = new BufferedReader(new InputStreamReader(is));
                // Read response until the end
                try {
                    while ((line = rd.readLine()) != null) {
                        total.append(line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // Return full string
                return total;
            }




    private void ContactsandIm() throws URISyntaxException, ClientProtocolException, IOException {
        // TODO Auto-generated method stub
        BufferedReader in = null;
        String data = null;


        HttpClient get = new DefaultHttpClient();
        URI website = new URI("http://www.gta5news.com/test.php");
        HttpGet webget = new HttpGet();
        webget.setURI(website);
        HttpResponse response = get.execute(webget);
        Log.w("HttpPost", "Execute HTTP Post Request");
        in = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
        //now we'll return the data that the PHP set from the MySQL Database.



        // just some test code, to see if the HttpGet was working.
        if (in.equals("True")); {
            Toast.makeText(this,"yay", Toast.LENGTH_LONG).show();
        }






    }

    // end bracket for "ContactsandIm"

    private void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }
}

【问题讨论】:

  • 那是什么?我以前从未见过这种方法。

标签: java android http listview http-get


【解决方案1】:

从代码中,我看到 PhonebookAdapter 是您的自定义适配器类。为什么不解析 PhoneBook 类型的 http 响应并将其添加到 listOfPhonebook。这应该会在 listView 中显示解析的内容。

【讨论】:

    【解决方案2】:

    据我了解,每次 Http 请求成功时,您都需要添加新的电话簿条目。 如果是这样,您必须选择使一切动态化:

    1. 每次收到新数据时重新创建适配器:

      • 使您的 listView 成为全局变量(以使其可从类中的任何函数访问)
      • 对您的列表做同样的事情
      • 收到新数据后 - 将此数据添加到您的列表中,创建新适配器并将此适配器设置为您的 ListView
    2. 创建一个可以更新 ListItems 的自定义适配器:

      公共类 YourCustomAdapter 扩展 BaseAdapter { 私人最终 LayoutInflater 充气机; 私有 ArrayList 列表 = 新 ArrayList(); 私人处理程序 uiHandler = 新处理程序();
      /*..... default set of functions from BaseAdapter ......*/
      
      public void setList(ArrayList<PhoneBook> list)
      {
          this.list = list;
      }
      
      public void addEntry(final PhoneBook entry)
      {
          uiHandler.post(new Runnable()
          {
              @Override
              public void run() 
              {
                  list.add(entry);
                  YourCustomAdapter.notifyDataSetChanged();
              }
          });
      }
      
      }
      • 请注意,在这种情况下,您只能从 UI 线程修改基础列表

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2023-03-08
      • 2012-03-28
      • 1970-01-01
      • 2014-07-08
      • 2017-03-13
      • 1970-01-01
      • 2015-05-24
      • 2013-07-16
      • 1970-01-01
      相关资源
      最近更新 更多