从listview适配器调用的对话框无法添加窗口 - 令牌null不适用于应用程序

时间:2016-08-27 17:38:35

标签: android listview dialog android-context

大家好,我在listview项目中从onClick侦听器中显示对话框时出现问题。在我在应用程序中调用listview适配器静态的某些方法之前,对话框在我的应用程序中出现并正常工作,以便我可以从适配器调用这些方法。我收到的错误是:

android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

致电:

   alertDialog.show();

在你告诉我去查找这个问题之前(因为我发现它很常见)我有。我找到了解决方案,但没有一个适合我。我还没有在自定义列表视图适配器中找到其他人遇到此问题。

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getContext());

工作正常,直到listview和某些方法在Services Acivity中保持静态。

DancerAdpater.java

public class DancerAdapter extends ArrayAdapter<OneDancer> {

   int type;
    private static FragmentManager fragmentManager;
    static Context context;
    static public Integer count=1;




  public DancerAdapter(Context context, ArrayList<OneDancer> dancers, int type) {
    super(context, 0, dancers);
    this.type=type;
    this.context=context;

}
    public DancerAdapter(Context context, ArrayList<OneDancer> dancers, int type,FragmentManager fragmentManager) {
        super(context, 0, dancers);
        this.type=type;
        this.fragmentManager = fragmentManager;
    }

@Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Get the data item for this position
        final OneDancer oneDancer = getItem(position);
        // Check if an existing view is being reused, otherwise inflate the view
        if (convertView == null) {


if(type==3) {

                convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_services, parent, false);

                final Button button4 = (Button)convertView.findViewById(R.id.button4);

                final TextView counterTextView = (TextView)convertView.findViewById(R.id.textView10);

                final Button button6 = (Button)convertView.findViewById(R.id.button6);

                final Button button5 = (Button)convertView.findViewById(R.id.button5);

                final Button button8 = (Button)convertView.findViewById(R.id.button8);

                final Button button9 = (Button)convertView.findViewById(R.id.button9);

                final Button button10 = (Button)convertView.findViewById(R.id.button10);



//Start Suite Button
                button8.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
                        // set title
                        alertDialogBuilder.setTitle("Confirm - Hold for Suite?");
                        // set dialog message
                        alertDialogBuilder
                                .setMessage("Confirm hold suite for " + oneDancer.name + "?")
                                .setCancelable(false)
                                .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,int id) {

                                        AsyncHttpClient client = new AsyncHttpClient();
                                        RequestParams params = new RequestParams();
                                        params.put("action", "makeVip");
                                        params.put("name", oneDancer.name);
                                        //params.put("TimeOut", );


                                        Log.v("SignInActivity","Girl Made UnAvailable Response Query");

                                        client.post("http://peekatu.com/apiweb/girlList.php", params,
                                                new AsyncHttpResponseHandler() {
                                                    @Override
                                                    public void onSuccess(String response) {
                                                        Log.v("response", response);
                                                        //responseString = response;
                                                        //parseDancerList(response);


                                                        button5.setVisibility(View.GONE);
                                                        button4.setVisibility(View.GONE);
                                                        button8.setVisibility(View.GONE);
                                                        button6.setVisibility(View.VISIBLE);
                                                        button9.setVisibility(View.VISIBLE);
                                                        button10.setVisibility(View.VISIBLE);
                                                        counterTextView.setVisibility(View.VISIBLE);
                                                        Services.refresh();


                                                        if (response.indexOf("OK") > -1) {
                                                            Toast.makeText(getContext(),
                                                                    "VIP Dance has began for " + oneDancer.name,
                                                                    Toast.LENGTH_SHORT).show();



                                                        }

                                                    }

                                                    @Override
                                                    public void onFailure(Throwable error, String content) {
                                                        Log.v("response", "response failed network error");
                                                        //waitncall(true);

                                                    }

                                                });
                                        dialog.cancel();
                                    }
                                })
                                .setNegativeButton("No",new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,int id) {
                                        // if this button is clicked, just close
                                        // the dialog box and do nothing
                                        dialog.cancel();
                                    }
                                });

                        // create alert dialog
                        AlertDialog alertDialog = alertDialogBuilder.create();

                        // show it
                        alertDialog.show();



                    }
                });

item_services.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#3d87d5">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Name"
        android:id="@+id/tvName"
        android:layout_weight="1"
        android:layout_gravity="center_vertical"
        android:textSize="20dp"
        android:textStyle="bold" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tvAvail"
        android:layout_gravity="center_vertical"
        android:layout_weight=".1"
        android:src="@drawable/online"
        />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/feature_button"
        android:id="@+id/button5"
        android:layout_gravity="center_vertical|right" />

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="@string/start_dance"
        android:id="@+id/button4"
        android:layout_gravity="center_vertical"
        android:background="#005906"
        android:layout_weight="1"
         />

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="+30 Mins"
        android:id="@+id/button10"
        android:layout_weight="1"
        android:visibility="gone" />

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="+60 Mins"
        android:id="@+id/button9"
        android:layout_weight="1"
        android:visibility="gone" />

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Start Suite"
        android:id="@+id/button8"
        android:layout_weight="1"
        android:background="#fdd32b" />

    <TextView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="00"
        android:id="@+id/textView10"
        android:visibility="gone"
        android:layout_weight="1" />

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="@string/stop_dance"
        android:id="@+id/button6"
        android:background="#ab0000"
        android:visibility="gone"
        android:layout_weight="1" />

</LinearLayout>

Services.java

public class Services extends Activity {

static Context context;
static private ListView listView ;
static private String responseString;
static String responseString2;
static ArrayList<OneDancer> oneDancerArrayList = new ArrayList<OneDancer>();
public DancerAdapter adapter;
Button addDancer;
Button loginDancer;
EditText dancerName;
EditText nameInput;
Integer count=0;
static DialogFragment newFragment;
public View rootView;

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

    Services.context = getApplicationContext();
    if(adapter!=null){
        adapter.clear();
    }

    View rootView = null;
    View currentFocus = getWindow().getCurrentFocus();
    if (currentFocus != null)
        rootView = currentFocus.getRootView();

    Log.v("SignInActivity", "Activity has began");
    // Declare Listview
    listView = (ListView) findViewById(R.id.listView);

    // Assign adapter to ListView
    listView.setAdapter(adapter);

    //Call to Database and retrieve girl list
    getGirlList();

    }

static public void refresh(){
        getGirlList();
        adapter.notifyDataSetChanged();
    }
static public void getGirlList() {

    Log.v("SignInActivity","getGirlList has started");


    AsyncHttpClient client = new AsyncHttpClient();
    RequestParams params = new RequestParams();
    params.put("action", "getDancers");

    Log.v("SignInActivity","Girl List Response Query");

    client.post("http://peekatu.com/apiweb/girlList.php", params,
            new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(String response) {
                    Log.v("response", response);
                    responseString = response;
                    parseDancerList(response);
                    Log.v("SignInActivity", response);
                    Log.v("SignInActivity","Girl List Response" + responseString);
                }

                @Override
                public void onFailure(Throwable error, String content) {
                    Log.v("response", "response failed network error");
                    //waitncall(true);

                }

            });
    Log.v("SignInActivity","getGirlList ended");
}


// Parsing of private messages
    static public void parseDancerList(String response) {

    Log.v("SignInActivity","parseDancerList");
    XMLParser parser = new XMLParser();

    Document doc = parser.getDomElement(response); // getting DOM element

    NodeList nl = doc.getElementsByTagName("DANCERS");

oneDancerArrayList.clear();



    Log.v("response ", "Dancer Count " + nl.getLength());
    // looping through all item nodes <item>
    for (int i = 0; i < nl.getLength(); i++) {
        // creating new HashMap
        //adapter = new DancerAdapter(context,oneDancerArrayList,3);
       // adapter = new DancerAdapter(this,oneDancerArrayList,3);
        Element e = (Element) nl.item(i);
        Log.v("response ", "Dancers  " + parser.getValue(e, "NAME"));

        OneDancer newDancer = new OneDancer(parser.getValue(e,"POSITION"),
                parser.getValue(e,"NAME"),
                parser.getValue(e,"AVAILABLE"),
                null,
                null,
                null,
                null,
                null,
                null,"0");

        adapter.addAll(newDancer);
        listView.setAdapter(adapter);
        adapter.notifyDataSetChanged();




    }

}

我已尝试thisServices.this以及getApplicationContext(),但这些解决方案都不适用于我。请帮忙。谢谢。

1 个答案:

答案 0 :(得分:0)

您可以按照以下步骤操作:

  1. 为适配器数据源创建一个全局ArrayList,并使用此arraylist初始化适配器(在使用之前初始化它)onCreate()方法
  2. 当新数据可用时,通过调用ArrayList.clear()清除ArrayList的先前数据,然后将所有新数据添加到该Arraylist并调用adapter.notifyDataSetChanged();
  3. 通过这种方式,您可以避免在静态上下文中使用this

    <强>编辑: 使用Context创建传递给构造函数的AlertDialog。

    1. 在Adapter类中声明一个Context变量,并使用您作为参数传递的上下文对象在构造函数内初始化它。
    2. 然后使用该上下文对象初始化AlertDialog。

       AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getContext());
      
    3. 使用在构造函数中初始化的上下文变量而不是getContext()