1

I have one page timeline like Facebook (there are EditText and Button), it has 2 async task. The first one is used to send parameter to remote server, the second one to load data json from URL. Actually first time, program will load JSON on the listview with async, then if I wanna update status after click Button then it will insert to table on the remote server. Both of them work successfully. But I have a little problem : after click button (update status) I want to refresh my listview. I have added the code on event click button, and then added onPostExecute (Class TheTask). After I send parameter, listview does not reload contents again. Can somebody help me to solve this problem ?

my source code :

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);
        }       
    }   
}
AKHolland
  • 4,435
  • 23
  • 35
Agoeng Putz
  • 19
  • 1
  • 8
  • there is a method named invalidate(); – Maveňツ Jul 14 '14 at 13:13
  • This is not the correct way to compare `Strings` in Java `result=="SUCCESS"`. [See here](http://stackoverflow.com/questions/19432553/if-edittext-gettext-tostring-dont-work/19432569#19432569) – codeMagic Jul 14 '14 at 13:14
  • See this answer here: http://stackoverflow.com/questions/2250770/how-to-refresh-android-listview – Mel Jul 14 '14 at 14:05

2 Answers2

2

Here you have to create global Adapter and call to notifydatasetchanged() using adapter

Declare globally

ListViewTimelineAdapter adapter=null;

and replace

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

code with

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

thats it...and when ever you want to refresh list just write

adapter.NotifyDatasetChanged();

and listview reloaded...

Jayesh Khasatiya
  • 2,140
  • 1
  • 14
  • 15
  • something like this will also work: `((ListViewTimelineAdapter)listview.getAdapter()).notifyDatasetChanged();` – invertigo Jul 14 '14 at 14:25
  • @jay : So i change the code onPostExecute on GetTimelineAyncTask with yours ? if yes, I have changed it but it doesnt work. – Agoeng Putz Jul 15 '14 at 02:51
  • have you used BaseAdapter in ListViewTimelineAdapter class? if No then used it. or other way to do your task ReCall Adapter class write code adapter=new ListViewTimelineAdapter(getBaseContext(), arrtimeline); listview.setAdapter(adapter); adapter.NotifyDatasetChanged(); try this one... – Jayesh Khasatiya Jul 15 '14 at 05:53
0

This may become handy in your situation:

myListView.invalidateViews();

Original answer with some other ways explained can be found here: How to refresh Android listview?

Hope it helps.

Community
  • 1
  • 1
Mel
  • 1,730
  • 17
  • 33