如何在asynctask android之后刷新listview

时间:2014-07-14 13:10:28

标签: android listview

我有一个像Facebook这样的页面时间轴(有EditText和Button),它有2个异步任务。第一个用于向远程服务器发送参数,第二个用于从URL加载数据json。实际上,第一次,程序将使用async在listview上加载JSON,然后如果我想在单击Button后更新状态,那么它将插入远程服务器上的表。它们都成功地运作了。但我有一点问题:点击按钮(更新状态)后我想刷新我的列表视图。我在事件单击按钮上添加了代码,然后添加了onPostExecute(Class TheTask)。发送参数后,listview不会再次重新加载内容。有人可以帮我解决这个问题吗?

我的源代码:

public class Timeline extends Activity {
    private static String BaseUrl="";
    private String status;
    final int PROGRESS_DIALOG=1;
    private ProgressBar pb;

    ViewConnection connection;

    ArrayList<URLPostClass> timelinelist=new ArrayList<URLPostClass>();         
    ArrayList<URLPostClass> arrtimeline=new ArrayList<URLPostClass>();  
    //ArrayList<String> arritemcategory;

    ListView listview;
    //ListViewAdapter ListViewAdapter;

    @Override
    protected Dialog onCreateDialog(int id) {
        switch(id)
        {
        case PROGRESS_DIALOG:
            ProgressDialog progress =new ProgressDialog(this);
            progress.setMessage("Loading");
            progress.setTitle("Memuat status");         
            progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progress.setProgress(0);
            progress.setMax(100);           
            return progress;
        }
        return super.onCreateDialog(id);
    }

    private class GetTimelineAyncTask extends AsyncTask<Hashtable<String,String>,Void,String> {             
        @Override
        protected void onPreExecute() {
            showDialog(PROGRESS_DIALOG);
            super.onPreExecute();
        } 
        @Override
        protected String doInBackground(Hashtable<String, String>... params) 
        {
            // TODO Auto-generated method stub
            Hashtable ht=params[0];         

            String json=HelperHttp.getJSONResponseFromURL(BaseUrl, ht);
            if(json!=null) {
                parseJsonString(timelinelist,json); 
            }else{
                return "No internet access";
            }
            return json;
        }               

        protected void parseJsonString(ArrayList<URLPostClass> timelinelistjs,String json){
            try {               
                JSONObject jsonObj = new JSONObject(json);
                JSONArray array = jsonObj.getJSONArray("listtimeline");             

                URLPostClass.setlength(array.length());

                for (int i=0;i<array.length();i++){
                    JSONObject js=array.getJSONObject(i);

                    URLPostClass timeline=new URLPostClass(js.getString("IdTimeline"),
                            js.getString("NamaSales"),
                            js.getString("JenisStatus"),
                            js.getString("Remark"),
                            js.getString("TgglInsert"),
                            js.getString("Path"));
                    timelinelistjs.add(timeline);
                }
            }catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        protected void onPostExecute(String result){
            if(result=="SUCCESS")
            {
            }else{              
                DecimalFormat formatter = new DecimalFormat("#,###,###");

                JSONObject jObject = null;
                Context mContext = null;
                try {                   
                    jObject = new JSONObject(result);
                    JSONArray jArray = jObject.getJSONArray("listtimeline");

                    for (int i=0; i < jArray.length(); i++)
                    {                     
                        JSONObject oneObject=jArray.getJSONObject(i);                   
                        URLPostClass timeline=new URLPostClass(oneObject.getString("IdTimeline"),
                                oneObject.getString("NamaSales"),
                                oneObject.getString("JenisStatus"),
                                oneObject.getString("Remark"),
                                oneObject.getString("TgglInsert"),
                                oneObject.getString("Path"));   
                        arrtimeline.add(timeline);                          
                    }               
                    listview = (ListView) findViewById(R.id.listtimeline); 
                    listview.setAdapter(new ListViewTimelineAdapter(getBaseContext(), arrtimeline));                                        
                }catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            removeDialog(PROGRESS_DIALOG);
            super.onPostExecute(result);
        }       
    }   

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_timeline);
        Global.Timeline=this;

        final RadioButton rbtnlisting=(RadioButton)findViewById(R.id.rbtnlisting);
        final RadioButton rbtnclosing=(RadioButton)findViewById(R.id.rbtnclosing);
        final RadioButton rbtnprospek=(RadioButton)findViewById(R.id.rbtnprospek);      
        final EditText edtstatus=(EditText)findViewById(R.id.edtstatus);
        Button btnpost=(Button)findViewById(R.id.btnpost);

        edtstatus.setTextSize(TypedValue.COMPLEX_UNIT_PX, getBaseContext().getResources().getDimensionPixelSize( R.dimen.lbltitlelistviewitem));
        btnpost.setTextSize(TypedValue.COMPLEX_UNIT_PX, getBaseContext().getResources().getDimensionPixelSize( R.dimen.lbltitlelistviewitem));
        rbtnlisting.setTextSize(TypedValue.COMPLEX_UNIT_PX, getBaseContext().getResources().getDimensionPixelSize( R.dimen.lbltitlelistviewitem));
        rbtnclosing.setTextSize(TypedValue.COMPLEX_UNIT_PX, getBaseContext().getResources().getDimensionPixelSize( R.dimen.lbltitlelistviewitem));
        rbtnprospek.setTextSize(TypedValue.COMPLEX_UNIT_PX, getBaseContext().getResources().getDimensionPixelSize( R.dimen.lbltitlelistviewitem));  

        listview = (ListView) findViewById(R.id.listtimeline); 

        pb=(ProgressBar)findViewById(R.id.progressBar1);
        pb.setVisibility(View.GONE);        

        connection = new ViewConnection(getBaseContext());
        if (connection.isConnectingToInternet())
        {
            btnpost.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {                           
                    if (edtstatus.getText().length()>5) {
                        pb.setVisibility(View.VISIBLE);
                        TheTask async=new TheTask();
                        async.execute("ccc");                                                   
                    }else {
                        Toast.makeText(getBaseContext(), "Your status is too short", Toast.LENGTH_LONG).show();
                    }           
                }
            });         

            BaseUrl="http://xxx.xxx.xxx.xxx/dummy/gettimeline.php";
            executeAsyncTask();             
        }else {

            // Internet connection is not present
            LayoutInflater li = LayoutInflater.from(Timeline.this);
            final View inputdialogcustom = li.inflate(R.layout.activity_confirm_connection, null);              
            AlertDialog.Builder alert = new AlertDialog.Builder(Timeline.this);                                             
            alert.setView(inputdialogcustom);       

            alert.setPositiveButton("OK", new DialogInterface.OnClickListener() { 
                @Override
                public void onClick(DialogInterface dialog, int which) {                                
                    System.exit(0);
                }
            }); 
            alert.show();
        }       

    }
    class TheTask extends AsyncTask<String, Integer, Double>
    {
        @Override
        protected Double doInBackground(String... params) {         
            postData(params[0]);
            return null;            
        }       

        protected void onPostExecute(Double result) {
            // TODO Auto-generated method stub
            pb.setVisibility(View.GONE);
            Toast.makeText(getApplicationContext(), "Status telah diposting !", Toast.LENGTH_LONG).show();

            BaseUrl="http://xxx.xxx.xxx.xxx/dummy/gettimeline.php"; // I PUT ON HERE
            executeAsyncTask();
        }
        protected void onProgressUpdate(Integer... progress){
            pb.setProgress(progress[0]);
        }       

        public void postData(String valueIWantToSend) {
            // Create a new HttpClient and Post Header
            RadioButton rbtnlisting=(RadioButton)findViewById(R.id.rbtnlisting);
            RadioButton rbtnclosing=(RadioButton)findViewById(R.id.rbtnclosing);
            RadioButton rbtnprospek=(RadioButton)findViewById(R.id.rbtnprospek);        
            EditText edtstatus=(EditText)findViewById(R.id.edtstatus);          

            if (edtstatus.getText().length()>5) {
                RadioGroup radiotipe = (RadioGroup) findViewById(R.id.radiotipe);
                int selectedId = radiotipe.getCheckedRadioButtonId();

                RadioButton rbtnselected=(RadioButton) findViewById(selectedId);
                status=rbtnselected.getText().toString();

                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://xxx.xxx.xxx.xxx/dummy/insert.php");
                try {               
                    // Add your data
                    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
                    nameValuePairs.add(new BasicNameValuePair("idsales",OtherClass.getIdSales().toString()));
                    nameValuePairs.add(new BasicNameValuePair("jenis", status));
                    nameValuePairs.add(new BasicNameValuePair("remark", edtstatus.getText().toString()));
                    nameValuePairs.add(new BasicNameValuePair("path", "coba coba"));
                    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                    // Execute HTTP Post Request
                    HttpResponse response=httpclient.execute(httppost);
                } 
                catch (ClientProtocolException e) 
                {
                    e.printStackTrace();
                    // TODO Auto-generated catch block
                } catch (IOException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }                   

            }else {
                Toast.makeText(getBaseContext(), "Your status is too short", Toast.LENGTH_LONG).show();
            }
        }       
    }
    private void executeAsyncTask(){
        Hashtable<String,String> ht=new Hashtable<String,String>();
        GetTimelineAyncTask async=new GetTimelineAyncTask();
        Hashtable[] ht_array={ht};
        async.execute(ht_array);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        //getMenuInflater().inflate(R.menu.tab_sport, menu);
        MenuInflater inflater=getMenuInflater();
        inflater.inflate(R.menu.menutimeline, menu);        

        return super.onCreateOptionsMenu(menu);
    }   

    @SuppressLint("NewApi")
    public boolean onOptionsItemSelected(MenuItem item) {       
        switch(item.getItemId())
        {
            case R.id.menulogout:
                //Toast.makeText(getBaseContext(), "test", Toast.LENGTH_LONG).show();

                //View view = item.getActionView();
                //final EditText edtsearchitem=(EditText)view.findViewById(R.id.edtsearchitem);             
                OtherClass.setIdSales("");              
                Global.Timeline.finish();                       

                Intent MyIntentDetailItem=new Intent(getBaseContext(), MainActivity.class);                         
                startActivity(MyIntentDetailItem);

                return true;
            default:
                return super.onOptionsItemSelected(item);
        }       
    }   
}

2 个答案:

答案 0 :(得分:2)

在这里,你必须创建全局适配器并使用适配器

调用notifydatasetchanged()

全球宣布

ListViewTimelineAdapter adapter = null;

并替换

listview = (ListView) findViewById(R.id.listtimeline); 
                    listview.setAdapter(new ListViewTimelineAdapter(getBaseContext(), arrtimeline));

代码

listview = (ListView) findViewById(R.id.listtimeline); 
adapter=new ListViewTimelineAdapter(getBaseContext(), arrtimeline);
listview.setAdapter(adapter);
adapter.NotifyDatasetChanged();

多数民众赞成......当你想要刷新列表时,只需写下

adapter.NotifyDatasetChanged();

和listview重新加载......

答案 1 :(得分:0)

在您的情况下,这可能会变得很方便:

myListView.invalidateViews();

原始答案以及其他一些解释方法可以在这里找到: How to refresh Android listview?

希望它有所帮助。