2013-10-10 6 views
0

Я не могу показать Dialog, я пытаюсь вернуть нулевой указатель. Проблема, я думаю, это контекст, я попытался с этим, но получить тот же результат ... Еще одна возможность, я думаю, - открыть поток, а внутри Основной активности показать AlertDialog, это мой код:Alertdialog не может отображаться по getview

файл Sector1.java общественный класс сектор1 расширяет фрагмент {

private Button btnNew_order,btnAggiungi; 
    private Spinner spin_prodotto, spin_tipo; 
    private EditText EtQta; 
    ListView userList; 
    static UserCustomAdapter userAdapter; 
    ArrayList<User> userArray = new ArrayList<User>(); 


     @Override 
     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
      View rootView = inflater.inflate(R.layout.sector1, container, false); 

      userAdapter = new UserCustomAdapter(getActivity().getBaseContext(), R.layout.row, userArray); 
      userList = (ListView) rootView.findViewById(R.id.listView); 
      userList.setItemsCanFocus(false); 
      userAdapter.notifyDataSetChanged(); 
      userList.setAdapter(userAdapter); 

UserCustomAdapter.java

public class UserCustomAdapter extends ArrayAdapter<User> { 
    private static final int INVISIBLE = 4; 
    private static final int VISIBLE = 0; 
    Context context; 
    int layoutResourceId; 
    ArrayList<User> data = new ArrayList<User>(); 

    public UserCustomAdapter(Context context, int layoutResourceId, ArrayList<User> data) { 
        super(context, layoutResourceId, data); 
        this.layoutResourceId = layoutResourceId; 
        this.context = context; 
        this.data = data; 
      } 

     @Override 
     public View getView(int position, View convertView, ViewGroup parent) { 

      View row = convertView; 
      UserHolder holder = null; 

      System.out.println("@@@[email protected]@@"); 
      if (row == null) { 

       //LayoutInflater inflater = ((Activity) context).getLayoutInflater(); 
       LayoutInflater inflater = LayoutInflater.from(context); 
       row = inflater.inflate(layoutResourceId, parent, false); 
       holder = new UserHolder(); 
       holder.textName = (TextView) row.findViewById(R.id.tv_prodotto); 
       holder.textQta = (TextView) row.findViewById(R.id.tv_qta); 
       //holder.textLocation = (TextView) row.findViewById(R.id.textView3); 
       holder.btnEdit = (ImageButton) row.findViewById(R.id.button1); 
       holder.btnDelete = (ImageButton) row.findViewById(R.id.button2); 

      row.setTag(holder); 
      } else { 
      holder = (UserHolder) row.getTag(); 
      } 

      User user = data.get(position); 
      holder.Useritem = data.get(position); 
      holder.textName.setText(user.getName()); 
      holder.textQta.setText(user.getQta()); 
      //holder.textLocation.setText(user.getLocation()); 

      holder.btnDelete.setTag(holder.Useritem);// mi segno la posizione in modo da recuperarla poi in seguito!! 
      holder.btnEdit.setTag(holder.Useritem);// mi segno la posizione in modo da recuperarla poi in seguito!! 

      //rendo invisibili i pulsanti per la prima riga 
      if(position == 0){ 
       holder.btnDelete.setVisibility(INVISIBLE); 
       holder.btnEdit.setVisibility(INVISIBLE); 
      }else{ 
       holder.btnDelete.setVisibility(VISIBLE); 
       holder.btnEdit.setVisibility(VISIBLE); 
      } 
      holder.btnEdit.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 
      // TODO Auto-generated method stub 
      Log.i("Edit Button Clicked", "**********"); 
      showDialog(); 
      } 
      }); 

      holder.btnDelete.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       // TODO Auto-generated method stub 
       Log.i("Delete Button Clicked", "**********"); 
       Toast.makeText(context, "Delete item", 
        Toast.LENGTH_LONG).show(); 

       User itemToRemove = (User)v.getTag(); 
       Sector1.userAdapter.remove(itemToRemove); 
       Sector1.userAdapter.notifyDataSetChanged(); 
      } 
      }); 
      return row; 
    } 

    private void showDialog(){ 
      AlertDialog.Builder alertDialog = new AlertDialog.Builder(context); 
      AlertDialog dialog = alertDialog.create();  
      alertDialog.setTitle("Conformation"); 
      alertDialog.setMessage("Are you sure you want to do ???"); 
      alertDialog.setIcon(android.R.drawable.ic_dialog_alert); 
      alertDialog.show(); 
     } 

     static class UserHolder { 
      TextView textName; 
      TextView textQta; 
      //TextView textLocation; 
      ImageButton btnEdit; 
      ImageButton btnDelete; 
      User Useritem; 
     } 
    } 

NoticeDialogFragment.java

общественного класса NoticeDialogFragment расширяет DialogFragment {

/* The activity that creates an instance of this dialog fragment must 
* implement this interface in order to receive event callbacks. 
* Each method passes the DialogFragment in case the host needs to query it. */ 
public interface NoticeDialogListener { 
    public void onDialogPositiveClick(DialogFragment dialog); 
    public void onDialogNegativeClick(DialogFragment dialog); 
} 

// Use this instance of the interface to deliver action events 
NoticeDialogListener mListener; 

// Override the Fragment.onAttach() method to instantiate the NoticeDialogListener 
@Override 
public void onAttach(Activity activity) { 
    super.onAttach(activity); 
    // Verify that the host activity implements the callback interface 
    try { 
     // Instantiate the NoticeDialogListener so we can send events to the host 
     mListener = (NoticeDialogListener) activity; 
    } catch (ClassCastException e) { 
     // The activity doesn't implement the interface, throw exception 
     throw new ClassCastException(activity.toString() 
       + " must implement NoticeDialogListener"); 
    } 
} 

@Override 
public Dialog onCreateDialog(Bundle savedInstanceState) { 
    // Build the dialog and set up the button click handlers 
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 
    builder.setMessage("ciaoo") 
      .setPositiveButton("ok", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int id) { 
        // Send the positive button event back to the host activity 
        mListener.onDialogPositiveClick(NoticeDialogFragment.this); 
       } 
      }) 
      .setNegativeButton("cancel", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int id) { 
        // Send the negative button event back to the host activity 
        mListener.onDialogPositiveClick(NoticeDialogFragment.this); 
       } 
      }); 
    return builder.create(); 
} 

}

на MainActivity.java

public void showNoticeDialog() { 
      // Create an instance of the dialog fragment and show it 
      DialogFragment dialog = new NoticeDialogFragment(); 
      dialog.show(getSupportFragmentManager(), "NoticeDialogFragment"); 
     } 
// The dialog fragment receives a reference to this Activity through the 
    // Fragment.onAttach() callback, which it uses to call the following methods 
    // defined by the NoticeDialogFragment.NoticeDialogListener interface 
    @Override 
    public void onDialogPositiveClick(DialogFragment dialog) { 
     // User touched the dialog's positive button 
     Toast.makeText(this, "Positive button Clicked", 
      Toast.LENGTH_LONG).show(); 
    } 

    @Override 
    public void onDialogNegativeClick(DialogFragment dialog) { 
     // User touched the dialog's negative button 
     Toast.makeText(this, "Negative button Clicked", 
        Toast.LENGTH_LONG).show();   
    } 

I woul d хотел бы реализовать вторую версию Dialog по вызову showNoticeDialog(), если я вызываю эту функцию в MainActivity, все в порядке, но как вызывать эту функцию на моем getView выше?

это мой LOG для первого диалогового Metod:

10-10 19:41:49.206: D/MainActivity(9150): MainActivity.onCreate 
10-10 19:41:49.218: D/MainActivity(9150): MainActivity.onStart 
10-10 19:41:49.218: D/MainActivity(9150): MainActivity.onResume 
10-10 19:41:49.278: W/EGL_emulation(9150): eglSurfaceAttrib not implemented 
.... 
10-10 19:41:52.914: I/Edit Button Clicked(9150): ********** 
10-10 19:41:52.914: D/AndroidRuntime(9150): Shutting down VM 
10-10 19:41:52.918: W/dalvikvm(9150): threadid=1: thread exiting with uncaught exception (group=0xa622c288) 
10-10 19:41:52.918: E/AndroidRuntime(9150): FATAL EXCEPTION: main 
10-10 19:41:52.918: E/AndroidRuntime(9150): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application 
10-10 19:41:52.918: E/AndroidRuntime(9150):  at android.view.ViewRootImpl.setView(ViewRootImpl.java:589) 
10-10 19:41:52.918: E/AndroidRuntime(9150):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:326) 
10-10 19:41:52.918: E/AndroidRuntime(9150):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224) 
10-10 19:41:52.918: E/AndroidRuntime(9150):  at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149) 
10-10 19:41:52.918: E/AndroidRuntime(9150):  at android.app.Dialog.show(Dialog.java:277) 
10-10 19:41:52.918: E/AndroidRuntime(9150):  at android.app.AlertDialog$Builder.show(AlertDialog.java:932) 
10-10 19:41:52.918: E/AndroidRuntime(9150):  at com.bandweb.ordinifornitori.UserCustomAdapter.showDialog(UserCustomAdapter.java:148) 
10-10 19:41:52.918: E/AndroidRuntime(9150):  at com.bandweb.ordinifornitori.UserCustomAdapter.access$0(UserCustomAdapter.java:142) 
10-10 19:41:52.918: E/AndroidRuntime(9150):  at com.bandweb.ordinifornitori.UserCustomAdapter$1.onClick(UserCustomAdapter.java:121) 
10-10 19:41:52.918: E/AndroidRuntime(9150):  at android.view.View.performClick(View.java:4084) 
10-10 19:41:52.918: E/AndroidRuntime(9150):  at android.view.View$PerformClick.run(View.java:16966) 
10-10 19:41:52.918: E/AndroidRuntime(9150):  at android.os.Handler.handleCallback(Handler.java:615) 
10-10 19:41:52.918: E/AndroidRuntime(9150):  at android.os.Handler.dispatchMessage(Handler.java:92) 
10-10 19:41:52.918: E/AndroidRuntime(9150):  at android.os.Looper.loop(Looper.java:137) 
10-10 19:41:52.918: E/AndroidRuntime(9150):  at android.app.ActivityThread.main(ActivityThread.java:4745) 
10-10 19:41:52.918: E/AndroidRuntime(9150):  at java.lang.reflect.Method.invokeNative(Native Method) 
10-10 19:41:52.918: E/AndroidRuntime(9150):  at java.lang.reflect.Method.invoke(Method.java:511) 
10-10 19:41:52.918: E/AndroidRuntime(9150):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 
10-10 19:41:52.918: E/AndroidRuntime(9150):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
10-10 19:41:52.918: E/AndroidRuntime(9150):  at dalvik.system.NativeStart.main(Native Method) 
+1

какой контекст вы передаете в конструкторе? applicationContext? – Shubhank

+0

Прежде всего, вы должны быть более ясными о том, что вы пытаетесь сделать. Какую задачу вы хотите достичь, в каком контексте? В вашем описании вы упоминаете что-то о диалоге, но в коде вы показываете нам ArrayAdapter. Какой диалог вы хотите показать и почему? И как вы планируете использовать этот адаптер? Также покажите полный след журнала ошибок - может быть «вызвано» где-то внизу, что полезно. – trungdinhtrong

+0

Я обновил код –

ответ

1

Вы пытались отправить активность для использования его контекста?

С другой стороны, вы должны извлечь метод, как показано ниже.

private void showDialog(){ 
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(context); 
    AlertDialog dialog = alertDialog.create();  
    alertDialog.setTitle("Conformation"); 
    alertDialog.setMessage("Are you sure you want to do ???"); 
    alertDialog.setIcon(android.R.drawable.ic_dialog_alert); 
    alertDialog.show(); 
} 
+0

та же проблема исключения ... –

0

Вы должны заменить

alertDialog.setTitle("Conformation"); 
    alertDialog.setMessage("Are you sure you want to do ???"); 
    alertDialog.setIcon(android.R.drawable.ic_dialog_alert); 
    alertDialog.show(); 

с

dialog.setTitle("Conformation"); 
     dialog.setMessage("Are you sure you want to do ???"); 
     dialog.setIcon(android.R.drawable.ic_dialog_alert); 
     dialog.show(); 
5

Вы не показали alertdialog еще. Попробуйте это

AlertDialog dialog; 
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);  
    alertDialog.setTitle("Conformation"); 
    alertDialog.setMessage("Are you sure you want to do ???"); 
    alertDialog.setIcon(android.R.drawable.ic_dialog_alert); 
    dialog = alertDialog .create(); 
    dialog .show(); 

Вам просто нужно показать alertdialog, а не строитель. И здесь вы используете идеальный контекст, который инициализируется через ваш конструктор. happy programming ..

+0

та же проблема исключения ... –

+0

комментировать предложение sysyem.out.println(), затем скомпилировать его – Ranjit

+0

, а также изменить инициализацию layoutinflater, например, LayoutInflater inflater = (LayoutInflater) context.getSystemService (Context.LAYOUT_INFLATER_SERVICE); – Ranjit

Смежные вопросы