数据库调用后弹出对话框的时间

时间:2018-03-09 19:55:28

标签: java android

在我从Firebase数据库加载数据后,我需要弹出一个对话框,因为我希望弹出窗口包含数据库中的信息。

我的弹出窗口是这样写的;

    AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
    builder.setMessage("Check the match details are correct;\n\n-Home Team - " + diaHomeTeam + "\n-Away Team - " + diaAwayTeam +"\n-Time / Date - " + diaDate + " / " + diaTime + " \n-Pitch number - " + diaPitch)
            .setCancelable(false)
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    //do things
                }
            });
    AlertDialog alert = builder.create();
    alert.show();

并且在我的公共虚空onViewCreated中。我的数据库调用在public void onAttach中,无论我何时尝试调用该对话框,它总是返回null,因为它在返回数据之前执行。

我是Android开发的新手,想要查找有关方法执行顺序的信息,因此我可以确定首先调用的内容以及在捕获数据库值后允许我调用对话框的内容在我的类变量中预先(或者我是否需要在构造函数中执行此操作?)。

感谢所有帮助。

下面的完整片段代码;

package uk.co.futsalselect.app.futsalselect;

import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.MutableData;
import com.google.firebase.database.Query;
import com.google.firebase.database.Transaction;
import com.google.firebase.database.ValueEventListener;

import java.util.HashMap;
import java.util.Map;

import static android.content.ContentValues.TAG;

public class refscorecard_fragment extends Fragment {
    private OnFragmentInteractionListener mListener;
    ListView listViewLive;
    ImageView stopWatch;
    Integer gameOn = 0;

    public refscorecard_fragment() {
        // Required empty public constructor
    }

    public static refscorecard_fragment newInstance(String param1, String param2) {
        refscorecard_fragment fragment = new refscorecard_fragment();
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        listViewLive = (ListView) getView().findViewById(R.id.listViewAsItHappens);
    }

    public void updateDBMatches(final String fieldUpd, final Object valueUpd) {
        String getArgument = getArguments().getString("matchid");
        final DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("Matches").child(getArgument);
        ref.runTransaction(new Transaction.Handler() {
            @Override
            public Transaction.Result doTransaction(MutableData mutableData) {
                Map<String, Object> updates = new HashMap<String,Object>();
                updates.put(fieldUpd, valueUpd);
                ref.updateChildren(updates);
                return null;
            }
            @Override
            public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_refscorecard, container, false);

        AlertDialog.Builder diaBox = alert();
        diaBox.show();

        //Home Score Button
        Button homeScoreBtn = (Button) view.findViewById(R.id.btnHomeTeam);
        homeScoreBtn.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Button homeScoreBtn = (Button) getView().findViewById(R.id.btnHomeTeam);
                String homeScore = (String) homeScoreBtn.getText();
                final int homeScoreAdd = Integer.valueOf(homeScore.toString()) + 1;
                homeScoreBtn.setText(String.valueOf(homeScoreAdd));
                updateDBMatches("homeScore", homeScoreAdd);
            }
        });

        //Away Score Button
        Button awayScoreBtn = (Button) view.findViewById(R.id.btnAwayTeam);
        awayScoreBtn.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Button awayScoreBtn = (Button) getView().findViewById(R.id.btnAwayTeam);
                String awayScore = (String) awayScoreBtn.getText();
                final int awayScoreAdd = Integer.valueOf(awayScore.toString()) + 1;
                awayScoreBtn.setText(String.valueOf(awayScoreAdd));
                updateDBMatches("awayScore", awayScoreAdd);
            }
        });

        //Away Fouls Button
        Button awayFoulsBtn = (Button) view.findViewById(R.id.btnAwayFouls);
        awayFoulsBtn.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Button awayFoulsBtn = (Button) getView().findViewById(R.id.btnAwayFouls);
                String awayFouls = (String) awayFoulsBtn.getText();
                final int awayFoulsAdd = Integer.valueOf(awayFouls.toString()) + 1;
                awayFoulsBtn.setText(String.valueOf(awayFoulsAdd));

                if (Integer.valueOf(awayFoulsAdd) > 5) {
                    awayFoulsBtn.setBackgroundColor(Color.parseColor("#ff0000"));
                    MediaPlayer mp = MediaPlayer.create(getContext(), R.raw.airhornsoundeffect);
                    mp.start();
                }
                updateDBMatches("awayFouls", awayFoulsAdd);
            }
        });

        //Home Fouls Button
        Button homeFoulsBtn = (Button) view.findViewById(R.id.btnHomeFouls);
        homeFoulsBtn.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Button homeFoulsBtn = (Button) getView().findViewById(R.id.btnHomeFouls);
                String homeFouls = (String) homeFoulsBtn.getText();
                final int homeFoulsAdd = Integer.valueOf(homeFouls.toString()) + 1;
                homeFoulsBtn.setText(String.valueOf(homeFoulsAdd));

                if (Integer.valueOf(homeFoulsAdd) > 5) {
                    homeFoulsBtn.setBackgroundColor(Color.parseColor("#ff0000"));
                    MediaPlayer mp = MediaPlayer.create(getContext(), R.raw.airhornsoundeffect);
                    mp.start();
                }
                updateDBMatches("homeFouls", homeFoulsAdd);
            }
        });

        //Home Score Min Button
        Button homeScoreMinBtn = (Button) view.findViewById(R.id.btnMinHomeScore);
        homeScoreMinBtn.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Button homeScoreBtn = (Button) getView().findViewById(R.id.btnHomeTeam);
                String homeScoreMin = (String) homeScoreBtn.getText();

                if (Integer.valueOf(homeScoreMin.toString()) > 0) {
                    final int homeScoreAdd = Integer.valueOf(homeScoreMin.toString()) -1;
                    homeScoreBtn.setText(String.valueOf(homeScoreAdd));
                    updateDBMatches("homeScore", homeScoreAdd);
                }
            }
        });

        //Away Score Min Button
        Button awayScoreMinBtn = (Button) view.findViewById(R.id.btnMinAwayScore);
        awayScoreMinBtn.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Button awayScoreBtn = (Button) getView().findViewById(R.id.btnAwayTeam);
                String awayScoreMin = (String) awayScoreBtn.getText();
                if (Integer.valueOf(awayScoreMin.toString()) > 0) {
                    final int awayScoreAdd = Integer.valueOf(awayScoreMin.toString()) - 1;
                    awayScoreBtn.setText(String.valueOf(awayScoreAdd));
                    updateDBMatches("awayScore", awayScoreAdd);
                }
            }
        });

        //Countdown clock button
        Button counterBtn = (Button) view.findViewById(R.id.matchCountDownBtn);
        counterBtn.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                updateDBMatches("played", 1);
                final Button counterBtn = (Button) getView().findViewById(R.id.matchCountDownBtn);
                new CountDownTimer(20000, 1000){
                    public void onTick(long millisUntilFinished){
                        stopWatch.setVisibility(View.VISIBLE);
                        counterBtn.setEnabled(false);
                        long l = millisUntilFinished / 1000;
                        int i = (int) l;
                        counterBtn.setText(secondsToString(i));
                        gameOn = 1;
                    }
                    public  void onFinish(){
                        gameOn = 0;
                        MediaPlayer mp = MediaPlayer.create(getContext(), R.raw.airhornsoundeffect);
                        mp.start();
                        //Disable score buttons
                        Button homeFoulsBtnDisabled = (Button) getView().findViewById(R.id.btnHomeFouls);
                        Button awayFoulsBtnDisabled = (Button) getView().findViewById(R.id.btnAwayFouls);
                        homeFoulsBtnDisabled.setEnabled(false);
                        awayFoulsBtnDisabled.setEnabled(false);
                        Button counterBtn = (Button) getView().findViewById(R.id.matchCountDownBtn);
                        stopWatch.setVisibility(View.INVISIBLE);
                        counterBtn.setText("FULL TIME");
                        updateDBMatches("played", 2);
                    }
                }.start();
            }
        });

        return view;
    }

    public void onPause() {
        super.onPause();
        if (gameOn == 1) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
            builder.setMessage("Are you sure you want to cancel the match?")
                    .setCancelable(false)
                    .setTitle("Cancel match?")
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            //do things
                        }
                    });
            AlertDialog alert = builder.create();
                alert.show();
        }
    }


    private String secondsToString(int pTime) {
        return String.format("%02d:%02d", pTime / 60, pTime % 60);
    }

    private String diaHomeTeam;
    private String diaAwayTeam;
    private String diaDate;
    private String diaTime;
    private String diaPitch;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        String getArgument = getArguments().getString("matchid");
        DatabaseReference database = FirebaseDatabase.getInstance().getReference();
        DatabaseReference ref = database.child("Matches");
        Query gameQuery = ref.orderByChild("gameID").equalTo(getArgument);
        gameQuery.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
                    TextView homeTeamSetTxt = (TextView) getView().findViewById(R.id.txtRefHomeTeam);
                    TextView awayTeamSetTxt = (TextView) getView().findViewById(R.id.txtRefAwayTeam);
                    TextView dataSetTxt = (TextView) getView().findViewById(R.id.txtRefDate);
                    TextView timeSetTxt = (TextView) getView().findViewById(R.id.txtRefTime);
                    TextView pitchSetTxt = (TextView) getView().findViewById(R.id.txtRefPitch);
                    Button homeScoreBtn = (Button) getView().findViewById(R.id.btnHomeTeam);
                    Button awayScoreBtn = (Button) getView().findViewById(R.id.btnAwayTeam);
                    Button homeFoulBtn = (Button) getView().findViewById(R.id.btnHomeFouls);
                    Button awayFoulBtn = (Button) getView().findViewById(R.id.btnAwayFouls);
                    homeTeamSetTxt.setText(singleSnapshot.child("homeTeam").getValue().toString());
                    awayTeamSetTxt.setText(singleSnapshot.child("awayTeam").getValue().toString());
                    dataSetTxt.setText(singleSnapshot.child("date").getValue().toString());
                    timeSetTxt.setText(singleSnapshot.child("time").getValue().toString());
                    pitchSetTxt.setText("Pitch " + singleSnapshot.child("pitch").getValue().toString());
                    homeScoreBtn.setText(singleSnapshot.child("homeScore").getValue().toString());
                    awayScoreBtn.setText(singleSnapshot.child("awayScore").getValue().toString());
                    homeFoulBtn.setText(singleSnapshot.child("homeFouls").getValue().toString());
                    awayFoulBtn.setText(singleSnapshot.child("awayFouls").getValue().toString());

                    stopWatch = (ImageView) getView().findViewById(R.id.imgStopWatch);
                    stopWatch.setVisibility(View.INVISIBLE);

                    diaHomeTeam = singleSnapshot.child("homeTeam").getValue().toString();
                    diaAwayTeam = singleSnapshot.child("awayTeam").getValue().toString();
                    diaDate = singleSnapshot.child("date").getValue().toString();
                    diaTime = singleSnapshot.child("time").getValue().toString();
                    diaPitch = singleSnapshot.child("pitch").getValue().toString();
                }
            }
            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.e(TAG, "onCancelled", databaseError.toException());
            }
        });
    }



    private AlertDialog.Builder alert() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setMessage("Check the match details are correct;\n\n-Home Team - " + diaHomeTeam + "\n-Away Team - " + diaAwayTeam + "\n-Time / Date - " + diaDate + " / " + diaTime + " \n-Pitch number - " + diaPitch)
                .setCancelable(false)
                .setTitle("Checklist")
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        //do things
                    }
                });
        AlertDialog alert = builder.create();
        return builder;
        //alert.show();
        //myQuittingDialogBox.setIcon(R.drawable.);
    }



    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

1 个答案:

答案 0 :(得分:1)

您应该已经发布了片段中的所有代码。

您可以在此处查看片段生命周期:https://developer.android.com/guide/components/fragments.html#Creating

但是您希望在收到数据库中的信息后创建并显示对话框。