继承BaseListActivity并使用AsyncTask时,ListActivity不会更新

时间:2012-05-26 19:16:46

标签: android android-asynctask listactivity

我有一个类SomeActivity扩展了BaseListActivity。 BaseListActivity扩展了ListActivity,所有这些都有效。

但是当列表必须更新时,我使用AsyncTask进行远程服务器调用,声明如下:

public class DownloadWebPageTask extends AsyncTask<String, Void, String> 

在那里,有一行来更新列表,如下所示:

adapter.notifyDataSetChanged();

但这条线似乎没有做任何事情。

知道应该有什么不同才能让它发挥作用吗?

这是BaseListActivity

public class BaseListActivity extends ListActivity {

    public ListView getListView() {
        return (ListView)findViewById(android.R.id.list);
    }

    public ListAdapter getListAdapter() {
        return getListView().getAdapter();
    }   

    @Override
    public void setContentView(int layoutResID) {    
        super.setContentView(layoutResID);
        {
            setListAdapter(this.getListAdapter());

            Button home_header = (Button) findViewById(R.id.home_header);
            Button questions_header = (Button) findViewById(R.id.questions_header);

            home_header.setOnClickListener(new Button.OnClickListener() {
                public void onClick(View v) {
                    Intent myIntent = new Intent(BaseListActivity.this,
                            ProblemioActivity.class);
                    BaseListActivity.this.startActivity(myIntent);
                }
            });

            questions_header.setOnClickListener(new Button.OnClickListener() {
                public void onClick(View v) {
                    Intent myIntent = new Intent(BaseListActivity.this,
                            MyQuestionsActivity.class);
                    BaseListActivity.this.startActivity(myIntent);
                }
            });
        }
    }
}

这是整个DownloadWebPageTask代码:

public class DownloadWebPageTask扩展了AsyncTask {
        @覆盖         protected String doInBackground(String ... theParams)         {             字符串myUrl = theParams [0];             final String user_id = theParams [1];

        String charset = "UTF-8";           
        String response = null;

        try 
        {                           
            String query = String.format("user_id=%s", 
                     URLEncoder.encode( user_id, charset) );

            final URL url = new URL( myUrl + "?" + query );

            Log.d( "QuestionUserURL" , url+ "" );

            final HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setDoOutput(true); 
            conn.setRequestMethod("POST");

            conn.setDoOutput(true);
            conn.setUseCaches(false);

            conn.connect();

            final InputStream is = conn.getInputStream();
            final byte[] buffer = new byte[8196];
            int readCount;
            final StringBuilder builder = new StringBuilder();
            while ((readCount = is.read(buffer)) > -1) 
            {
                builder.append(new String(buffer, 0, readCount));
            }

            response = builder.toString();      
        } 
        catch (Exception e) 
        {
                Log.d( "EXCEPTIONNNN: " , "Yup" + e.getMessage());
                e.printStackTrace();
        }

        Log.d( "MyQuestionsActivity" , "*** Response: " + response );
        return response;
    }

    @Override
    protected void onPostExecute(String result) 
    {
        Log.d( "MyQuestionsActivity" , "In the post-execute method: " + result );

        if ( result != null && result.trim().equals( "no_user_id" ) )
        {
            Log.d( "Post execute: " , "NOOOT  OKKKK - no user id" );    
            // Show the user a message that they did not enter the right login

            Toast.makeText(getApplicationContext(), "Could not get your questions. We are working to fix this. ", Toast.LENGTH_LONG).show();                                

        sendEmail("Error in My Questions", "The questions by user did not load because on the server the validation for user id said the user id was empty." );     
        }
        else
        if ( result != null && result.trim().equals( "database_error" ) )
        {
            Log.d( "Post execute: " , "NOOOT  OKKKK - no user database error" );    
            // Show the user a message that they did not enter the right login

            Toast.makeText(getApplicationContext(), "Could not get your questions. We are working to fix this. ", Toast.LENGTH_LONG).show();                                

        sendEmail("Error in My Questions", "The questions by user did not load because on the server there " +
                "was a database error." );                  
        }
        else
        if ( result != null && result.trim().equals( "no_questions_by_user" ) )
        {           
            // Show the user a message that they did not enter the right login

            //Toast.makeText(getApplicationContext(), "You have not asked any questions.  Ask your business questions! ", Toast.LENGTH_LONG).show();                                

        //sendEmail("No Questions so far in My Questions", "User got message that they do not have questions." );           

        TextView question_label = (TextView) findViewById(R.id.question_label);
        question_label.setText("You have not asked any business questions.  Ask your question." );
        }
        else
        {
            Log.d( "MyQuestionsActivity" , "In JSON parsing area.." );

                try
                {   
                    JSONArray obj = new JSONArray(result);

                    if ( obj != null )
                    {
                        questions.clear();

                        for ( int i = 0; i < obj.length(); i++ )
                        {
                            JSONObject o = obj.getJSONObject(i);

                            String question_id = o.getString("question_id");
                            String question = o.getString("question");
                            String questioner_id = o.getString("member_id");
                            String first_name = o.getString("first_name");
                            String last_name = o.getString("last_name");

                            Log.d( "Question: " , question );                               
                            Log.d( "Question_id: " , question_id );       

                            Question q = new Question ( );
                            q.setQuestion(question);
                            q.setQuestionId(question_id);
                            q.setQuestionByMemberId( questioner_id );

                            q.setAuthorName(first_name + " " + last_name );

                            questions.add( q );
                        }
                    }

                    adapter.notifyDataSetChanged();

                    TextView question_label = (TextView) findViewById(R.id.question_label);
                    question_label.setText("The questions you asked are below. Choose one or ask a new question.");
                }                   
                catch ( Exception e )
                {
                    Log.d( "MyQuestionsActivity: " , "some crap happened 1: " + e.getMessage() );
                    e.printStackTrace();
                }
            }

            //adapter.notifyDataSetChanged();                       
        }
    }        

这是我现在在日志中看到的例外:

05-26 19:59:55.774: W/System.err(3103): java.net.UnknownHostException: Unable to resolve host "www.problemio.com": No address associated with hostname
05-26 19:59:55.777: W/System.err(3103):     at java.net.InetAddress.lookupHostByName(InetAddress.java:426)
05-26 19:59:55.777: W/System.err(3103):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
05-26 19:59:55.777: W/System.err(3103):     at java.net.InetAddress.getAllByName(InetAddress.java:220)
05-26 19:59:55.777: W/System.err(3103):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:71)
05-26 19:59:55.777: W/System.err(3103):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
05-26 19:59:55.777: W/System.err(3103):     at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:351)
05-26 19:59:55.777: W/System.err(3103):     at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:86)
05-26 19:59:55.777: W/System.err(3103):     at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
05-26 19:59:55.777: W/System.err(3103):     at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:308)
05-26 19:59:55.777: W/System.err(3103):     at libcore.net.http.HttpEngine.connect(HttpEngine.java:303)
05-26 19:59:55.777: W/System.err(3103):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282)
05-26 19:59:55.777: W/System.err(3103):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232)
05-26 19:59:55.797: W/System.err(3103):     at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
05-26 19:59:55.807: W/System.err(3103):     at utils.SendEmail.doInBackground(SendEmail.java:38)
05-26 19:59:55.807: W/System.err(3103):     at utils.SendEmail.doInBackground(SendEmail.java:1)
05-26 19:59:55.819: W/System.err(3103):     at android.os.AsyncTask$2.call(AsyncTask.java:264)
05-26 19:59:55.827: W/System.err(3103):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
05-26 19:59:55.827: W/System.err(3103):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
05-26 19:59:55.837: W/System.err(3103):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:208)
05-26 19:59:55.837: W/System.err(3103):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
05-26 19:59:55.847: W/System.err(3103):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
05-26 19:59:55.847: W/System.err(3103):     at java.lang.Thread.run(Thread.java:856)
05-26 19:59:55.956: W/System.err(3103): Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
05-26 19:59:56.177: D/dalvikvm(3103): GC_CONCURRENT freed 406K, 6% free 9330K/9863K, paused 32ms+6ms

但异常并不准确。我能够解决该主机没问题。在我添加BaseListActivity之前,这个代码曾经用过。

谢谢!

1 个答案:

答案 0 :(得分:1)

ListAdapter重新设置为ListView将与调用adapter.notifyDataSetChanged();相同,我认为notifyDataSetChanged();仅在您使用数据库Cursor对象时才有效数据提供者。而不是adapter.notifyDataSetChanged();只需致电setListAdapter();哪个实习生将重建ListView