user7641488
user7641488

Reputation:

How to create Async Task loading back ground while get data from data base

I just created a simple project that get data by Using Selects forms from sql server data base,as it loads and take a bit of time while getting data from data base all I need I want to make a loading bar or icon in a form of async task while getting data from data base as it shows this loading bar after get data it removes the loading bar here's my data base helper class

package abtech.waiteriano.com.waitrer.data_base_helper;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * Created by Mitch on 2016-05-13.
 */
public class DatabaseHelper extends SQLiteOpenHelper {

    public static final String DATABASE_NAME = "OutLet_DB_SETUP.db";
    public static final String TABLE_NAME = "SETUP_OutIP";
    public static final String ID = "ID";
    public static final String IP = "IP";
    public static final String UName = "UName";
    public static final String PW = "PW";
    public static final String DBName = "DBName";
    public static final String OutletName = "OutletName";


    public static final String USER_ID = "UserID";
    public static final String USER_PW = "UserPW";




    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }



    @Override
    public void onCreate(SQLiteDatabase db) {
        String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY , " +
                " OutletName TEXT,IP TEXT,UName TEXT,PW TEXT,DBName TEXT)";
        db.execSQL(createTable);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME);
        onCreate(db);
    }



    public boolean addData(int _ID, String _IP, String _UName, String _PW, String _DBName, String _OutletName) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(ID, _ID);
        contentValues.put(OutletName, _OutletName);
        contentValues.put(IP, _IP);
        contentValues.put(UName, _UName);
        contentValues.put(PW, _PW);
        contentValues.put(DBName, _DBName);

        long result = db.insert(TABLE_NAME, null, contentValues);
        //if date as inserted incorrectly it will return -1
        if (result == -1) {
            db.execSQL("Update " + TABLE_NAME + " Set IP = '" + _IP + "' ,UName = '" + _UName + "', PW = '" + _PW + "',DBName = '" + _DBName + "',OutletName = '" + _OutletName + "' Where ID = " + _ID);
            return true;
        } else {
            return true;
        }

    }

    public Cursor getListContents(String _ID) {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME + _ID, null);
        return data;
    }
    public int DeleteContents(String _ID) {
        SQLiteDatabase db = this.getWritableDatabase();
       int r = db.delete(TABLE_NAME," ID = " + _ID,null);
       return  r;
    }

}

and this is my connection class

package abtech.waiteriano.com.waitrer.connection_class;


import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.util.Log;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class ConnectionClass {

    public static String ip;
    public static String classs;
    public static String db;
    public static String un;
    public static String password;
    public static String OutletName;
    public static String OutletID = "1";
    public static String Rest_ID = "1";
    public static String FL_ID = "0";

    public ConnectionClass() {
        classs = "net.sourceforge.jtds.jdbc.Driver";
//        db = "Feteera";
//        un = "sa";
//        password = "123";
//        ip = "192.168.1.210";
    }

    public ConnectionClass(String Ip, String Classs, String Db, String Un,
                           String Password) {
        ip = Ip;
        classs = Classs;
        db = Db;
        un = Un;
        password = Password;
    }

    public String getip() {
        return ip;

    }

    public String getclasss() {
        return classs;

    }

    public String getdb() {
        return db;
    }

    public String getun() {
        return un;
    }

    public String getpassword() {
        return password;
    }

    public void setip(String Ip) {
        ip = Ip;
    }

    public void setdb(String Db) {
        db = Db;
    }

    public void setclasss(String Classs) {
        classs = Classs;
    }

    public void setun(String Un) {
        un = Un;
    }

    public void setpassword(String Password) {
        password = Password;
    }

    @SuppressLint("NewApi")
    private static Connection CONN(String _user, String _pass, String _DB,
                                   String _server) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
        Connection conn = null;
        String ConnURL = null;
        try {

            Class.forName("net.sourceforge.jtds.jdbc.Driver");
            ConnURL = "jdbc:jtds:sqlserver://" + _server + ";"
                    + "databaseName=" + _DB + ";user=" + _user + ";password="
                    + _pass + ";";
            conn = DriverManager.getConnection(ConnURL);
        } catch (SQLException se) {
            Log.e("ERRO", se.getMessage());
        } catch (ClassNotFoundException e) {
            Log.e("ERRO", e.getMessage());
        } catch (Exception e) {
            Log.e("ERRO", e.getMessage());
        }
        return conn;
    }

    public static boolean checkConnection() {
        boolean flag = false;
        Connection connect;
        connect = CONN(un, password, db, ip);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
        Connection conn = null;
        String ConnURL = null;
        ConnURL = "jdbc:jtds:sqlserver://" + ConnectionClass.ip + ";"
                + "databaseName=" + ConnectionClass.db + ";user=" + ConnectionClass.un + ";password=" + ConnectionClass.password + ";";
        try {
            conn = DriverManager.getConnection(ConnURL);
            Statement statement = null;
            statement = conn.createStatement();
            flag = true;
        } catch (SQLException e) {
            flag = false;

        }


        return flag;
    }

    public static String Ret_Col(String Sql) {
        String Col = "";
        Connection connect;
        connect = CONN(un, password, db, ip);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
        Connection conn = null;
        String ConnURL = null;
        ConnURL = "jdbc:jtds:sqlserver://" + ConnectionClass.ip + ";"
                + "databaseName=" + ConnectionClass.db + ";user=" + ConnectionClass.un + ";password=" + ConnectionClass.password + ";";
        try {
            conn = DriverManager.getConnection(ConnURL);
            Statement statement = null;
            statement = conn.createStatement();
            ResultSet rs = statement.executeQuery(Sql);
            while (rs.next())
                Col = rs.getString(1);
        } catch (SQLException e) {

            Col = e.getMessage().toString();

        }


        return Col;
    }

    public static String SelectNewIDCheck() {
        String StrID = "";
        int ID = 0;
        Connection connect;
        connect = CONN(un, password, db, ip);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
        Connection conn = null;
        String ConnURL = null;
        ConnURL = "jdbc:jtds:sqlserver://" + ConnectionClass.ip + ";"
                + "databaseName=" + ConnectionClass.db + ";user=" + ConnectionClass.un + ";password=" + ConnectionClass.password + ";";
        try {
            conn = DriverManager.getConnection(ConnURL);
            Statement statement = null;
            statement = conn.createStatement();
            ResultSet rs = statement.executeQuery("Select  Max(Round(Substring(convert(nvarchar,ID),Len(ID)-5,6),0)) From Checks_V where OutLet_ID = 1 And Rest_ID_Active = 1");
            while (rs.next()) {
                String ser = String.valueOf(rs.getLong(1));
                if (ser.length() > 6)
                    ser = ser.substring(ser.length() - 6, 6);
                ID = Integer.parseInt(ser);
            }
            StrID = GetStrID(1, 2) + GetStrID(1, 3) + GetStrID(1, 2) + GetStrID(ID + 1, 6);

        } catch (SQLException e) {
            StrID = "0";

        }


        return StrID;
    }

    public static boolean executeUpdate(String str) {
        boolean flag = false;
        Connection connect;
        connect = CONN(un, password, db, ip);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
        Connection conn = null;
        String ConnURL = null;
        ConnURL = "jdbc:jtds:sqlserver://" + ConnectionClass.ip + ";"
                + "databaseName=" + ConnectionClass.db + ";user=" + ConnectionClass.un + ";password=" + ConnectionClass.password + ";";
        try {
            conn = DriverManager.getConnection(ConnURL);
            Statement statement = null;
            statement = conn.createStatement();
            if (statement.executeUpdate(str) > 0)
                flag = true;
        } catch (SQLException e) {
            flag = false;

        }


        return flag;
    }

    public static String GetStrID(int ID, int Digit) {
        String str = String.valueOf(ID);
        for (int i = String.valueOf(ID).length(); i < Digit; i++)
            str = "0" + str;
        return str;
    }

    public static String GetStrID(long ID, int Digit) {
        String str = String.valueOf(ID);
        if (str.length() > Digit)
            str = str.substring(str.length() - Digit, Digit);
        else
            for (int i = String.valueOf(ID).length(); i < Digit; i++)
                str = "0" + str;
        return str;
    }
    public static ResultSet Ret_RS(String Sql) {
        ResultSet rs ;
        Connection connect;
        connect = CONN(un, password, db, ip);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
        Connection conn = null;
        String ConnURL = null;
        ConnURL = "jdbc:jtds:sqlserver://" + ConnectionClass.ip + ";"
                + "databaseName=" + ConnectionClass.db + ";user=" + ConnectionClass.un + ";password=" + ConnectionClass.password + ";";
        try {
            conn = DriverManager.getConnection(ConnURL);
            Statement statement = null;
            statement = conn.createStatement();
             rs = statement.executeQuery(Sql);

        } catch (SQLException e) {

            rs = null;

        }


        return rs;
    }
}

if any could could tell me how can I use these process and where can I put this process sorry if any thing is un clear if any one need classes to under stand more just leave a comment this is simple fragment that I get data from data base

package abtech.waiteriano.com.waitrer.fragments;

import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.ProgressBar;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.SortedMap;
import java.util.TreeMap;

import abtech.waiteriano.com.waitrer.MenuActivity;
import abtech.waiteriano.com.waitrer.R;
import abtech.waiteriano.com.waitrer.adapters.CustomMenuLVAdapter;
import abtech.waiteriano.com.waitrer.connection_class.ConnectionClass;

public class LVMenuFragment extends android.app.Fragment {
    View rootView;
    ListView menuListView;
    public static ArrayList<String> listMenuArray = new ArrayList<String>();
    ArrayList<SortedMap> alphabets = new ArrayList<SortedMap>();

    public LVMenuFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        rootView = inflater.inflate(R.layout.fragment_lvmenu, container, false);
        progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar);
        menuListView = (ListView) rootView.findViewById(R.id.listView);
        listMenuArray.clear();
        alphabets.clear();
        String menuListSTR = "";
        if (MenuActivity.Prst_ID.trim() == "-1")
            menuListSTR = "Select ID,Code,Name,Name2 From Presets Where Active = 1 And Rest_ID_Active = 1 AND OutLet_ID_Active = 1 ORDER BY Code";
        else
            menuListSTR = "select dbo.MenuItems.Item_ID, dbo.Items.Code, dbo.Items.Name, dbo.Items.Name2, dbo.Items.PrintOnChick, dbo.Items.Taxable, dbo.Items.NoServiceCharge, dbo.Items.PrintOnReport,Case { fn IFNULL ((SELECT Price_Value FROM dbo.ItemsPrices WHERE (PriceLVL_ID = 1) AND (Item_ID = dbo.Items.ID)), 0) } when 0 then dbo.Items.StaticPrice Else { fn IFNULL ((SELECT Price_Value FROM dbo.ItemsPrices WHERE (PriceLVL_ID = 1) AND (Item_ID = dbo.Items.ID)), dbo.Items.StaticPrice) } END AS Price From dbo.MenuItems LEFT OUTER JOIN dbo.Items ON dbo.MenuItems.Item_ID = dbo.Items.ID Where  (dbo.MenuItems.Preset_ID = " + MenuActivity.Prst_ID + ") AND (dbo.MenuItems.Rest_ID_Active = " + ConnectionClass.Rest_ID + ") AND (dbo.MenuItems.OutLet_ID_Active = " + ConnectionClass.OutletID + ") AND (dbo.Items.Active = 1) ORDER BY dbo.MenuItems.SortNumber";

        ResultSet rs = ConnectionClass.Ret_RS(menuListSTR);
        try {
            while (rs.next()) {
                SortedMap<String, String> sm = new TreeMap<String, String>();
                sm.put("Item_ID", rs.getString("Item_ID"));
                sm.put("Name", rs.getString("Name"));
                sm.put("Price", rs.getString("Price"));
                sm.put("PrintOnChick", rs.getString("PrintOnChick"));
                sm.put("Taxable", rs.getString("Taxable"));
                sm.put("NoServiceCharge", rs.getString("NoServiceCharge"));
                sm.put("PrintOnReport", rs.getString("PrintOnReport"));
                if (TablesFragment.Check_Items.containsKey(rs.getString("Item_ID"))) {
                    SortedMap<String, String> sm1 = TablesFragment.Check_Items.get(rs.getString("Item_ID"));
                    sm.put("Qty", sm1.get("Qty"));
                } else
                    sm.put("Qty", "0");
                alphabets.add(sm);
                listMenuArray.add(rs.getString("Name"));

            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        menuListView.setAdapter(new CustomMenuLVAdapter(this, listMenuArray, alphabets));
        new MyAsyncTask().execute();
        return rootView;
    }
    ProgressBar progressBar;
    // The types specified here are the input data type, the progress type, and the result type
    private class MyAsyncTask extends AsyncTask<String, Void, String> {
        protected void onPreExecute() {
            // Runs on the UI thread before doInBackground
            // Good for toggling visibility of a progress indicator
            progressBar.setVisibility(ProgressBar.VISIBLE);
        }

        protected String doInBackground(String... strings) {
            String someBitmap ="";
            String menuListSTR = "";
            if (MenuActivity.Prst_ID.trim() == "-1")
                menuListSTR = "Select ID,Code,Name,Name2 From Presets Where Active = 1 And Rest_ID_Active = 1 AND OutLet_ID_Active = 1 ORDER BY Code";
            else
                menuListSTR = "select dbo.MenuItems.Item_ID, dbo.Items.Code, dbo.Items.Name, dbo.Items.Name2, dbo.Items.PrintOnChick, dbo.Items.Taxable, dbo.Items.NoServiceCharge, dbo.Items.PrintOnReport,Case { fn IFNULL ((SELECT Price_Value FROM dbo.ItemsPrices WHERE (PriceLVL_ID = 1) AND (Item_ID = dbo.Items.ID)), 0) } when 0 then dbo.Items.StaticPrice Else { fn IFNULL ((SELECT Price_Value FROM dbo.ItemsPrices WHERE (PriceLVL_ID = 1) AND (Item_ID = dbo.Items.ID)), dbo.Items.StaticPrice) } END AS Price From dbo.MenuItems LEFT OUTER JOIN dbo.Items ON dbo.MenuItems.Item_ID = dbo.Items.ID Where  (dbo.MenuItems.Preset_ID = " + MenuActivity.Prst_ID + ") AND (dbo.MenuItems.Rest_ID_Active = " + ConnectionClass.Rest_ID + ") AND (dbo.MenuItems.OutLet_ID_Active = " + ConnectionClass.OutletID + ") AND (dbo.Items.Active = 1) ORDER BY dbo.MenuItems.SortNumber";

            ResultSet rs = ConnectionClass.Ret_RS(menuListSTR);
            try {
                while (rs.next()) {
                    SortedMap<String, String> sm = new TreeMap<String, String>();
                    sm.put("Item_ID", rs.getString("Item_ID"));
                    sm.put("Name", rs.getString("Name"));
                    sm.put("Price", rs.getString("Price"));
                    sm.put("PrintOnChick", rs.getString("PrintOnChick"));
                    sm.put("Taxable", rs.getString("Taxable"));
                    sm.put("NoServiceCharge", rs.getString("NoServiceCharge"));
                    sm.put("PrintOnReport", rs.getString("PrintOnReport"));
                    if (TablesFragment.Check_Items.containsKey(rs.getString("Item_ID"))) {
                        SortedMap<String, String> sm1 = TablesFragment.Check_Items.get(rs.getString("Item_ID"));
                        sm.put("Qty", sm1.get("Qty"));
                    } else
                        sm.put("Qty", "0");
                    alphabets.add(sm);
                    listMenuArray.add(rs.getString("Name"));

                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            return someBitmap;
        }

//        protected void onProgressUpdate(Progress... values) {
//            // Executes whenever publishProgress is called from doInBackground
//            // Used to update the progress indicator
//            progressBar.setProgress(values[0]);
//        }

        protected void onPostExecute(Bitmap result) {
            // This method is executed in the UIThread
            // with access to the result of the long running task
            menuListView.setAdapter(new CustomMenuLVAdapter(LVMenuFragment.this, listMenuArray, alphabets));
            // Hide the progress bar
            progressBar.setVisibility(ProgressBar.INVISIBLE);
        }
    }

}

Error enter image description here

Upvotes: 0

Views: 1231

Answers (2)

humazed
humazed

Reputation: 76942

in the activity or the fragment, you load the data you can create Asynctask. regarding the progressBar start showing it in onPreExecute method the Asynctask and stop it in onPostExecute method.

// The types specified here are the input data type, the progress type, and the result type
private class MyAsyncTask extends AsyncTask<String, Void, String> {
     protected void onPreExecute() {
         // Runs on the UI thread before doInBackground
         // Good for toggling visibility of a progress indicator
         progressBar.setVisibility(ProgressBar.VISIBLE);
     }

     protected Bitmap doInBackground(String... strings) {
          String menuListSTR = "";
    if (MenuActivity.Prst_ID.trim() == "-1") 
        menuListSTR = "Select ID,Code,Name,Name2 From Presets Where Active = 1 And Rest_ID_Active = 1 AND OutLet_ID_Active = 1 ORDER BY Code";
    else 
        menuListSTR = "select dbo.MenuItems.Item_ID, dbo.Items.Code, dbo.Items.Name, dbo.Items.Name2, dbo.Items.PrintOnChick, dbo.Items.Taxable, dbo.Items.NoServiceCharge, dbo.Items.PrintOnReport,Case { fn IFNULL ((SELECT Price_Value FROM dbo.ItemsPrices WHERE (PriceLVL_ID = 1) AND (Item_ID = dbo.Items.ID)), 0) } when 0 then dbo.Items.StaticPrice Else { fn IFNULL ((SELECT Price_Value FROM dbo.ItemsPrices WHERE (PriceLVL_ID = 1) AND (Item_ID = dbo.Items.ID)), dbo.Items.StaticPrice) } END AS Price From dbo.MenuItems LEFT OUTER JOIN dbo.Items ON dbo.MenuItems.Item_ID = dbo.Items.ID Where  (dbo.MenuItems.Preset_ID = " + MenuActivity.Prst_ID + ") AND (dbo.MenuItems.Rest_ID_Active = " + ConnectionClass.Rest_ID + ") AND (dbo.MenuItems.OutLet_ID_Active = " + ConnectionClass.OutletID + ") AND (dbo.Items.Active = 1) ORDER BY dbo.MenuItems.SortNumber";

    ResultSet rs = ConnectionClass.Ret_RS(menuListSTR);
    try { 
        while (rs.next()) {
            SortedMap<String, String> sm = new TreeMap<String, String>();
            sm.put("Item_ID", rs.getString("Item_ID"));
            sm.put("Name", rs.getString("Name"));
            sm.put("Price", rs.getString("Price"));
            sm.put("PrintOnChick", rs.getString("PrintOnChick"));
            sm.put("Taxable", rs.getString("Taxable"));
            sm.put("NoServiceCharge", rs.getString("NoServiceCharge"));
            sm.put("PrintOnReport", rs.getString("PrintOnReport"));
            if (TablesFragment.Check_Items.containsKey(rs.getString("Item_ID"))) {
                SortedMap<String, String> sm1 = TablesFragment.Check_Items.get(rs.getString("Item_ID"));
                sm.put("Qty", sm1.get("Qty"));
            } else 
                sm.put("Qty", "0");
            alphabets.add(sm);
            listMenuArray.add(rs.getString("Name"));

        } 
    } catch (SQLException e) {
        e.printStackTrace();
    }  
         return someBitmap;
     }

     protected void onProgressUpdate(Progress... values) {
        // Executes whenever publishProgress is called from doInBackground
        // Used to update the progress indicator
        progressBar.setProgress(values[0]);
     }  

     protected void onPostExecute(Bitmap result) {
         // This method is executed in the UIThread
         // with access to the result of the long running task
           menuListView.setAdapter(new CustomMenuLVAdapter(this, listMenuArray, alphabets));
         // Hide the progress bar
         progressBar.setVisibility(ProgressBar.INVISIBLE);
     }
}

now in onCreateView call new MyAsyncTask().execute();

let me know if you need more clarification.

for more information take a look: https://guides.codepath.com/android/Creating-and-Executing-Async-Tasks#understanding-the-asynctask

Upvotes: 1

user7462841
user7462841

Reputation:

Set a progress bar in the fuction where your Async task starts like this:

// Create a progressdialog
            mProgressDialog = new ProgressDialog(ActivityName.this);

            // Set progressdialog title
            mProgressDialog.setTitle("Please wait...");

            // Set progressdialog message
            mProgressDialog.setMessage("Loading ....");
            mProgressDialog.setIndeterminate(false);

            // Show progressdialog
            mProgressDialog.show();

            // disable touch while loading
            mProgressDialog.setCanceledOnTouchOutside(false);

And dismiss your progress bar bar where your Async task ends like this:

// Close the progressdialog
            mProgressDialog.dismiss();

Hope this will resolve your issue.

Upvotes: 0

Related Questions