java.lang.IllegalArgumentException:从给定的视图中找不到合适的父级。请提供有效的视图

2022-09-01 12:49:08

我的应用程序崩溃时尝试显示服务器消息,我认为问题可能出在我的.下面是崩溃发生和我的getView()registerActivityactivity_register.xml

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.fastchat.helper.SQLiteHandler;
import com.fastchat.helper.SessionManager;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


public class RegisterActivity extends Activity {

private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnRegister;
private Button btnLinkToLogin;
private EditText inputFullName;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
private ProgressBar progress;


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


    inputFullName = (EditText) findViewById(R.id.name);
    inputEmail = (EditText) findViewById(R.id.email);
    inputPassword = (EditText) findViewById(R.id.password);
    btnRegister = (Button) findViewById(R.id.btnRegister);
    btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);

    // Progress dialog
    pDialog = new ProgressDialog(this);
    pDialog.setCancelable(true);

    /*
    // Session manager
    session = new SessionManager(getApplicationContext());

    // SQLite database handler
    db = new SQLiteHandler(getApplicationContext());

    // Check if user is already logged in or not
   if (session.isLoggedIn()) {
        // User is already logged in. Take him to main activity
        Intent intent = new Intent(RegisterActivity.this,
                SearchableActivity.class);
        startActivity(intent);
        finish();

    }
*/
    // Register Button Click event
    btnRegister.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            String name = inputFullName.getText().toString();
            String email = inputEmail.getText().toString();
            String password = inputPassword.getText().toString();

            if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {
                registerProcess(name, email, password);
            } else {
                Toast.makeText(getApplicationContext(),
                        "Please enter your details!", Toast.LENGTH_LONG)
                        .show();
            }
        }
    });

    // Link to Login Screen
    btnLinkToLogin.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            Intent i = new Intent(getApplicationContext(),
                    LoginActivity.class);
            startActivity(i);
            finish();
        }
    });

}   

 private void registerProcess(String name,String email,String password){

    String tag_string_req = "req_register";
    //pDialog = new AlertDialog.Builder(getActivity());
    pDialog.setMessage("please wait");
    pDialog.show();


    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    RequestInterface requestInterface = retrofit.create(RequestInterface.class);

    User user = new User();
    user.setName(name);
    user.setEmail(email);
    user.setPassword(password);
    ServerRequest request = new ServerRequest();
    request.setOperation(Constants.REGISTER_OPERATION);
    request.setUser(user);
    Call<ServerResponse> response = requestInterface.operation(request);

    response.enqueue(new Callback<ServerResponse>() {
        private View view;

        public View getView() {
            return view;

        }

        @Override
        public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {

            ServerResponse resp = response.body();

           if(resp !=null)//tried to check if resp is null but its not

//crash occurs here
            Snackbar.make(getView(),resp.getMessage(), Snackbar.LENGTH_LONG).show();
            pDialog.dismiss();
        }


        @Override
        public void onFailure(Call<ServerResponse> call, Throwable t) {

           // progress.setVisibility(View.INVISIBLE);
            Log.d(Constants.TAG, "failed");
            Toast.makeText(getApplicationContext(), t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
            pDialog.dismiss();


        }
    });
}

activity_register.xml

  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:tools="http://schemas.android.com/tools"
android:background="@color/bg_register"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp"
android:id="@+id/chat">

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:orientation="vertical"
    android:paddingLeft="20dp"
    android:paddingRight="20dp" >

    <ImageView
        android:layout_width="389dp"
        android:layout_height="72dp"
        android:layout_gravity="center_horizontal"
        android:layout_marginBottom="24dp"
        android:src="@drawable/logo"
        tools:ignore="ContentDescription" />


    <EditText
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:background="@color/input_register_bg"
        android:hint="@string/hint_name"
        android:padding="10dp"
        android:singleLine="true"
        android:inputType="textCapWords"
        android:textColor="@color/input_register"
        android:textColorHint="@color/input_register_hint" />

    <EditText
        android:id="@+id/email"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:background="@color/input_register_bg"
        android:hint="@string/hint_email"
        android:inputType="textEmailAddress"
        android:padding="10dp"
        android:singleLine="true"
        android:textColor="@color/input_register"
        android:textColorHint="@color/input_register_hint" />

    <EditText
        android:id="@+id/password"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:background="@color/input_register_bg"
        android:hint="@string/hint_password"
        android:inputType="textPassword"
        android:padding="10dp"
        android:singleLine="true"
        android:textColor="@color/input_register"
        android:textColorHint="@color/input_register_hint" />

    <!-- Login Button -->

    <Button
        android:id="@+id/btnRegister"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dip"
        android:background="#ea4c88"
        android:text="register"
        android:textColor="@color/white" />

    <!-- Link to Login Screen -->

    <Button
        android:id="@+id/btnLinkToLoginScreen"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dip"
        android:background="@null"
        android:text="already a member? login"
        android:textAllCaps="false"
        android:textColor="@color/white"
        android:textSize="15dp" />
</LinearLayout>

下面是日志消息

 java.lang.IllegalArgumentException: No suitable parent found from the given view. Please provide a valid view.
                                                              at android.support.design.widget.Snackbar.make(Snackbar.java:137)
                                                              at com.chat.RegisterActivity$3.onResponse(RegisterActivity.java:143)
                                                              at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:68)
                                                              at android.os.Handler.handleCallback(Handler.java:739)
                                                              at android.os.Handler.dispatchMessage(Handler.java:95)

答案 1

我建议您尝试使用.findViewById(android.R.id.content)

这就是为我做的诀窍:

Snackbar.make(findViewById(android.R.id.content), resp.getMessage(), Snackbar.LENGTH_LONG).show();

android.R.id.content将为您提供视图的根元素(有关更多信息,请查看Android:什么是Android。R.id.content 用于?)。


答案 2

我发现了一个解决方案,可以帮助其他正在寻找共同解决方案的人。

当我尝试在加载整个XML文件之前使用Skackbar显示消息时,我遇到了此错误。

在片段中,我试图调用API并显示如下消息:onCreateView();SnackbarInternet connection is off

@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    mBindingObject = DataBindingUtil.inflate(inflater, getLayoutResId(), container, false);

    getData();

    return mBindingObject.getRoot();
}

我只是把那个方法放进去onViewCreated()

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    getData();
}

它现在为我工作。

奖金:

始终尝试在成功加载视图后使用视图。一条线的每个位置都很重要。

谢谢。


推荐