无法在Android上显示AlertDialog,因为我收到了NullPointerException

时间:2013-10-23 16:06:51

标签: android android-alertdialog android-dialog

我有一个活动,我想显示没有按钮和元素列表的AlertDialog。 问题是,如果我显示它,我会收到此错误:

  

显示java.lang.NullPointerException   在android.widget.createViewFromResource(ArrayAdapter.java 394)......

这是我的代码:

    public class ContactsActivity extends BasicListActivity implements TextWatcher, DialogInterface.OnClickListener {

    protected static final String NAMES_SHARED_PREF = "names_shared_pref";
    protected static final String LEMON_SHARED_PREF = "lemon_shared_pref";

    protected EditText search_bar;
    protected ImageButton search_button;

    ProgressDialog diag;

    protected ArrayList<String> source = new ArrayList<String>();
    protected ArrayList<String> names_result = new ArrayList<String>(); // i risultati di una ricerca
    protected ArrayList<Boolean> lemonSims = new ArrayList<Boolean>();
    protected ArrayList<Boolean> lemon_result = new ArrayList<Boolean>(); // per i risultati della ricerca

    protected ServerInterface server;

    String empty_message; 
    protected String script_name = "app_autocomplete.php";

    protected AlertDialog.Builder builder;

    protected String my_number ="";

    protected String[] numbers; //viene usato per scegliere il numero dei contatti multipli
    protected int popup_pos = 0;


/*============================================================= METHODS ================================================================*/


    /**
     * ON CREATE
     * se la mainactivity non ha già le azioni nella savedInstanceState lancia una asynctask per ottenerle
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {


        this.setContentView(R.layout.search);

        Bundle extras = this.getIntent().getExtras();
        if (extras != null){
            if (extras.containsKey(SmsChat.MY_PHONE)) my_number = extras.getString(SmsChat.MY_PHONE);
        }

        search_bar = (EditText) findViewById(R.id.search_bar);
        search_button = (ImageButton) findViewById(R.id.search_button);
        search_bar.addTextChangedListener(this);
        listview = (ListView) findViewById(android.R.id.list);

        diag = new ProgressDialog(ContactsActivity.this);
           diag.setMessage(getResources().getString(R.string.updating));

        super.onCreate(savedInstanceState);

        getActionBar().setTitle(this.getResources().getString(R.string.contacts));

        builder = new AlertDialog.Builder(this);

        search_bar.setOnEditorActionListener(new OnEditorActionListener(){

            @Override
            public boolean onEditorAction(TextView v, int actionId,
                    KeyEvent event) {

                setContents(search(v.getText().toString()));

                return true;
            }

        });


        search_button.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {

                setContents(search(search_bar.getText().toString()));

            }



        });



        listview.setOnItemClickListener(new OnItemClickListener(){

            @Override
            public void onItemClick(AdapterView<?> l, View v, final int position,
                    long id) {
                ContactsInterface con = new ContactsInterface();

                numbers = con.getContactNumberByDisplayName(names_result.get(position), ContactsActivity.this);

                popup_pos = position;

                if (numbers.length >1)
                {

                    builder.setTitle(R.string.phone_numbers);
                    builder.setItems(numbers , new PopUpClickListener());

                    AlertDialog dialog = builder.create();
                    dialog.show();
                }else{
                    startChat(numbers,position, 0);
                }


            }

        });






    }




    @Override
    public void setup(){

        GetContacts gettask = new GetContacts();
        gettask.execute("");

    }




    public void setContents(ArrayList<String> names){


        if (names == null) return;



        setContent(names, lemon_result);

    }


    /**
     *  SET CONTENT 
     *  
     *  */
    public void setContent(ArrayList<String> data, ArrayList<Boolean> lemonSims){

        if (lemonSims.size() != data.size()){
            lemonSims.clear();
            for (int i=0; i<data.size();i++){
                lemonSims.add(false);
            }

        }

        if (data.size()>0){
            ContactsAdapter adpt = new ContactsAdapter(data, lemonSims, this);
            listview.setAdapter(adpt);
            adpt.notifyDataSetChanged();

        }
        else{
            setEmptyLayout();
        }
    }



    /**
     * SEARCH
     * @param pattern
     * @return
     */
    public ArrayList<String> search(String pattern){

        ArrayList<String> res = new ArrayList<String>();
        ArrayList<Boolean> sims = new ArrayList<Boolean>();

        if (source == null) return null;
        if (pattern.length() <2){
            names_result = source;
            lemon_result = lemonSims;
            return source;
        }

        for (int i=0; i<source.size();i++){

            if (source.get(i).toLowerCase(Locale.US).contains(pattern.toLowerCase(Locale.US))){
                res.add(source.get(i));
                sims.add(lemonSims.get(i));
            }
        }
        names_result = res;
        lemon_result = sims;
        return res;

    }


    @Override
    public void afterTextChanged(Editable arg0) {


    }


    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
            int arg3) {


    }


    @Override
    public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) {

        setContents(search(s.toString()));

    }




    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.contacts_menu, menu);
            return true;
    }

    /**
     * ON OPTION ITEM SELECTED
     * associa un'azione ad ogni oggetto dell'action bar
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Pass the event to ActionBarDrawerToggle, if it returns
        // true, then it has handled the app icon touch event


        switch (item.getItemId()) {


        case R.id.action_writenumber:
        {
            Intent intent = new Intent(this, SmsChat.class);
            intent.putExtra(SmsChat.MY_PHONE, my_number);
            startActivity(intent);
            finish();
            return true;
        }
        case R.id.action_update:{
            diag.show();
            GetContacts task = new GetContacts();
            task.execute("update");
            return true;
        }

        }

        return super.onOptionsItemSelected(item);
    }



    /**
     * GET CONTACTS TASK
     * @author pc
     *
     */
    protected class GetContacts extends AsyncTask<String, Void, Boolean>{



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

               diag.show();

           }


        @Override
        protected Boolean doInBackground(String... params) {
            /**
             * I contatti sono caricati in un'altra attività
             */

            if (params[0].equalsIgnoreCase("update")){
                ContactsInterface con = new ContactsInterface();
                con.loadFromPhone(ContactsActivity.this);
            }
            names_result = ContactsInterface.getContactsNames();
            source = names_result;



            lemonSims.clear();
            lemonSims = ContactsInterface.getContactsLemon();

            if (lemonSims.size() != source.size() || params[0].equalsIgnoreCase("update")) {
                if (AppUtils.isOnline(ContactsActivity.this)){
                    CheckOnlineTask task = new CheckOnlineTask();
                    task.execute("");
                }else {
                    lemonSims.clear();
                    for (int i=0; i<source.size();i++){
                        lemonSims.add(false);
                    }
                    lemon_result = lemonSims;
                    return true;
                }

            } else {
                lemon_result = lemonSims;
                return true;
            }

            return false;
        }

        @Override
        protected void onPostExecute(Boolean success){
            if (success){
                ContactsActivity.this.setContents(source);
                diag.hide();
            }


        }

    }



    /**
    * CHECK LEMONSIM TASK 
    * AsyncTask che fa partire lo stream
    * @author pc
    *
    */
   protected class CheckOnlineTask extends AsyncTask<String, Void, Boolean> {

       JSONArray jobject = new JSONArray();



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

        ServerInterface server = new ServerInterface();
        ContactsInterface con = new ContactsInterface();

        ArrayList<String> numbers = con.getPhoneContactNumbers(ContactsActivity.this);
        for (int i=0; i<numbers.size();i++){
            jobject.put(numbers.get(i));
        }

        ArrayList<NameValuePair> args = new ArrayList<NameValuePair>();
        args.add(new BasicNameValuePair("numeri",jobject.toString()));

        jobject = server.sendJsonArray("http://www.lemonsim.com/mobile/numeri_lemonsim.php", args);


        return true;
    }

    @Override
    protected void onPostExecute(Boolean success){
            lemonSims = AppUtils.jsonArrayToListBoolean(jobject);
            lemon_result = lemonSims;
            AppUtils.saveBooleanArraySharedPreferences(ContactsActivity.LEMON_SHARED_PREF, lemonSims, ContactsActivity.this);
            ContactsActivity.this.setContents(source);
            diag.hide();
    }


}

   /**
    *  START CHAT
    * @param numbers
    * @param position
    * @param n_pos
    */
   protected void startChat(String[] numbers,int position, int n_pos){

        Intent intent = new Intent(this, SmsChat.class);
        intent.putExtra(SmsChat.MY_PHONE, my_number);
        intent.putExtra(SmsChat.NUMBER, numbers[n_pos]);
        intent.putExtra(SmsChat.NAME, names_result.get(position));
        intent.putExtra(SmsChat.IS_LEMONSIM, lemon_result.get(position));
       startActivity(intent);


   }


   class PopUpClickListener implements DialogInterface.OnClickListener{
       @Override
       public void onClick(DialogInterface dialog, int which) {

           startChat(numbers, ContactsActivity.this.popup_pos, which);
   }

   }



   @Override
   public void onClick(DialogInterface dialog, int which) {

           startChat(numbers, ContactsActivity.this.popup_pos, which);
   }



}

1 个答案:

答案 0 :(得分:1)

您必须对onclicklistener进行一些更改:

 listview.setOnItemClickListener(new OnItemClickListener(){

        @Override
        public void onItemClick(AdapterView<?> l, View v, final int position,
                long id) {
            ContactsInterface con = new ContactsInterface();

            numbers = con.getContactNumberByDisplayName(names_result.get(position), ContactsActivity.this);

            popup_pos = position;
AlertDialog.Builder builder = new AlertDialog.Builder(
            getApplicationContext());


            if (numbers.length >1)
            {

                builder.setTitle(R.string.phone_numbers);
                builder.setItems(numbers , new PopUpClickListener());

                AlertDialog dialog = builder.create();
                dialog.show();
            }else{
                startChat(numbers,position, 0);
            }


        }

    });