2016-07-04 3 views
0

Я хочу показать alertdialog и получить некоторый ввод от пользователя, а после этого обработать входные данные в asynctask, но alertdialog будет отклонен, прежде чем получить входные данные и запустить асинтекс.Как показать alertdialog перед запуском asynctask

Что мне делать? Пожалуйста, помогите мне. Вот мой код;

private String[] newspapers,newspapersUrl,newspapersPath; 
private String[] choosed,choosedUrl,choosedPath; 
private boolean[] checked; 

private int perNewspaper; 
private boolean returned = false; 

private AlertDialog.Builder builder; 


private FetchingNewsByChoice fetchingNewsByChoice; 

@Override 
protected void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 

    returned = AlertDialogCreation(); 

    if(returned) 
    { 
     fetchingNewsByChoice = new FetchingNewsByChoice((AppCompatActivity)MainActivity.this,choosed,choosedPath,perNewspaper); 
     fetchingNewsByChoice.execute(); 
    } 


    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
    fab.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) 
        .setAction("Action", null).show(); 
     } 
    }); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.menu_main, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 

    //noinspection SimplifiableIfStatement 
    if (id == R.id.action_settings) { 
     return true; 
    } 

    return super.onOptionsItemSelected(item); 
} 

//***** Alert Dialog *****// 
public boolean AlertDialogCreation() 
{ 
    //***** File Control And Creating An Dialog Interface if this is first usage *****// 
    File file = getApplicationContext().getFileStreamPath("First.txt"); 

    if(!file.exists()) 
    { 
     writeToFile("First.txt", "0",true); 
    } 

    if(readFromFile("First.txt",false)[0].equals("0")) 
    { 
     newspapers = readFromFile("Choicable Newspaper.txt",true); 
     newspapersUrl = readFromFile("Choicable Url.txt",true); 
     newspapersPath = readFromFile("Choicable Path.txt",true); 

     checked = new boolean[newspapers.length]; 

     builder = new AlertDialog.Builder(this,R.style.AppCompatAlertDialogStyle); 

     builder.setTitle("Lütfen Güncel Haberlerini Takip Etmek İstediğiniz Siteleri Seçiniz.."); 
     builder.setItems(newspapers, null); 

     builder.setPositiveButton("Tamam", new DialogInterface.OnClickListener() { 
      @Override 
      public void onClick(DialogInterface dialogInterface, int i) { 
       int count = 0; 

       for (int a = 0; a < newspapers.length; a++) { 
        if (checked[a]) { 
         count++; 
         writeToFile("Choosed.txt", newspapers[a], false); 
         writeToFile("ChoosedUrl.txt", newspapersUrl[a], false); 
         writeToFile("ChoosedPath.txt", newspapersPath[a], false); 
        } 

        if (a == (newspapers.length - 1) && count == 0) { 
         Toast.makeText(getApplicationContext(), "En az bir gazete seçmek zorundasınız..", Toast.LENGTH_LONG).show(); 
         builder.show(); 
        } 
       } 
      } 
     }); 

     builder.setMultiChoiceItems(newspapers, checked, new DialogInterface.OnMultiChoiceClickListener() { 
      @Override 
      public void onClick(DialogInterface dialogInterface, int i, boolean isChecked) { 

       if (isChecked) { 
        checked[i] = true; 
       } else { 
        checked[i] = false; 
       } 
      } 
     }); 

     try 
     { 
      builder.show(); 
     } 
     catch (Exception ex) 
     { 
      ex.printStackTrace(); 
     } 


     writeToFile("First.txt", "1", true); 

     choosed = readFromFile("Choosed.txt",false); 
     choosedUrl = readFromFile("ChoosedUrl.txt",false); 
     choosedPath = readFromFile("ChoosedPath.txt",false); 

     if(choosed != null) 
     { 
      perNewspaper = (int) Math.ceil(newspapers.length/choosed.length); 

      if(perNewspaper > 15) 
      { 
       perNewspaper = 14; 
      } 
     } 

     return true; 
    } 
    else if(readFromFile("First.txt",false)[0].equals("1")) 
    { 
     newspapers = readFromFile("Choicable Newspaper.txt",true); 
     newspapersUrl = readFromFile("Choicable Url.txt",true); 
     newspapersPath = readFromFile("Choicable Path.txt",true); 

     choosed = readFromFile("Choosed.txt",false); 
     choosedUrl = readFromFile("ChoosedUrl.txt",false); 
     choosedPath = readFromFile("ChoosedPath.txt",false); 

     perNewspaper = (int) Math.ceil(newspapers.length/choosed.length); 

     if(perNewspaper > 15) 
     { 
      perNewspaper = 14; 
     } 

     return true; 
    } 
    else 
    { 
     return false; 
    } 
    //***** File Control And Creating An Dialog Interface if this is first usage *****// 
} 

//*****Files*****// 
private void writeToFile(String fileName,String data,boolean isPrivate) 
{ 
    try 
    { 
     OutputStreamWriter outputStreamWriter; 

     if(isPrivate) 
     { 
      outputStreamWriter = new OutputStreamWriter(getApplicationContext().openFileOutput(fileName, MODE_PRIVATE)); 
     } 
     else 
     { 
      outputStreamWriter = new OutputStreamWriter(getApplicationContext().openFileOutput(fileName, MODE_APPEND)); 
     } 

     outputStreamWriter.write(data+"\r\n"); 

     outputStreamWriter.close(); 
    } 
    catch (IOException e) 
    { 

    } 
} 


public String[] readFromFile(String fileName,boolean isAsset) 
{ 
    String[] ret=null; 

    try 
    { 
     InputStream inputStream; 

     if(isAsset) 
     { 
      inputStream = getApplicationContext().getAssets().open(fileName); 
     } 
     else 
     { 
      inputStream = getApplicationContext().openFileInput(fileName); 
     } 


     if (inputStream != null) 
     { 

      InputStreamReader inputStreamReader = new InputStreamReader(inputStream); 
      BufferedReader bufferedReader = new BufferedReader(inputStreamReader); 


      String receiveString; 

      StringBuilder stringBuilder = new StringBuilder(); 

      while ((receiveString = bufferedReader.readLine()) != null) { 

       stringBuilder.append(receiveString).append(","); 
      } 

      inputStream.close(); 
      ret = stringBuilder.toString().split(","); 

      inputStream.close(); 
     } 
    } 
    catch (FileNotFoundException e) 
    { 

    } 
    catch (IOException e) 
    { 

    } 

    return ret; 
} 
+0

Можете ли вы показать нам свой код? Вы должны вызывать свой alertdialog и влиять на значение перед вызовом вашей асинтезы, в случае, если вы вызываете alertdialog в asynctask. – theyouishere

ответ

0

Я полагаю, у вас есть setpositivebutton click listenener. Начните свою асинктаску в этом слушателе с нужным входом.

+0

Большое спасибо !!. Я был на нем часами. Еще раз спасибо, что это помогло. –

+0

Приветствую Вас! – Memme

0
  1. Сначала Напишите свою собственную функцию с параметрами.
  2. Задайте задачу async внутри этой функции.
  3. Теперь вызовите эту функцию, передав значения формы в качестве параметров этой функции после того, как вы закончите сглаживание диалогового окна.
Смежные вопросы