Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/234.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 从单独文件中的AsyncTask显示和更新对话框_Java_Android_Android Asynctask - Fatal编程技术网

Java 从单独文件中的AsyncTask显示和更新对话框

Java 从单独文件中的AsyncTask显示和更新对话框,java,android,android-asynctask,Java,Android,Android Asynctask,我有一个带按钮的活动。单击时,其中一个按钮从另一个类调用静态方法。然后,此方法调用一系列菊花链异步任务。就像在第一个任务的OnPostExecute中,我将调用一个新的AsyncTask,然后在第二个AsyncTask的OnPostExecute中,我将再次调用一个新的AsyncTask。这将持续大约15个级别。我需要在这些任务运行时显示进度对话框,并显示相应的状态(百分比)。为此,我在第一个异步任务的OnPreExecute上创建了一个新的ProgressDialog。我的问题是,当设备旋转或

我有一个带按钮的活动。单击时,其中一个按钮从另一个类调用静态方法。然后,此方法调用一系列菊花链异步任务。就像在第一个任务的OnPostExecute中,我将调用一个新的AsyncTask,然后在第二个AsyncTask的OnPostExecute中,我将再次调用一个新的AsyncTask。这将持续大约15个级别。我需要在这些任务运行时显示进度对话框,并显示相应的状态(百分比)。为此,我在第一个异步任务的OnPreExecute上创建了一个新的ProgressDialog。我的问题是,当设备旋转或进入睡眠状态时,ProgressDialog会消失,当我从最后一个OnPostExecute调用Disclease()时会引发异常

以下是我的代码(将异步任务的级别降低到2级)

活动:

private class OnButtonMenuClick implements OnClickListener {
    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
        case R.id.textViewDownload:
            downloadReferenceFiles();
            break;

        case R.id.textViewProductNotes:
            showProductNotes();
            break;

        case R.id.textViewCustomerNotes:
            showCustomerNotes();
            break;

        case R.id.textViewAdjustOrders:
            orderAdjustments();
            break;

        case R.id.textViewUploadOrders:
            uploadDataToServer();
            break;

        case R.id.textViewToolsReconciliationIcon:
            cashCount();
            break;

        case R.id.textViewToolsExpensesIcon:
            expensesEntry();
            break;

        case R.id.textViewSalesSummaryIcon:
            showSalesSummary();
            break;              

        case R.id.textViewInventoryIcon:
            showInventory();
            break;

        case R.id.textViewInventoryByVolumeIcon:
            showInventoryByVolume();
            break;
        }
    }
}

public void downloadReferenceFiles() {      
    ReferenceFilesDownloader.downloadData(ToolsActivity.this, true);
}
参考文件下载器类(单独文件)

import java.util.ArrayList;
导入org.json.JSONObject;
导入android.app.ProgressDialog;
导入android.content.Context;
导入android.os.AsyncTask;
导入android.util.Log;
公共类引用FilesDownLoader{
私有静态进程对话框进程;
私有静态语境;
私有静态布尔includeInventory;
公共静态void下载数据(上下文ctx){
上下文=ctx;
includeInventory=false;
新建AsyncCheckServerDate().execute();
}
公共静态void setContext(Context ctx){
上下文=ctx;
}
公共静态void下载数据(上下文ctx、布尔资源清册){
上下文=ctx;
includeInventory=存货;
新建AsyncCheckServerDate().execute();
}
公共静态字符串buildProgress(int值,int max){
整数百分比=(整数)((双倍)值/(双倍)最大值)*100);
字符串电流=“+max+”中的值+”(“+percent+%completed)”;
回流;
}
公共静态void createProgress(){
如果(进度==null){
进度=新建进度对话框(上下文);
进度。设置不确定(false);
进度。可设置可取消(false);
progress.setCanceledOnTouchOutside(false);
progress.setProgressStyle(ProgressDialog.STYLE_水平);
}
如果(!progress.isShowing()){
progress.show();
}
}
受保护的静态类AsyncCheckServerDate扩展了AsyncTask{
@凌驾
受保护字符串doInBackground(无效…参数){
今天字符串=”;
RestAPI api=new RestAPI();
试试{
JSONObject jsonObj=api.GetDateToday();
JSONParser=新的JSONParser();
今天=parser.parseDateToday(jsonObj);
}
捕获(NullPointerException e){
}
捕获(例外e){
}
今天回来;
}
@凌驾
受保护的void onPreExecute(){
//进度。显示(经理,标签)
/*进度=新建进度对话框(上下文);
progress.setMessage(“正在验证服务器日期。请稍候…”);
进度。可设置可取消(false);
progress.setCanceledOnTouchOutside(false);
progress.show()*/
}
@凌驾
受保护的void onPostExecute(字符串结果){
if(result.equals(StaticHolder.today())){
新客户().execute();
}
否则{
AppMessages.showMessage(上下文,
“此设备上的日期未与服务器同步。请将其调整为正确的日期。”,
“日期不同步”,
AppMessages.messages\u信息,
无效);
}
}
}
受保护的静态类AsyncTask{
@凌驾
受保护的Void doInBackground(Void…参数){
ArrayList客户=null;
RestAPI api=new RestAPI();
试试{
JSONObject jsonObj=api.GetReferenceFiles((字节)4);
JSONParser=新的JSONParser();
customers=parser.parseCustomer(jsonObj);
CustomersTable.importData(上下文、客户、此);
}
捕获(NullPointerException e){
}
捕获(例外e){
}
返回null;
}
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
createProgress();
progress.setTitle(“下载客户信息”);
}
@凌驾
受保护的void onPostExecute(void结果){
新建AsyncItems().execute();
}
@凌驾
受保护的void onProgressUpdate(字符串…值){
super.onProgressUpdate(值);
progress.setMessage(值[0]);
}
public void showProgress(int值,int max){
发布进度(构建进度(值,最大值));
}
}
受保护的静态类AsyncItems扩展了AsyncTask{
@凌驾
受保护的Void doInBackground(Void…参数){
arraylistitems=null;
RestAPI api=new RestAPI();
试试{
JSONObject jsonObj=api.GetReferenceFiles((字节)6);
JSONParser=新的JSONParser();
items=parser.parseItem(jsonObj);
importData(上下文、项、此);
}
捕获(NullPointerException e){
}
捕获(例外e){
}
返回null;
}
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
createProgress();
progress.setTitle(“下载项目主文件”);
}
@凌驾
受保护的void onPostExecute(void结果){
如果(进度!=null){
dismis();
}
}
@凌驾
受保护的void onProgressUpdate(字符串…值){
super.onProgressUpdate(值);
progress.setMessage(值[0]);
}
public void showProgress(int值
import java.util.ArrayList;

import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

public class ReferenceFilesDownloader {

private static ProgressDialog progress;
private static Context context;
private static boolean includeInventory;

public static void downloadData(Context ctx) {      
    context = ctx;
    includeInventory = false;   
    new AsyncCheckServerDate().execute();       
}

public static void setContext(Context ctx) {
    context = ctx;
}

public static void downloadData(Context ctx, boolean inventory) {
    context = ctx;
    includeInventory = inventory;
    new AsyncCheckServerDate().execute();       
}

public static String buildProgress(int value, int max) {
    int percent = (int)(((double)value / (double)max) * 100);
    String current = value + " of " + max + " (" + percent + "% completed)";                    
    return current;
}

public static void createProgress() {
    if (progress == null) {
        progress = new ProgressDialog(context);
        progress.setIndeterminate(false);
        progress.setCancelable(false);
        progress.setCanceledOnTouchOutside(false);
        progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    }

    if (!progress.isShowing()) {
        progress.show();
    }
}

protected static class AsyncCheckServerDate extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... params) {
        String today = "";
        RestAPI api = new RestAPI();
        try {               
            JSONObject jsonObj = api.GetDateToday();
            JSONParser parser = new JSONParser();
            today = parser.parseDateToday(jsonObj);
        }
        catch (NullPointerException e) {
        }
        catch (Exception e) {
        }
        return today;
    }

    @Override
    protected void onPreExecute() {
        //progress.show(manager, tag)
        /*progress = new ProgressDialog(context);
        progress.setMessage("Verifying server date. Please wait...");
        progress.setCancelable(false);
        progress.setCanceledOnTouchOutside(false);
        progress.show();*/

    }

    @Override
    protected void onPostExecute(String result) {
        if (result.equals(StaticHolder.today())) {
            new AsyncCustomers().execute();             
        }
        else {
            AppMessages.showMessage(context,
                                    "The date on this device is not synchronized with the server. Please adjust it to the correct date.",
                                    "Date Out of Sync", 
                                    AppMessages.MESSAGE_INFO,
                                    null);          
        }
    }
}

protected static class AsyncCustomers extends AsyncTask<Void, String, Void> {

    @Override
    protected Void doInBackground(Void... params) {
        ArrayList<Customer> customers = null;
        RestAPI api = new RestAPI();
        try {               
            JSONObject jsonObj = api.GetReferenceFiles((byte)4);
            JSONParser parser = new JSONParser();
            customers = parser.parseCustomer(jsonObj);
            CustomersTable.importData(context, customers, this);
        }
        catch (NullPointerException e) {
        }
        catch (Exception e) {
        }
        return null;
    }

    @Override
    protected void onPreExecute() {         
        super.onPreExecute();
        createProgress();
        progress.setTitle("Downloading Customer Information");
    }

    @Override
    protected void onPostExecute(Void result) {
        new AsyncItems().execute();
    }

    @Override
    protected void onProgressUpdate(String... values) {     
        super.onProgressUpdate(values);
        progress.setMessage(values[0]);
    }

    public void showProgress(int value, int max) {          
        publishProgress(buildProgress(value, max));
    }

}

protected static class AsyncItems extends AsyncTask<Void, String, Void> {

    @Override
    protected Void doInBackground(Void... params) {
        ArrayList<Item> items = null;
        RestAPI api = new RestAPI();
        try {               
            JSONObject jsonObj = api.GetReferenceFiles((byte)6);
            JSONParser parser = new JSONParser();
            items = parser.parseItem(jsonObj);
            ItemsTable.importData(context, items, this);                
        }
        catch (NullPointerException e) {
        }
        catch (Exception e) {
        }
        return null;
    }

    @Override
    protected void onPreExecute() {         
        super.onPreExecute();
        createProgress();
        progress.setTitle("Downloading Items Master File");         
    }

    @Override
    protected void onPostExecute(Void result) {
        if (progress != null) {
           progress.dismis();
        }
    }

    @Override
    protected void onProgressUpdate(String... values) {     
        super.onProgressUpdate(values);
        progress.setMessage(values[0]);
    }

    public void showProgress(int value, int max) {
        publishProgress(buildProgress(value, max));
    }

}

}
import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;

public class CustomersTable {

public static void importData(Context context, ArrayList<Customer> customers, ReferenceFilesDownloader.AsyncCustomers async) {
        ADIDBContext dbContext = new ADIDBContext(context);     
        String query = "DELETE FROM Customers";
        dbContext.execSQL(query);   
        try {
            dbContext.beginTransaction();
        int row = 0;
        for (Customer customer : customers) {
            ContentValues values = new ContentValues();

            async.showProgress(++row, customers.size());

            values.put("CustomerId", customer.customerId);
            values.put("LastName", customer.lastName);
            values.put("FirstName", customer.firstName);

            values.put("MiddleName", customer.middleName);
            values.put("Address1", customer.address1);
            values.put("Address2", customer.address2);              

            values.put("ProvinceId", customer.provinceId);
            values.put("CityId", customer.cityId);
            values.put("BarangayId", customer.barangayId);

            dbContext.getDatabase().insert("Customers", null, values);
        }

        dbContext.setTransactionSuccessful();                       
    }
    catch (Exception ex) {          
    }       
    dbContext.endTransaction();
    dbContext.close();              
}

}
import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;

public class ItemsTable {
    public static void importData(Context context, ArrayList<Item> items, ReferenceFilesDownloader.AsyncItems async) {
    ADIDBContext dbContext = new ADIDBContext(context);
    String query = "DELETE FROM Items";
    dbContext.execSQL(query);

    try {
        dbContext.beginTransaction();

        int row = 0;
        for (Item item : items) {
            ContentValues values = new ContentValues();

            async.showProgress(++row, items.size());

            values.put("Barcode", item.barcode);
            values.put("ItemId", item.itemId);
            values.put("ItemDesc", item.itemDesc);
            values.put("UnitId", item.unitId);

            values.put("CompanyId", item.companyId);
            values.put("UnitDescription", item.unitDescription);
            values.put("UnitConversion", item.unitConversion);

            values.put("Cost", item.cost);

            values.put("SellingPrice1", item.sellingPrice1);
            values.put("SellingPrice2", item.sellingPrice2);
            values.put("SellingPrice3", item.sellingPrice3);
            values.put("SellingPrice4", item.sellingPrice4);
            values.put("SellingPrice5", item.sellingPrice5);

            values.put("PiecePrice1", item.piecePrice1);
            values.put("PiecePrice2", item.piecePrice2);
            values.put("PiecePrice3", item.piecePrice3);
            values.put("PiecePrice4", item.piecePrice4);
            values.put("PiecePrice5", item.piecePrice5);

            values.put("Taxable", item.taxable);

            dbContext.getDatabase().insert("Items", null, values);
        }

        dbContext.setTransactionSuccessful();                       
    }
    catch (Exception ex) {          
    }       
    dbContext.endTransaction();
    dbContext.close();              
}
}
android:configChanges="keyboardHidden|orientation"
<activity
   android:screenOrientation="portrait"
   ...  />
@Override
public void onTaskStarted() {
    lockScreenOrientation();
    progressDialog = ProgressDialog.show(CopyOfCopyOfMainActivity.this, "Loading", "Please wait a moment!");
}

@Override
public void onTaskFinished(String result) {
    if (progressDialog != null) {
        progressDialog.dismiss();
    }
    unlockScreenOrientation();
}

private void lockScreenOrientation() {
    int currentOrientation = getResources().getConfiguration().orientation;
    if (currentOrientation == Configuration.ORIENTATION_PORTRAIT) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    } else {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }
}

private void unlockScreenOrientation() {
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
}