2017-02-17 1 views
1

Мой индикатор выполнения - это просто счетчик.Почему не работает работа с прядильщиками после закрытия диалогового окна предупреждения в Android?

Я показываю два варианта для пользователя, и когда пользователь нажимает параметр, я показываю диалог, чтобы пользователь его читал и понимал.

Это то, что я хочу. Когда они нажимают «положительно», он должен показывать счетчик и продолжать звонить на фоновом режиме. Когда они нажимают минус, он должен отключить опцию.

Вот код.

Этот radioGroup.setOnClickListener переходит в метод onCreateView фрагмента.

public class Choose_CountryFragment extends Fragment { 
     private RadioGroup radioGroup; 
     private TextView textView; 
     private String countryChosen = null; 
     ConnectionStatus connectionStatus = new ConnectionStatus(getContext()); 
     public Choose_CountryFragment() { 
     } 

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

      radioGroup = (RadioGroup) rootView.findViewById(R.id.country_choice_radio); 
     radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() 
       { 
        public void onCheckedChanged(RadioGroup group, int checkedId) { 
         switch(checkedId){ 
          case R.id.countryCanada: 
           // do operations specific to this selection 
           countryChosen = "Canada"; 
           Intent explicitServiceIntent = new Intent(getActivity(), Service.class); 
           explicitServiceIntent.putExtra("country", "Canada"); 
           getActivity().startService(explicitServiceIntent); 
           connectionStatus.showProgress(); 
           break; 
          case R.id.countryUSA: 
           countryChosen = "USA"; 
           Dialog dialog = onCreateDialog(savedInstanceState); 
           dialog.show(); 
           connectionStatus.showProgress(); 
           break; 
         } 
        } 
       }); 

     public Dialog onCreateDialog(final Bundle savedInstanceState) { 
      // Use the Builder class for convenient dialog construction 
      AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 
      Toast.makeText(getContext(), "Click Got it", Toast.LENGTH_LONG).show(); 
      builder.setMessage(R.string.SignUpWarningInfo) 
        .setPositiveButton(R.string.gotIt, new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int id) { 
          Intent explicitServiceIntentUSA = new Intent(getActivity(), Service.class); 
          explicitServiceIntentUSA.putExtra("country", countryChosen); 
          getActivity().startService(explicitServiceIntentUSA); 

         } 
        }) 
        .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int id) {       
          return; 
         } 
        }); 
      // Create the AlertDialog object and return it 
      return builder.create(); 
     } 
    } 
} 

ConnectionStatus.java

public class ConnectionStatus { 

    private Context _context; 

    private ProgressDialog progressDialog = null; 

    public ConnectionStatus(Context context) { 
     this._context = context; 
    } 
    public void showProgress(){ 
      progressDialog = new ProgressDialog(_context); 
      progressDialog.setCancelable(false); 
      progressDialog.setIndeterminate(true); 
      progressDialog.show(); 
     } 
} 

ошибка происходит, когда я нажимаю США. Ошибка я получаю

  java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference 
        at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:154) 
        at android.app.AlertDialog.<init>(AlertDialog.java:109) 
        at android.app.ProgressDialog.<init>(ProgressDialog.java:77) 
        at com.a2.a2.ConnectionStatus.showProgress(ConnectionStatus.java:66) 
        at com.a2.a2.signUp.Choose_CountryFragment$1.onCheckedChanged(Choose_CountryFragment.java:73) 
+0

после полного 'Choose_CountryFragment' кода –

+0

@kishorejethava Done. –

ответ

0

Context Ваше возвращение null

Изменить код в Choose_CountryFragment

public class Choose_CountryFragment extends Fragment { 
    ... 
    protected Context mContext; 
    private ConnectionStatus connectionStatus 
    ... 

    public Choose_CountryFragment() { 
    } 

     @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          final Bundle savedInstanceState) { 
     View rootView = inflater.inflate(R.layout.fragment_choose__country, container, false); 
     ... 
     connectionStatus = new ConnectionStatus(mContext);// initialize ConnectionStatus here 
     ... 
    } 

} 

Ov erride onAttach Внутри Choose_CountryFragment

@Override 
public void onAttach(Context context) { 
    super.onAttach(context); 
    mContext = context; 
} 
+0

Хорошо. Я пытаюсь понять здесь. Когда вы говорите: «Your' Context'returning «null» ConnectionStatus connectionStatus = new ConnectionStatus (getContext()); // Вы хотите сказать, что getContext() возвращает null –

+0

Кто передал контекст toAttach()? Я новичок. Извините за слишком много вопросов. –

+0

Вы должны изучить 'oops' для' Override' –

0

В Fragment, вы должны использовать:

ProgressDialog progressDialog = new ProgressDialog(getActivity); 

Из documentation, метод getActivity() возвращает Activity этот Fragment в настоящее время связан с ним.

Edit: В Activity класс, вы должны использовать как:

ProgressDialog progressDialog = new ProgressDialog(YourActivityClassName.this); 
+0

Вы имеете в виду внутри метода showProgress()? –

+0

Где вы упоминали этот метод в классе «Фрагмент» или «Активность»? –

+0

в Fragment.Почему не текущая работа? Не могли бы вы объяснить это? –

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