【问题标题】:Alert Dialog Exception "Unable to add windows -- token null is not for an application", what context should I give?警告对话框异常“无法添加窗口——令牌 null 不适用于应用程序”,我应该给出什么上下文?
【发布时间】:2018-06-18 19:49:37
【问题描述】:

我知道之前有人问过同样的问题,我检查了他们并没有帮助,所以我正在构建一个 Android 应用程序,我正在使用列表视图,我在项目中添加了一个按钮,删除条目,我想显示一个确认对话框。

当我按下那个按钮时,应用程序崩溃了,当我搜索问题时,我发现我正在传递的上下文中存在问题,我尝试了很多东西但我找不到解决方案,这里是代码。 这是项目适配器代码:

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    final View v;

    LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    v = layoutInflater.inflate(R.layout.product_cell, null);

    final Produit currentProduit = getItem(position);
    getviews(v);
    fillViews(currentProduit);

    supprimer.setOnClickListener(new Button.OnClickListener() {
        @Override
        public void onClick(View view) {
            MyMethodsClass.displayToast("i'm working dude", view.getContext());
            AlertDialog.Builder confirmDialog;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
                confirmDialog = new AlertDialog.Builder(v.getContext(), android.R.style.Theme_Material_Dialog_Alert);
            else
                confirmDialog = new AlertDialog.Builder(v.getContext());

            confirmDialog.setTitle("Supprimer?");
            confirmDialog.setMessage("Etes vous sur de vouloir supprimer le produit" + currentProduit.getNomP());
            confirmDialog.setNegativeButton("Annuler", new AlertDialog.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                }
            });
            confirmDialog.setPositiveButton("Confirmer", new AlertDialog.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    deleteProduct(currentProduit);
                    productsAdapter.remove(currentProduit);
                    productsAdapter.notifyDataSetChanged();
                }
            }).show();
        }
    });

    return v;
}

这是使用它的活动的代码:

public class Stock extends AppCompatActivity implements View.OnClickListener {

String barcode;
EditText codebare, nomproduit;
Button scanbut, rechbut;
ListView stockProdList;
ArrayList<Produit> productsArray;
public static ProductsAdapter productsAdapter;
public Context context = this;

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

    barcode = getIntent().getStringExtra("code");
    codebare = (EditText) findViewById(R.id.rechStockEditScan);
    nomproduit = (EditText) findViewById(R.id.rechStockNomP);
    scanbut = (Button) findViewById(R.id.scannStock);
    rechbut = (Button) findViewById(R.id.rechercheStock);
    stockProdList = (ListView) findViewById(R.id.listStockSup);

    productsAdapter = new ProductsAdapter(getApplicationContext(), 0);
    productsArray = new ArrayList<>();

    if (!TextUtils.isEmpty(barcode))
        codebare.setText(barcode);

    stockProdList.setAdapter(productsAdapter);
    fillListView();
}

void searchProduct() {
    productsArray.clear();
    String query = "SELECT * FROM produit WHERE ";
    if (!nomproduit.getText().toString().isEmpty() && !codebare.getText().toString().isEmpty()) {
        query += "NOMP='" + nomproduit.getText().toString() + "' AND BAREC='" + codebare.getText().toString() + "';";
    } else if (!nomproduit.getText().toString().isEmpty()) {
        query += "NOMP='" + nomproduit.getText().toString() + "';";
    } else if (!codebare.getText().toString().isEmpty()) {
        query += "BAREC='" + codebare.getText().toString() + "';";
    } else {
        MyMethodsClass.displayToast("FAUT REMPLIRE AU MOIN UN CHAMP POUR RECHERCHER", this);
    }
    try {
        Connection connection = DataBaseConnection.CONNECT();
        Statement st = connection.createStatement();
        ResultSet rs = st.executeQuery(query);

        while (rs.next()) {
            productsArray.add(new Produit(rs.getString("NOMP"), rs.getString("BAREC"), rs.getString("PHOTOP"), rs.getFloat("PRIXA"), rs.getFloat("PRIXG"),
                    rs.getFloat("PRIXD"), rs.getInt("QUANTITEP"), rs.getInt("NBREMBA"), rs.getInt("IDP")));
        }
    } catch (Exception e) {
        Log.e("ERROR WHILE SEARCHING FOR DATA LINE 70", e.getMessage());
    }
    Log.e("what the hell?", "it's running");
    productsAdapter.clear();
    productsAdapter.addAll(productsArray);
    stockProdList.setAdapter(null);
    stockProdList.setAdapter(productsAdapter);
}

这是日志:

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.simapps.mobilestock, PID: 9260
              android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
                  at android.view.ViewRootImpl.setView(ViewRootImpl.java:684)
                  at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:289)
                  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
                  at android.app.Dialog.show(Dialog.java:311)
                  at android.app.AlertDialog$Builder.show(AlertDialog.java:993)
                  at Adapters.ProductsAdapter$1.onClick(ProductsAdapter.java:87)
                  at android.view.View.performClick(View.java:4855)
                  at android.view.View$PerformClick.run(View.java:20287)
                  at android.os.Handler.handleCallback(Handler.java:815)
                  at android.os.Handler.dispatchMessage(Handler.java:104)
                  at android.os.Looper.loop(Looper.java:194)
                  at android.app.ActivityThread.main(ActivityThread.java:5637)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:372)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)

【问题讨论】:

    标签: java android exception token android-context


    【解决方案1】:

    要显示Dialog,您需要使用Activity 上下文。在这里,您使用了不正确的 Application 上下文。

    productsAdapter = new ProductsAdapter(getApplicationContext(), 0);
    

    要使其正常工作,请将上面的行更改为使用 Activity 上下文。由于此调用是在 Activity 内进行的,因此您可以使用:

    productsAdapter = new ProductsAdapter(this, 0);
    

    但这不是最好的方法,因为您的参数类型是 Context 而不是 Acticity,而且当它发生在您身上时,上下文可能不正确。

    更好的办法是为您的Activity 提供一个点击监听回调,并在Activity 中管理Dialog 而不是Adapter

    【讨论】:

    • 非常感谢,它完成了这项工作,现在我将尝试“更好的想法”,谢谢。
    猜你喜欢
    • 2020-09-17
    • 2011-12-17
    • 1970-01-01
    • 1970-01-01
    • 2012-09-12
    • 1970-01-01
    • 1970-01-01
    • 2011-05-28
    相关资源
    最近更新 更多