Giúp đỡ về auto loadding refesh data

vip_traivinh

New Member
15/3/20
3
0
1
ha noi
Em mới học về lập trình android studio. Em có đoạn code muốn nó tự động load lại dữ liệu. Code sử dụng AsyncTask. Cụ nào có thể chỉ giùm em được không ah.
Code:
package com.androidjson.userloginreg_androidjsoncom;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import android.os.Handler;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Window;
import android.widget.ListView;
import android.widget.Toast;
/*
 * @author Firzan Ghulam
 */
public class muachuyen extends Activity {
    private Handler mHandler;
    JSONArray jArray;
    String result = null;
    InputStream is = null;
    StringBuilder sb = null;
    ArrayList<String> al = new ArrayList<String>();
    ArrayList<String> al1 = new ArrayList<String>();
    ArrayList<String> al2 = new ArrayList<String>();
    ArrayList<String> al3 = new ArrayList<String>();
    ArrayList<String> al4 = new ArrayList<String>();
    ArrayList<String> al5 = new ArrayList<String>();
    String targetmonth;
    String targetyear;
    String targetamount;
    String targetgiatien;
    String targetngay;
    String targetgio;
    //    int responseCode;
    //int listItemCount=0;
    ListView listview ;
    private Object Runnable;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(Color.WHITE);
        setTitleColor(Color.rgb(0x74, 0, 0x37));
        setTitle("DEMO PHP");
        requestWindowFeature(Window.FEATURE_RIGHT_ICON);
        setContentView(R.layout.activity_muachuyen);

        listview = (ListView) findViewById(R.id.listView1);
        this.mHandler = new Handler();

        this.mHandler.postDelayed((java.lang.Runnable) Runnable,5000);

        new LoadData().execute();
    }

    private class LoadData extends AsyncTask<Void, Void, Void> {
        private ProgressDialog progressDialog;

        @Override
        // can use UI thread here
        protected void onPreExecute() {
            this.progressDialog = ProgressDialog.show(muachuyen.this, "", " Loading...");
        }

        @Override
        protected void onPostExecute(final Void unused) {
            try {

                listview.setAdapter(new DataAdapter(muachuyen.this, al.toArray(new String[al.size()]), al1.toArray(new String[al1.size()]), al2.toArray(new String[al2.size()]), al3.toArray(new String[al3.size()]), al4.toArray(new String[al4.size()]), al5.toArray(new String[al5.size()])));
                this.progressDialog.dismiss();
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
            }
        }

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub
            // HTTP post

                    try {
                        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                        HttpClient httpclient = new DefaultHttpClient();
                        try {
                            HttpPost httppost = new HttpPost("http://xxx/android/muachuyen.php");

                            StringEntity se = new StringEntity("envelope", HTTP.UTF_8);
                            httppost.setEntity(se);
                            HttpParams httpParameters = new BasicHttpParams();
                            // Set the timeout in milliseconds until a connection is established.
                            int timeoutConnection = 3000;
                            HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
                            // Set the default socket timeout (SO_TIMEOUT)
                            // in milliseconds which is the timeout for waiting for data.
                            int timeoutSocket = 3000;
                            HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

                            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                            HttpResponse response = httpclient.execute(httppost);
                            HttpEntity entity = response.getEntity();
                            is = entity.getContent();
                        } catch (Exception e) {
                            Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
                        }
                        //buffered reader
                        try {
                            BufferedReader reader = new BufferedReader(new InputStreamReader(
                                    is, "iso-8859-1"), 80);
                            sb = new StringBuilder();
                            sb.append(reader.readLine() + "\n");
                            String line = "0";
                            while ((line = reader.readLine()) != null) {
                                sb.append(line + "\n");
                            }
                            is.close();
                            result = sb.toString();
                        } catch (Exception e) {
                            Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
                        }
                        try {
                            jArray = new JSONArray(result);
                            JSONObject json_data = null;
                            for (int i = 0; i < jArray.length(); i++) {
                                json_data = jArray.getJSONObject(i);
                                targetamount = json_data.getString("name");
                                targetmonth = json_data.getString("nguoidang");
                                targetyear = json_data.getString("loaixe");
                                targetgiatien = json_data.getString("giacuoc");
                                targetgio = json_data.getString("giodang");
                                targetngay = json_data.getString("ngaydang");
                                al.add(targetmonth);
                                al1.add(targetyear);
                                al2.add(targetamount);
                                al3.add(targetgiatien);
                                al4.add(targetgio);
                                al5.add(targetngay);

                                //listItemCount=al2.size();
                            }
                        } catch (JSONException e) {
                            Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
                        }
                    } catch (ParseException e) {
                        //    Log.e("log_tag", "Error in http connection" + e.toString());
                        Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
                    } catch (Exception e) {
                        //    Log.e("log_tag", "Error in http connection" + e.toString());
                        Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
                    }

          return null;
        }

    }
}
 

vip_traivinh

New Member
15/3/20
3
0
1
ha noi
Em đã refesh được rồi nhưng có một lỗi là khi nó load lại. đồng nghĩa với việc con trỏ chuột sẽ kéo lên hàng đầu tiên. Em không muốn như vậy mà muốn con trỏ di chuyển ở đâu sẽ nằm ở nguyên chỗ đó có cách nào không ah
Code:
package com.androidjson.userloginreg_androidjsoncom;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import android.os.Handler;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.method.TextKeyListener;
import android.view.Window;
import android.widget.ListView;
import android.widget.Toast;
import android.os.SystemClock;

/*
 * @author Firzan Ghulam
 */
public class muachuyen extends Activity {
    JSONArray jArray;
    String result = null;
    InputStream is = null;
    StringBuilder sb = null;
    ArrayList<String> al = new ArrayList<String>();
    ArrayList<String> al1 = new ArrayList<String>();
    ArrayList<String> al2 = new ArrayList<String>();
    ArrayList<String> al3 = new ArrayList<String>();
    ArrayList<String> al4 = new ArrayList<String>();
    ArrayList<String> al5 = new ArrayList<String>();
    String targetmonth;
    String targetnoidung1;
    String targetnoidung3;
    String targetnoidung2;
    String targetngay;
    String targetgio;
    //    int responseCode;
    //int listItemCount=0;
    ListView listview ;
    private Handler mHandler;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(Color.WHITE);
        setTitleColor(Color.rgb(0x74, 0, 0x37));
        setTitle("DEMO PHP");
        requestWindowFeature(Window.FEATURE_RIGHT_ICON);
        setContentView(R.layout.activity_muachuyen);

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

        this.mHandler = new Handler();
        this.mHandler.postDelayed(m_Runnable,5);
    }
    private final Runnable m_Runnable = new Runnable()
    {
        @Override
        public void run()

        {
            new LoadData().execute();
            muachuyen.this.mHandler.postDelayed(m_Runnable, 2000);
            al.clear();
            al1.clear();
            al2.clear();
            al3.clear();
        }
    };//runnable



    @Override
    protected void onPause() {
        super.onPause();
        mHandler.removeCallbacks(m_Runnable);
        finish();

    }
    private class LoadData extends AsyncTask<Void, Void, Void> {
        private ProgressDialog progressDialog;

        @Override
        // can use UI thread here
        protected void onPreExecute() {

        }

        @Override
        protected void onPostExecute(final Void unused) {
            try {

                listview.setAdapter(new DataAdapter(muachuyen.this, al.toArray(new String[al.size()]), al1.toArray(new String[al1.size()]), al2.toArray(new String[al2.size()]), al3.toArray(new String[al3.size()])));

            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
            }
        }

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub
            // HTTP post

                    try {
                        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                        HttpClient httpclient = new DefaultHttpClient();
                        try {
                            HttpPost httppost = new HttpPost("xxx/android/muachuyen.php");

                            StringEntity se = new StringEntity("envelope", HTTP.UTF_8);
                            httppost.setEntity(se);
                            HttpParams httpParameters = new BasicHttpParams();
                            // Set the timeout in milliseconds until a connection is established.
                            int timeoutConnection = 3000;
                            HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
                            // Set the default socket timeout (SO_TIMEOUT)
                            // in milliseconds which is the timeout for waiting for data.
                            int timeoutSocket = 3000;
                            HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

                            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                            HttpResponse response = httpclient.execute(httppost);
                            HttpEntity entity = response.getEntity();
                            is = entity.getContent();
                        } catch (Exception e) {
                            Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
                        }
                        //buffered reader
                        try {
                            BufferedReader reader = new BufferedReader(new InputStreamReader(
                                    is, "iso-8859-1"), 80);
                            sb = new StringBuilder();
                            sb.append(reader.readLine() + "\n");
                            String line = "0";
                            while ((line = reader.readLine()) != null) {
                                sb.append(line + "\n");
                            }
                            is.close();
                            result = sb.toString();
                        } catch (Exception e) {
                            Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
                        }
                        try {
                            jArray = new JSONArray(result);
                            JSONObject json_data = null;
                            for (int i = 0; i < jArray.length(); i++) {
                                json_data = jArray.getJSONObject(i);
                                targetmonth = json_data.getString("nguoidang");
                                targetnoidung1 = "Điểm Đón:"+ "\n" + json_data.getString("diemdon")+"\n\n" + "Điểm Đến:" +"\n" + json_data.getString("diemden");
                                targetnoidung2 ="Loại Xe:" + json_data.getString("loaixe")+"\n"
                                                + "Giá Tiền:" + json_data.getString("giacuoc")+"\n"
                                               + "Ngày:" + json_data.getString("date");
                                targetnoidung3 = "Ngày Đi:"+ "\n" + json_data.getString("ngaydang")+"\n" + "Giờ Đi:"+ "\n" + json_data.getString("thoigian");
                                al.add(targetmonth);
                                al1.add(targetnoidung1);
                                al2.add(targetnoidung2);
                                al3.add(targetnoidung3);

                                //listItemCount=al2.size();
                            }
                        } catch (JSONException e) {
                            Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
                        }
                    } catch (ParseException e) {
                        //    Log.e("log_tag", "Error in http connection" + e.toString());
                        Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
                    } catch (Exception e) {
                        //    Log.e("log_tag", "Error in http connection" + e.toString());
                        Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
                    }

          return null;
        }

    }
}
 

Joe

Thành viên VIP
21/1/13
3,022
1,335
113
Could you explain your problem in English?
 

vip_traivinh

New Member
15/3/20
3
0
1
ha noi
Could you explain your problem in English?
I Want autoResfesh Listview When Charger Mysql. Please help me!

Code:
Code:
package com.androidjson.userloginreg_androidjsoncom;
import android.support.v7.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.app.Activity;
import com.androidjson.userloginreg_androidjsoncom.muachuyen.ListAdapterClass;
import com.androidjson.userloginreg_androidjsoncom.muachuyen.HttpServicesClass;
import com.androidjson.userloginreg_androidjsoncom.muachuyen.subjects;
import android.os.Handler;
public class Muachuyen extends AppCompatActivity {

    ListView SubjectListView;
    ProgressBar progressBarSubject;
    String ServerURL = "http://xxxx/muachuyen.php";
    private Handler mHandler;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_muachuyen);
        SubjectListView = (ListView)findViewById(R.id.listview1);
        progressBarSubject = (ProgressBar)findViewById(R.id.progressBar);
        new GetHttpResponse(Muachuyen.this).execute();
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                new GetHttpResponse(Muachuyen.this).execute();
            }
        });
    }

    private class GetHttpResponse extends AsyncTask<Void, Void, Void>
    {
        public Context context;

        String ResultHolder;

        List<subjects> subjectsList;

        public GetHttpResponse(Context context)
        {
            this.context = context;
        }

        public GetHttpResponse() {

        }

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... arg0)
        {
            HttpServicesClass httpServiceObject = new HttpServicesClass(ServerURL);
            try
            {
                httpServiceObject.ExecutePostRequest();

                if(httpServiceObject.getResponseCode() == 200)
                {
                    ResultHolder = httpServiceObject.getResponse();

                    if(ResultHolder != null)
                    {
                        JSONArray jsonArray = null;

                        try {
                            jsonArray = new JSONArray(ResultHolder);

                            JSONObject jsonObject;

                            subjects subjects;

                            subjectsList = new ArrayList<subjects>();

                            for(int i=0; i<jsonArray.length(); i++)
                            {
                                subjects = new subjects();

                                jsonObject = jsonArray.getJSONObject(i);

                                subjects.SubjectName = "Điểm Đón:"+ "\n" + jsonObject.getString("diemdon")+"\n\n" + "Điểm Đến:" +"\n" + jsonObject.getString("diemden");
                                subjects.SubjectDulieu2 = "Loại Xe:" + jsonObject.getString("loaixe")+"\n"
                                        + "Giá Tiền:" + jsonObject.getString("giacuoc")+"\n"
                                        + "Ngày:" + jsonObject.getString("date");
                                subjects.SubjectDulieu3 = "Ngày Đi:"+ "\n" + jsonObject.getString("ngaydang")+"\n" + "Giờ Đi:"+ "\n" + jsonObject.getString("thoigian");
                                subjects.SubjectDulieu4 = "Giờ Đi: " + jsonObject.getString("thoigian");
                                subjectsList.add(subjects);
                            }
                        }
                        catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
                else
                {
                    Toast.makeText(context, httpServiceObject.getErrorMessage(), Toast.LENGTH_SHORT).show();
                }
            }
            catch (Exception e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
            //Code for the UiThread
        }

        @Override
        protected void onPostExecute(Void result)

        {
            progressBarSubject.setVisibility(View.GONE);

            SubjectListView.setVisibility(View.VISIBLE);

            if(subjectsList != null)
            {


                final ListAdapterClass adapter = new ListAdapterClass(subjectsList, context);
                SubjectListView.setAdapter(adapter);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter.notifyDataSetChanged();
                        Toast.makeText(context, "chạy", Toast.LENGTH_SHORT).show();
                    }
                });
            }

        }

    }

}
 

Joe

Thành viên VIP
21/1/13
3,022
1,335
113
Working with GUI requires some synchronization between the main thread (app) and the component thread (e.g. Listview update or refresh). There are many ways to synchronize the two. How to do that? Run a Runnable that does the Refesh in Android. InvokeLater() in JAVA-SWING and runLater() in JavaFX. You could consult the codes posted HERE on Stackoverflow.com for more (see the Runnable part).