2015-09-20 2 views
1

У меня есть некоторые OptionItems с AsyncTask (с диалогом процесса) под названием, как показанAsyncTask называется в OptionItemSelected называется в неподходящем Пункте

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 

    super.onOptionsItemSelected(item); 
    if (mDrawerToggle.onOptionsItemSelected(item)) { 
     return true; 
    } 

    switch (item.getItemId()) { 

     case R.id.FilterSpeed: 
      GetSpeed(); 
      break; 
     case R.id.FilterEvent: 
      GetEvents(); 
      break; 
     case R.id.FilterDevice: 
      GetDevices(); 
      break; 
     case R.id.ClearFilter: 
      ClearFilter(); 
      break; 
    } 
    new GetAllUserDevices(Dashboard.this, Dashboard.this).execute(API_ServiceDev_method_url); 
    return true; 

} 

я получить доступ к данным AsyncTask в третьем пункте клике (GetDevices), но я получаю диалог прогресса при нажатии на второй элемент (GetEvents), хотя этот элемент не имеет ничего общего с AsyncTask.

Как я могу сделать диалоговое окно выполнения правильным выбором предмета?

Добавлено: GetDevices

public void GetDevices() { 
    DevicesNames = GetAllUserDevices.DevicesNames; 
    DevicesIds = GetAllUserDevices.DevicesIds; 
    SelectedDevicesIds = new HashSet<>(); 
    SelectedDevices = new ArrayList<>(); 
    isCheckedDeviceList = new boolean[DevicesIds.size()]; 
    if (oldChecked.size() > 0) { 
     for (int i = 0; i < DevicesIds.size(); i++) { 
      isCheckedDeviceList[i] = Dashboard.oldChecked.get(i); 
     } 
    } else { 
     for (int i = 0; i < DevicesIds.size(); i++) { 
      oldChecked.add(i, Dashboard.isCheckedDeviceList[i]); 
     } 
    } 
    CharSequence[] DevicesNamesInChar = DevicesNames.toArray(new CharSequence[DevicesNames.size()]); 
    builder = new AlertDialog.Builder(Dashboard.this); 
    builder.setTitle(getString(R.string.Devicename)) 
      .setMultiChoiceItems(DevicesNamesInChar, Dashboard.isCheckedDeviceList.length == DevicesIds.size() ? Dashboard.isCheckedDeviceList : null, new DialogInterface.OnMultiChoiceClickListener() { 
       @Override 
       public void onClick(DialogInterface dialog, int which, boolean isChecked) { 
        Dashboard.isCheckedDeviceList[which] = isChecked; 
        if (isChecked) { 
         Dashboard.SelectedDevices.add(which); 
        } else if (Dashboard.SelectedDevices.contains(which)) { 
         Dashboard.SelectedDevices.remove(Integer.valueOf(which)); 
        } 

       } 
      }) 
      .setPositiveButton(R.string.okay, new DialogInterface.OnClickListener() { 
       @Override 
       public void onClick(DialogInterface dialog, int id) { 


        for (int i = 0; i < Dashboard.isCheckedDeviceList.length; i++) { 
         boolean checked = Dashboard.isCheckedDeviceList[i]; 
         Dashboard.oldChecked.set(i, checked); 

         if (checked) { 
          Dashboard.SelectedDevicesIds.add(String.valueOf(DevicesIds.get(i))); 
         } 
        } 

        Dashboard.UserEditor.putStringSet("DevicesIds", Dashboard.SelectedDevicesIds); 
        Dashboard.UserEditor.commit(); 
        StopTimerTask(); 
        StartTimer(); 
       } 
      }) 

      .setCancelable(true).show(); 


} 

в отдельном GetAllDevices класса (AsyncTask):

public class GetAllUserDevices extends AsyncTask<String, Void, String> { 

//vars declaration 
static SharedPreferences UserInfo; 
static Context context; 
static String UserToken; 
static Activity activityTest; 
InputToString converter; 
public static Loading LoadingDialog; 
static boolean IsArabic; 
public static BufferedReader in; 
static String inputLine; 
static StringBuffer response; 
public static Text_Value_Pair[] devicesList; 
public static ArrayList<String> DevicesNames = new ArrayList<>(); 
public static ArrayList<Integer> DevicesIds = new ArrayList<>(); 
MoveTo moving; 

public GetAllUserDevices(Context currentcontext, Activity currentActivity) { 
    context = currentcontext; 
    UserInfo = context.getSharedPreferences("Login_UserInfo", Context.MODE_PRIVATE); 
    converter = new InputToString(); 
    activityTest = currentActivity; 
    LoadingDialog = new Loading(currentcontext); 
    moving = new MoveTo(context); 


} 

@Override 
protected String doInBackground(String... urls) { 
    return POSTJson(urls[0]); 
} 

protected void onPreExecute() { 
    super.onPreExecute(); 

} 

@Override 
protected void onPostExecute(String result) { 
} 

public String POSTJson(String url) { 
    //User Static Params 
    UserToken = UserInfo.getString("Token", "NoToken"); 
    IsArabic = (new IsArabic(context).IsLangArabic()); 
    String result = ""; 
    URL obj; 
    try { 
     obj = new URL(url); 
     HttpURLConnection con = (HttpURLConnection) obj.openConnection(); 
     con.setRequestMethod("POST"); 
     con.setRequestProperty("Accept", "application/json"); 
     con.setRequestProperty("Content-type", "application/json"); 
     con.setRequestProperty("Token", UserToken); 
     // Send post request 
     con.setDoOutput(true); 
     in = new BufferedReader(new InputStreamReader(con.getInputStream())); 
     response = new StringBuffer(); 

     while ((inputLine = in.readLine()) != null) { 
      response.append(inputLine); 
     } 
     in.close(); 
     result = response.toString(); 
    } catch (IOException e) { 
     moving.LogOffNow(); 
     e.printStackTrace(); 
    } 

    if (!result.endsWith("An error has occurred.\"}")) { 
     Gson gson = new Gson(); 
     devicesList = gson.fromJson(result, Text_Value_Pair[].class); 
    } else { 
     devicesList = null; 
    } 

    if (devicesList != null) { 
     DevicesNames.clear(); 
     DevicesIds.clear(); 
     int i = 0; 
     while (i < devicesList.length) { 
      DevicesNames.add(devicesList[i].getText()); 
      DevicesIds.add(devicesList[i].getValue()); 
      i++; 
     } 

    } 

    return "Data Updated"; 

} 

}

ответ

0

Я думаю, диалог прогресса появляется из-за GetAllUserDevices() AsyncTask выполняется после того, как переключатель чехол закончился.

Проверьте, не ли вы хотите выполнить GetAllUserDevices() во всех случаях? , если нет, то он должен быть вызван в конкретном корпусе коммутатора.

+0

Я попытался вызвать его в конкретном случае коммутатора, но диалог прогресса появился дважды, один раз щелкнув по кнопке меню и один раз, когда выбранный элемент щелкнул, что так раздражает, чтобы иметь промежуточный диалог прогресса 0,5 сек. –

+0

Выполняете ли вы AsyncTask следующими способами: 1) GetSpeed ​​(); 2) GetEvents(); 3) GetDevices(); 4) ClearFilter(); ?? –

+0

нет, только в GetDevices –

Смежные вопросы