Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在从数据库获取数据的同时创建异步任务加载后台_Java_Android - Fatal编程技术网

Java 如何在从数据库获取数据的同时创建异步任务加载后台

Java 如何在从数据库获取数据的同时创建异步任务加载后台,java,android,Java,Android,我刚刚创建了一个简单的项目,通过使用Selects forms从sql server数据库获取数据,因为从数据库获取数据时会加载并花费一些时间。我需要的是,在从数据库获取数据时,以异步任务的形式创建一个加载栏或图标,因为它在获取数据后会显示此加载栏。它会删除加载栏 这是我的数据库助手类 package abtech.waiteriano.com.waitrer.data_base_helper; import android.content.ContentValues; import andr

我刚刚创建了一个简单的项目,通过使用Selects forms从sql server数据库获取数据,因为从数据库获取数据时会加载并花费一些时间。我需要的是,在从数据库获取数据时,以异步任务的形式创建一个加载栏或图标,因为它在获取数据后会显示此加载栏。它会删除加载栏 这是我的数据库助手类

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;
    }

}
这是我的连接课程

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;
    }
}
如果有人能告诉我如何使用这些过程,我可以把这个过程放在哪里对不起,如果有什么事情不清楚,如果有人需要了解更多,请留下评论 这是我从数据库中获取数据的简单片段

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);
        }
    }

}
错误

在活动或片段中,加载可以创建的数据。 关于progressBar,请在onPreExecute方法中显示Asynctask,并在onPostExecute方法中停止它

现在在onCreateView中调用新的MyAsyncTask.execute

如果你需要更多的澄清,请告诉我


有关更多信息,请查看:

在异步任务开始的功能中设置进度条,如下所示:

// 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);
// Close the progressdialog
            mProgressDialog.dismiss();
并关闭异步任务结束时的进度条,如下所示:

// 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);
// Close the progressdialog
            mProgressDialog.dismiss();

希望这能解决您的问题。

非常感谢。我是要对我创建的每个活动和片段执行此操作还是只执行一次?啊哈,我可以向您发布一个片段吗?我如何使用它@humazed?请检查我发布一个简单的片段好,继续;但是请记住您需要从OnCreateView调用Asynctask的片段是的,我刚刚发布了我的片段,很高兴能帮助我:D