Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8983115
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T20:45:21+00:00 2026-06-15T20:45:21+00:00

my app will load data from server and show on listview and save this

  • 0

my app will load data from server and show on listview and save this data to database sqlite on device.When device don’t have connect to internet, app will load data from database of device to use.My problem is when run by data have connect to server fast, but when work offline load data from database, my app run slow and lag and delay.Can you help me why so!!
Source code

public class Hoadon extends Activity {

private String IDDelivery;
private static String addresslocation = null;
private Geocoder geocoder;
private LocationManager mlocManager;
private Location loc;
private String provider = LocationManager.GPS_PROVIDER;
private ArrayList<String> phonenumberArray = new ArrayList<String>();
private ArrayList<String> codeInvoiceArray = new ArrayList<String>();
private ArrayList<String> nameArray = new ArrayList<String>();
private ArrayList<String> addressArray = new ArrayList<String>();
private ArrayList<String> urlArray = new ArrayList<String>();
private ListView listview;
private DB_Adapter mDb = new DB_Adapter(this);

// Resume ứng dụng
@Override
protected void onResume() {
    // TODO Auto-generated method stub
    Toast.makeText(this, addresslocation, Toast.LENGTH_SHORT).show();
    super.onResume();
}

// Khởi tạo ứng dụng
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.hoadon);

    // Nhận dữ liệu từ activity khác
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        IDDelivery = extras.getString("ID");
    }

    // hàm kiểm tra cài đặt gps trên thiết bị
    LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
    boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
    if (!enabled) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Thông tin GPS!");
        builder.setMessage("Bạn có muốn bật GPS không?");
        builder.setPositiveButton("Có", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // Launch settings, allowing user to make a change
                Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(i);
            }
        });
        builder.setNegativeButton("Không", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        builder.create().show();
    }

    // Lấy thông tin vị trí hiện tại của thết bị
    geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
    mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    LocationListener mlocListener = new GPSLocationListener();
    mlocManager.requestLocationUpdates(provider, 10000, 5, mlocListener);

    // Khởi động service để chuyển thông tin vị trí về server
    Intent i = new Intent(Hoadon.this, GpsService.class);
    i.putExtra("IDgps", IDDelivery);
    startService(i);
    doTimerTask();

}

public void testNetwork()
{
    // Kiểm tra kết nối đến server
    TestConnectionNew test = new TestConnectionNew();
    try {
        String recieve = test.execute("http://longvansolution.tk/monthlytarget.php").get();
        if (recieve.equalsIgnoreCase("true") && isNetworkAvailable() == true)
        {
            new LoadData().execute();
        }
        else if (recieve.equalsIgnoreCase("false") || isNetworkAvailable() == false)
        {
            String mess="Không thể kết nối đến server hoặc thiết bị chưa có kết nối internet!Ứng dụng sẽ chuyển sang hoạt động offline";
            Toast.makeText(Hoadon.this, mess, Toast.LENGTH_SHORT).show();
            workoffline();

        }

    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    // return testInternet;
}

// Hàm kiểm tra kết nối mạng trên thiết bị
public boolean isNetworkAvailable() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getActiveNetworkInfo();

    // Nếu không có kết nối mạng thì network sẽ null
    // Nếu có kết nối mạng chúng ta sẽ kết nối
    if (networkInfo != null && networkInfo.isConnected()) {

        // Log.i("net status:", "Online...!!!");
        return true;
    }
    // Log.i("net status:", "offline...!!!");
    return false;
}

// Thông báo dạng Alert
public void showAlert(final String mess) {
    Hoadon.this.runOnUiThread(new Runnable() {
        public void run() {
            AlertDialog.Builder builder = new AlertDialog.Builder(
                    Hoadon.this);
            builder.setTitle("Thông báo!");
            builder.setMessage(mess)
                    .setCancelable(false)
                    .setPositiveButton("Đồng ý",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int id) {
                                }
                            });
            AlertDialog alert = builder.create();
            alert.show();

        }
    });
}

// restart ứng dụng
@Override
protected void onRestart() {
    // TODO Auto-generated method stub
    // load dữ liệu mỗi lần khởi động lại activity
    workoffline();
    super.onRestart();
}

// Khởi tạo menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // TODO Auto-generated method stub
    MenuInflater i = getMenuInflater();
    i.inflate(R.menu.menu_hoadon, menu);
    return true;
}

// Menu activity
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // TODO Auto-generated method stub
    super.onOptionsItemSelected(item);
    switch (item.getItemId()) {
        case R.id.bando:
            Intent i = new Intent(Hoadon.this, Bando.class);
            startActivity(i);
            break;

        case R.id.chamsockhachhang:
            Intent j = new Intent(Hoadon.this, Cskh.class);
            startActivity(j);
            break;

        case R.id.logout_hoadon:
            Intent k = new Intent(Hoadon.this, GpsService.class);
            stopService(k);
            System.exit(0);
            break;

        case R.id.update:
            testNetwork();
            break;

        default:
            break;
    }
    return true;
}

// thực hiện load data từ server về theo thời gian định sẵn
public void doTimerTask() {
    TimerTask mTimerTask;
    Timer t = new Timer();
    final Handler handler = new Handler();

    mTimerTask = new TimerTask() {
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    testNetwork();
                    Log.d("TIMER", "TimerTask run");
                }
            });
        }
    };
    // public void schedule (TimerTask task, long delay, long period)
    t.schedule(mTimerTask, 500, 300000); //
}

// xử lý phím back
@Override
public void onBackPressed() {
}

// Thông báo dạng Toast
public void thongbao(String mess)
{
    Toast.makeText(Hoadon.this, mess, Toast.LENGTH_SHORT).show();
}

// load dữ liệu lên listview
public void loaddatalistview()
{
    listview = (ListView) findViewById(R.id.listView1);
    listview.setAdapter(new DataAdapter(Hoadon.this, codeInvoiceArray
            .toArray(new String[codeInvoiceArray.size()]), nameArray
            .toArray(new String[nameArray.size()]), phonenumberArray
            .toArray(new String[phonenumberArray.size()]), addressArray
            .toArray(new String[addressArray.size()])));
    listview.setOnItemClickListener(new OnItemClickListener() {

        // xử lý sự kiện khi chọn item trên listview
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            Intent j = new Intent(Hoadon.this, Menu_Main.class);

            // lấy thông tin thông qua vị trí của item được chọn
            String url = urlArray.get(position);
            String address = addressArray.get(position);
            String mahoadon = codeInvoiceArray.get(position);
            String phone = phonenumberArray.get(position);

            // chuyển thông tin này qua bên phần MENU
            j.putExtra("url", url);
            j.putExtra("address", address);
            j.putExtra("mahoadon", mahoadon);
            j.putExtra("phone", phone);
            j.putExtra("ID", IDDelivery);
            startActivity(j);
        }
    });

}

// Ứng dụng sẽ hoạt động data được lưu trong database khi thiết bị không có
// kết nối mạng
public void workoffline()
{
    codeInvoiceArray.clear();
    nameArray.clear();
    phonenumberArray.clear();
    addressArray.clear();
    urlArray.clear();
    try {
        mDb.openDB();
        Cursor mCursor = mDb.getAllInvoice(IDDelivery);
        if (mCursor.moveToFirst()) {
            do {
                codeInvoiceArray.add(mCursor.getString(1));
                nameArray.add(mCursor.getString(2));
                phonenumberArray.add(mCursor.getString(3));
                addressArray.add(mCursor.getString(4));
                urlArray.add(mCursor.getString(5));

            } while (mCursor.moveToNext());
            loaddatalistview();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    mDb.closeDB();
}

// class load data từ server về thiết bị
private class LoadData extends AsyncTask<Void, Void, Void> {
    private ProgressDialog progressDialog;
    private Boolean flag = false;
    private String phonenumber, name, address, url, code;
    private JSONArray jArray;
    private String result = null;
    private InputStream is = null;
    private StringBuilder sb = null;

    @Override
    // can use UI thread here
    protected void onPreExecute() {
        this.progressDialog = ProgressDialog.show(Hoadon.this, "",
                " Đang tải thông tin...");
    }

    @Override
    protected void onPostExecute(final Void unused) {
        this.progressDialog.dismiss();
        if (flag == true)
        {

            thongbao("Tải dữ liệu thành công");
        }
        else
        {
            thongbao("Hôm nay không có gì để giao!");
        }
        try {
            loaddatalistview();
        } catch (Exception e) {

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

    // lấy thông tin từ server về dưới dạng json, được chuyển thành chuỗi và
    // lưu vào các mảng
    @Override
    protected Void doInBackground(Void... params) {
        try {
            // Gửi thông tin id người giao hàng lên server để lấy danh sách
            // hóa đơn về
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(
                    "http://longvansolution.tk/monthlytarget.php");
            nameValuePairs = new ArrayList<NameValuePair>(1);
            nameValuePairs.add(new BasicNameValuePair("user", IDDelivery));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

            // chuyển thông tin nhận được về dạng chuỗi
            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();
        }

        // kiểm tra thông tin nhận được từ server
        if (result.equalsIgnoreCase("null\n\n \n"))
        {
            flag = false;

            // làm sạch mảng trước khi muốn thêm các thành phần để tránh
            // tình trạng trùng lặp
            phonenumberArray.clear();
            codeInvoiceArray.clear();
            nameArray.clear();
            addressArray.clear();
            urlArray.clear();
        } else
        {
            flag = true;
            try {
                jArray = new JSONArray(result);
                JSONObject json_data = null;
                phonenumberArray.clear();
                codeInvoiceArray.clear();
                nameArray.clear();
                addressArray.clear();
                urlArray.clear();
                mDb.openDB();

                // sử dụng json lấy các giá trị thông qua các key
                // gán nó vào các mảng tương ứng
                for (int i = 0; i < jArray.length(); i++) {
                    json_data = jArray.getJSONObject(i);
                    phonenumber = json_data.getString("phonenumber");
                    address = json_data.getString("address");
                    name = json_data.getString("name");
                    url = json_data.getString("url");
                    code = json_data.getString("code");
                    phonenumberArray.add(phonenumber);
                    codeInvoiceArray.add(code);
                    nameArray.add(name);
                    addressArray.add(address);
                    urlArray.add(url);
                    if (mDb.test(code) == true)
                    {
                        mDb.insert(code, name, phonenumber, address, url, "Chuagiao", IDDelivery);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();

            } catch (ParseException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        mDb.closeDB();
        return null;
    }
}

// Lấy vị trí của thiết bị
public class GPSLocationListener implements LocationListener {
    @Override
    public void onLocationChanged(Location location)
    {
        // chuyển thông tin vị trí của thiết bị thành dạng địa chỉ để hiển
        // thị cho người dùng
        loc = mlocManager.getLastKnownLocation(provider);
        GoogleDataReader reader = new GoogleDataReader();
        addresslocation = reader.GetAddressFromLatLng(loc.getLatitude(), loc.getLongitude(),
                geocoder);
    }

    @Override
    public void onProviderDisabled(String provider)
    {
    }

    @Override
    public void onProviderEnabled(String provider)
    {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras)
    {
    }
}

// Hàm trả về vị trí của thiết bị
public static String gettext() {
    // TODO Auto-generated method stub
    return addresslocation;
}
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T20:45:22+00:00Added an answer on June 15, 2026 at 8:45 pm

    You are calling the WorkOffline() method twice: first inside the testNetwork() -method, and after that in the onCreate() else statement.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

my app will load data from server and save it to database sqlite on
I have an iPhone (iOS) app that keeps data in a local SQLite database
I'm doing a app can update data every 1 minutes, data will from database
Some articles on the web tell me that System.loadLibrary() will load files in /data/data/{app
I have client/server application where the client app will open files. Those files get
My app will auto load data when i run app.My problem is when my
I have a simple app that I am doing that will load a list
I have a HighCharts client whose responsibility is to load data from a webservice
My app will allow users to create a personalised list of events from a
We have a folder where our app will be potentially reading, writing and creating/deleting

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.