简体   繁体   中英

How to show alertdialog before asynctask start

I want to show an alertdialog and get some input from user and after that, processing that inputs in an asynctask but the alertdialog become dismissed before get inputs and asynctask start to execute.

What should I do? Please help me. Here is my code;

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

I suppose you have a setpositivebutton click listener. Start your asynktask in that listener with the desired input.

  1. First Write your own function with parameters.
  2. Call async task inside that function.
  3. Now call that function by pass the form values as parameters to that function after you finish dimiss the dialog box.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM