簡體   English   中英

如何從AsyncTask更新ListView

[英]How to update listview from AsyncTask

首先很抱歉,如果它是重復的,因為我在問它,因為無法從其他問題中理解任何東西,或者我可以說我無法在我的情況下執行它。 實際上,我堅持要用AsyncTask網絡更新一個ListView來更新我的ListView的情況,但是現在如何實現它,不知道我嘗試了幾件事但無法使其工作。 請任何人詳細解釋我如何做,這是我的活動和異步類代碼

    package app.balaji.sid.listapp;

    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.support.v7.app.ActionBarActivity;
    import android.util.Log;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.widget.ArrayAdapter;
    import android.widget.ListView;

    import it.sauronsoftware.ftp4j.FTPClient;
    import it.sauronsoftware.ftp4j.FTPFile;


    public class ListActivity extends ActionBarActivity {
        ListView lv;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_list);
            lv=(ListView)findViewById(R.id.listView);
            String[] values = new String[] { "Item 1",
                    "Item 2",
                    "Item 3 ",
                    "Item 4",
                    "Item 5",
                    "Item 6",
                    "Item 7",
                    "Item 8"
            };
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_1, android.R.id.text1, values);
            lv.setAdapter(adapter);
            new ListFetcher().execute();


        }


        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.list, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();
            if (id == R.id.action_settings) {
                return true;
            }
            return super.onOptionsItemSelected(item);
        }

        protected class ListFetcher extends AsyncTask<String,String,String>{
            String sid;


            @Override
            protected String doInBackground(String... params) {
                String user = "user";
                String pass="password";
                String host="204.236.238.164";

                FTPClient client = new FTPClient();

                try {

                    client.connect(host,21);
                    client.login(user, pass);
                    client.setType(FTPClient.TYPE_BINARY);
                    client.changeDirectory("/");

                    FTPFile[] files = client.list();
                    String[] fileNames = new String[files.length];

                    for (int i = 0; i < files.length; i++)
                    {
                        fileNames[i] = files[i].getName();
                        String logVariable=fileNames[i];
                        Log.v(sid, logVariable);     // Here i am able to see list in log
                    }

                   }catch (Exception e)
                {

                    Log.v(sid,e.toString());
                }





                return sid;
            }

            protected void onPostExecute()
            {

    //i think list should be updated from here but don't know how to do it correctly
    // i just know i can update my listview by creating a new adapter and assign it to listview but don't know how
// also i am not able to get the fileNames array here

            }



        }
    }

如果您發布了您嘗試過的欺騙對象的鏈接並解釋了您不了解的內容,則答案會更容易回答。 發生/未發生的事情也將有所幫助。 但是,據我onPostExecute() ,您只需要將新的String傳遞給onPostExecute()並在那里更新列表和Adapter

protected void onPostExecute(String result)  // get the String you are passing
{

    //i think list should be updated from here but don't know how to do it correctly
    // I agree. Let's try this
    if(result != null)  // let's make sure you got something
    {
         values.add(result);  // add the new String to your list
         adapter.notifyDataSetChanged();  // Hey, Adapter, we've got some new data

}

您需要將Array更改為ArrayList以便長度可以是動態的。 您還需要使用它和Adapter成員變量,以便內部類可以看到它們。

public class ListActivity extends ActionBarActivity {
    ListView lv;

    // Declare them here
    ArrayAdapter<String> adapter;
    ArrayList<String> values = new ArrayList<String>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list);
    lv=(ListView)findViewById(R.id.listView);
    values.add("Item 1");
    values.add("Items 2");

    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
            android.R.id.text1, values);
    lv.setAdapter(adapter);
    new ListFetcher().execute();

您沒有向任務傳遞任何內容,但想返回一個數組

 @Override
        protected String[] doInBackground(Void... params) {

 protected void onPostExecute(String[] result)

如果您要為適配器返回一組全新的值,則可以使用新值對其進行更新。 如果您只是添加一些值,則可以遍歷它們並將它們添加到ArrayList並像上面顯示的那樣調用notifyDataSetChanged()

我只是解決了我的問題,所以以為我需要分享它,這樣其他面臨相同問題的人就可以輕松解決。

因此,首先在我的問題中,我只是用字符串參數聲明了AsyncTask類,但實際上我需要從此處填充ListView。

所以我做了什么:

 protected class ListFetcher extends AsyncTask<ArrayList,ArrayList,ArrayList>{
        String sid;
        ArrayList list;



        @Override
        protected ArrayList doInBackground(ArrayList... params) {
 FTPClient client = new FTPClient();

            try {

                client.connect(host,21);
                client.login(user, pass);
                client.setType(FTPClient.TYPE_BINARY);
                client.changeDirectory("/");

                FTPFile[] files = client.list();
                String[] fileNames = new String[files.length];

                for (int i = 0; i < files.length; i++)
                {
                    fileNames[i] = files[i].getName();
 String logVariable=fileNames[i];
                    Log.v(sid, logVariable);
                    values.add(fileNames[i]);

                }

               }catch (Exception e)
            {

                Log.v(sid,e.toString());
            }





            return list;
        }

        protected void onPostExecute(final ArrayList  result)//received result but didn't use it because in my case i don't need it instead of it i just updated my arraylist in doInbackground and updated my ui from here
        {


            adapter = new ArrayAdapter<String>(ListActivity.this, android.R.layout.simple_list_item_1, android.R.id.text1, values);
            ListView listView =(ListView)findViewById(R.id.listView);

            listView.setAdapter(adapter);




        }

暫無
暫無

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

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