new AlertDialog.Builderを、methodに入れて、Activityから呼び出すことは、可能ですか?
また、AlertDialog専用のクラスを作るということを、以前に、人に教わったのですが、現在、私は、新しく作ったclassに、様々なAlertと、そのAlertのボタンが押された時の処理をまとめて、書いているのですが、分けたほうがいいでしょうか?
このような、下のような、クラスを作って、LocationActivityから呼び出しているのですが、このようにエラーがでます。
java
1ava.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference 2 at android.app.Activity.findViewById(Activity.java:2323) 3 at com.example.android.sample.new3.Alart.newSet(Alart.java:30) 4 at com.example.android.sample.new3.LocationActivity.onOptionsItemSelected(LocationActivity.java:250)
java
1 2public class Alart extends Activity { 3 4 5 public String username; 6 7 public String newSet(LayoutInflater inflater, final Context context) { 8 9//この下がエラーの出ている30行目です。 10 final View layout = inflater.inflate(R.layout.dialog_contact_us, (ViewGroup) findViewById(R.id.layout_root)); 11 AlertDialog.Builder builder = new AlertDialog.Builder(context); 12 builder.setView(layout); 13 14builder.setPositiveButton("新規登録", new DialogInterface.OnClickListener() { 15 public void onClick(DialogInterface dialog, int which) { 16//この中で、EditTextに入力されたusernameの処理をしています。 17 EditText getusername2 = (EditText) layout.findViewById(R.id.username); 18 String username = getusername2.getText().toString(); 19} 20}); 21 22 AlertDialog alertDialog = builder.create(); 23 alertDialog.setOnShowListener(new DialogInterface.OnShowListener() { 24 @Override 25 public void onShow(DialogInterface arg0) { 26 EditText getusername2 = (EditText) layout.findViewById(R.id.username); 27 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); 28 inputMethodManager.showSoftInput(getusername2, 0); 29 } 30 }); 31 alertDialog.show(); 32 33 return username; 34 35 } 36 37}
//そして、呼び出し元であるLocationActivityのコードです。戻り値を取得してるところでエラーが出ています。
java
1@Override 2 public boolean onOptionsItemSelected(MenuItem item) { 3 int id = item.getItemId(); 4 if (id == R.id.action_setlogin) { 5 LayoutInflater inflater = (LayoutInflater) this.getSystemService( 6 LAYOUT_INFLATER_SERVICE); 7 8 Alart alart=new Alart(); 9//この下がエラーの出ている250行目です。 10 username=alart.newSet(inflater,this); 11 spinnerItems = favorite.favorite(LocationActivity.this, username);//これでok 12 arrayadapter();//spinnerのlistの更新のためのmethod 13 } 14}
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/06/09 18:19
2017/06/09 20:38