Toast Inside Fragment不工作

时间:2016-08-23 07:54:49

标签: java android android-fragments android-activity android-toast

我在片段中有片段我尝试在用户输入错误时调用Toast登录和密码但按下登录按钮时看不到Toast并且上面的toast正在调用,但仍然看不到Toast

This is my Fragment

这是我的片段

public class Login_Fragment extends Fragment {

    EditText LoginUname,LoginPass;
    ImageButton SignIn;
    Context context;
    public static final String TAG="Login Fragment";


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view= inflater.inflate(R.layout.login_fragment,container,false);
        LoginUname= (EditText) view.findViewById(R.id.Login_Box);
        LoginPass= (EditText) view.findViewById(R.id.Pass_Box);
        SignIn= (ImageButton) view.findViewById(R.id.LoginButton);

        SignIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String Phone=LoginUname.getText().toString();
                String Password=LoginPass.getText().toString();

                new AsyncTask(){
                    @Override
                    protected void onPostExecute(String result) {
                        super.onPostExecute(result);
                        Log.d("LOGIN FRAGMENT","Result: "+result); //GETTING RESULT FAIL HERE

                        if (result.equals("FAIL")){
                            Log.d("LOGIN FRAGMENT","Result is FAIL"); //THIS LOG SHOWING IN LOGCAT BUT TOAST IS NOT VISIBLE 
                            Toast.makeText(getActivity(), "Invalid Login And Password", Toast.LENGTH_LONG).show();

                        }
                        else if (result.equals("SUCCESS")){
                            Log.d("LOGIN FRAGMENT","Result is Success");

                        }

                    }
                }.execute();
                Log.d("LOGIN FRAGMENT","----LOGIN AND PASSWORD SENT");

            }
        });
        Registration.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Registration_Fragment registrationFragment=new Registration_Fragment();
                FragmentManager fragmentManager=getFragmentManager();
                FragmentTransaction transaction=fragmentManager.beginTransaction();
                transaction.replace(R.id.FragmentLoginRegistration,registrationFragment);
                transaction.commit();
            }
        });

        return view;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context=context;
    }
}

日志

08-23 14:04:38.115 29053-29053/com.boysjoys.com.pro_working1 D/LOGIN FRAGMENT: Result: FAIL
08-23 14:04:38.115 29053-29053/com.boysjoys.com.pro_working1 D/LOGIN FRAGMENT: Result is FAIL

我已经尝试了

Toast.makeText(getActivity(), "Invalid Login And Password", Toast.LENGTH_LONG).show();


Toast.makeText(getActivity().getApplicationContext(), "Invalid Login And Password", Toast.LENGTH_LONG).show();


Toast.makeText(Login_Fragment.this.getActivity(), "Invalid Login And Password", Toast.LENGTH_LONG).show();

几乎所有我可以用来显示吐司的方法,最后我尝试了runOnUiThread,但它仍未显示。

编辑1:添加了日志以显示我收到了来自服务器的响应 - " FAIL"

编辑2:我尝试了每一个答案,但我的Toast仍然没有显示出来。所以我的清单,布局是否有机会阻止Toast出现?如果是,请告诉我,以便我在我的问题中更新我的布局,风格,清单

6 个答案:

答案 0 :(得分:0)

如果在onAttach(Activity)之前运行,

getActivity()将返回null。相反,您应该直接在onPreExecute和onPostExecute方法中调用getActivity(),或者在onAttach中获取对它的引用:

public void onAttach (Activity attachedActivity) {
    activity = attachedActivity;
}

答案 1 :(得分:0)

最后或在应用活动中添加此方法并调用您希望其工作的位置

public void showToast(@NonNull String msg) {
    Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
}

答案 2 :(得分:0)

实际上你的代码对我来说很好。我已经在doInBackground中硬编码登录失败,因此它应该进入onPostExecute()登录失败块。这是代码

 new AsyncTask(){
                @Override
                protected Object doInBackground(Object[] params) {
                    return "FAIL"; // Hardcoded to make login fail
                }

                @Override
            protected void onPostExecute(Object result) {
                super.onPostExecute(result);
                Log.d("LOGIN FRAGMENT","Result: "+result);

                if (result.equals("FAIL")){
                    Log.d("LOGIN FRAGMENT","Result is FAIL");
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.d("LOGIN FRAGMENT","Result is FAIL 2");
                            Toast.makeText(getActivity(), "Invalid Login Or Password toast", Toast.LENGTH_LONG).show();
                        }
                    });

                }
                else if (result.equals("SUCCESS")){
                    Log.d("LOGIN FRAGMENT","Result is Success");

                }

            }
        }.execute();

答案 3 :(得分:0)

你应该在 UI线程上调用show Toast,所以试试这样:

Get-WmiObject win32_service -Filter 'Name="VSTTAgent"' -ComputerName $server | ForEach-Object {
    $filter = 'Name="{0}"' -f $_.PathName -replace '\\', '\\'
    $version = (Get-WmiObject CIM_DataFile -Filter $filter -ComputerName $server).Version

    if ($_.State -eq 'Running') {
        $userAccount = $ServiceInfo.DisplayName.ToString()
        Write-Host ("VSTTAgent ($version) service is Running on $server and  $userAccount")
    }
}

答案 4 :(得分:0)

我建议你像那样采取Asynctask Call

public class Login_Fragment extends Fragment {

EditText LoginUname,LoginPass;
ImageButton SignIn;
Context context;
public static final String TAG="Login Fragment";


@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view= inflater.inflate(R.layout.login_fragment,container,false);
    LoginUname= (EditText) view.findViewById(R.id.Login_Box);
    LoginPass= (EditText) view.findViewById(R.id.Pass_Box);
    SignIn= (ImageButton) view.findViewById(R.id.LoginButton);
 SignIn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String Phone=LoginUname.getText().toString();
            String Password=LoginPass.getText().toString();

              new Asynctask(Phone,Password).execute();

        }
    });

  Registration.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Registration_Fragment registrationFragment=new    Registration_Fragment();
            FragmentManager fragmentManager=getFragmentManager();
            FragmentTransaction    transaction=fragmentManager.beginTransaction();
              transaction.replace(R.id.FragmentLoginRegistration,registrationFragment);
            transaction.commit();
        }
    });

    return view;
 }

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    this.context=context;
}




 private class Asynctask extends AsyncTask<String, Integer, String> {


 String password,phone;

        public Asynctask(String phone, String password) {
            password=password;
            phone=phone;

        }
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected String doInBackground(String... params)
        {

       // you need to take doInbackground to return result
            return "SUCCESS";
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);

          Log.d("LOGIN FRAGMENT","Result: "+result);

            if (result.equals("FAIL")){
                Log.d("LOGIN FRAGMENT","Result is FAIL");
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d("LOGIN FRAGMENT","Result is FAIL 2");
                        Toast.makeText(getActivity(), "Invalid Login Or Password toast", Toast.LENGTH_LONG).show();
                    }
                });

            }
            else if (result.equals("SUCCESS")){
                Log.d("LOGIN FRAGMENT","Result is Success");

            }


        }
    }

 }

答案 5 :(得分:-1)

您可以通过以下代码实现Toast

public class arithmcalc {

public static void main(String[] args) {
    int operand1;
    int operand2;
    char operator;
    Scanner sc = new Scanner(System.in);
    System.out.println("enter operan1 operand2 and operator one by one");
    operand1 = sc.nextInt();
    sc.nextLine();
    operand2 = sc.nextInt();
    sc.next();
    operator = sc.findInLine(".").charAt(0);

    int result = 0;

    switch (operator) {
        case '+':
            result = operand1 + operand2;
            break;
        case '-':
            result = operand1 - operand2;
            break;
        case '*':
            result = operand1 * operand2;
            break;
        case '/':
            result = operand1 / operand2;
        default:
            System.out.println("illegal operand");
    }
  }
}