2017-02-10 3 views
2

приложение останавливается при запуске с этими ошибками кошки журнала, и я проверяю свой код много раз, не выясняя, что проблема Я думаю, что это может быть что-то, что я сделал неправильно в своем макете, но ничего плохого спасибо заранеедиалоговое окно предупреждения в android с onclicklistener

Моя ошибка LogCat является:

E/AndroidRuntime: FATAL EXCEPTION: main 
       Process: com.example.ahmed_samir.dialog, PID: 4229 
       java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ahmed_samir.dialog/com.example.ahmed_samir.dialog.MainActivity}: android.content.res.Resources$NotFoundException: File from xml type layout resource ID #0x1020009 
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325) 
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) 
        at android.app.ActivityThread.access$800(ActivityThread.java:151) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:135) 
        at android.app.ActivityThread.main(ActivityThread.java:5254) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at java.lang.reflect.Method.invoke(Method.java:372) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
       Caused by: android.content.res.Resources$NotFoundException: File from xml type layout resource ID #0x1020009 
        at android.content.res.Resources.loadXmlResourceParser(Resources.java:2696) 
        at android.content.res.Resources.loadXmlResourceParser(Resources.java:2651) 
        at android.content.res.Resources.getLayout(Resources.java:1082) 
        at android.view.LayoutInflater.inflate(LayoutInflater.java:412) 
        at com.android.internal.app.AlertController.setupView(AlertController.java:479) 
        at com.android.internal.app.AlertController.installContent(AlertController.java:236) 
        at android.app.AlertDialog.onCreate(AlertDialog.java:356) 
        at android.app.Dialog.dispatchOnCreate(Dialog.java:373) 
        at android.app.Dialog.show(Dialog.java:274) 
        at com.example.ahmed_samir.dialog.MainActivity.showDialog(MainActivity.java:65) 
        at com.example.ahmed_samir.dialog.MainActivity.onCreate(MainActivity.java:42) 
        at android.app.Activity.performCreate(Activity.java:5990) 
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106) 
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278) 
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)  
        at android.app.ActivityThread.access$800(ActivityThread.java:151)  
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)  
        at android.os.Handler.dispatchMessage(Handler.java:102)  
        at android.os.Looper.loop(Looper.java:135)  
        at android.app.ActivityThread.main(ActivityThread.java:5254)  
        at java.lang.reflect.Method.invoke(Native Method)  
        at java.lang.reflect.Method.invoke(Method.java:372)  
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)  
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)  
       Caused by: java.io.FileNotFoundException: 
        at android.content.res.AssetManager.openXmlAssetNative(Native Method) 
        at android.content.res.AssetManager.openXmlBlockAsset(AssetManager.java:485) 
        at android.content.res.Resources.loadXmlResourceParser(Resources.java:2678) 
        at android.content.res.Resources.loadXmlResourceParser(Resources.java:2651)  
        at android.content.res.Resources.getLayout(Resources.java:1082)  
        at android.view.LayoutInflater.inflate(LayoutInflater.java:412)  
        at com.android.internal.app.AlertController.setupView(AlertController.java:479)  
        at com.android.internal.app.AlertController.installContent(AlertController.java:236)  
        at android.app.AlertDialog.onCreate(AlertDialog.java:356)  
        at android.app.Dialog.dispatchOnCreate(Dialog.java:373)  
        at android.app.Dialog.show(Dialog.java:274)  
        at com.example.ahmed_samir.dialog.MainActivity.showDialog(MainActivity.java:65)  
        at com.example.ahmed_samir.dialog.MainActivity.onCreate(MainActivity.java:42)  
        at android.app.Activity.performCreate(Activity.java:5990)  
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)  
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)  
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)  
        at android.app.ActivityThread.access$800(ActivityThread.java:151)  
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)  
        at android.os.Handler.dispatchMessage(Handler.java:102)  
        at android.os.Looper.loop(Looper.java:135)  
        at android.app.ActivityThread.main(ActivityThread.java:5254)  
        at java.lang.reflect.Method.invoke(Native Method)  
        at java.lang.reflect.Method.invoke(Method.java:372)  
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)  
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)  

Мой обновленный код:

public class MainActivity extends Activity { 
//mobily 
private Button button; 

private AlertDialog myDialog; 

private TextView result; 

private SharedPreferences prefs; 
private String prefName = "report"; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    final EditText input = new EditText(this); 
    button = (Button) findViewById(R.id.button1); 
    result = (TextView) findViewById(R.id.tv); 

    button.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      showDialog(); 
     } 
    }); 

    showDialog(); 
} 

public void showDialog() { 
    if (myDialog == null) { 
     myDialog = new AlertDialog.Builder(this) 
       .setTitle("ID Number") 
       .setMessage("Please enter your ID") 
       .setView(input) 
       .setPositiveButton("OK", new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(DialogInterface dialog, int which) { 
         //your code 
        } 
       }) 
       .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
        @Override 
        public void onClick(DialogInterface dialog, int which) { 
         dialog.dismiss(); 
        } 
       }) 
       .create(); 
    } 
    myDialog.show(); 
} 

} 

ответ

1

после много исследований я нашел свой ответ, и я хотел бы поделиться своими знаниями и ей мой полный код с XML-файлы, надеюсь, что его полезно

public class NationalId extends Activity { 

final Context context = this; 
private Button button; 
private TextView result; 

public void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_national_id); 

    // components from main.xml 
    button = (Button) findViewById(R.id.button1); 
    result = (TextView) findViewById(R.id.tv1); 

    // add button listener 
    button.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View arg0) { 

      // get prompts.xml view 
      LayoutInflater li = LayoutInflater.from(context); 
      View promptsView = li.inflate(R.layout.prompts, null); 

      android.app.AlertDialog.Builder alertDialogBuilder = new android.app.AlertDialog.Builder(
        context); 

      // set prompts.xml to alertdialog builder 
      alertDialogBuilder.setView(promptsView); 

      final EditText userInput = (EditText) promptsView 
        .findViewById(R.id.editTextDialogUserInput); 

      // set dialog message 
      alertDialogBuilder 
        .setCancelable(false) 
        .setPositiveButton("OK", 
          new DialogInterface.OnClickListener() { 
           public void onClick(DialogInterface dialog,int id) { 
            // get user input and set it to result 
            // edit text 
            result.setText(userInput.getText()); 
           } 
          }) 
        .setNegativeButton("Cancel", 
          new DialogInterface.OnClickListener() { 
           public void onClick(DialogInterface dialog,int id) { 
            dialog.cancel(); 
           } 
          }); 

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

      // show it 
      alertDialog.show(); 

     } 
    }); 
} 
} 

мой основной файл XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
tools:context=".MainActivity" > 

<TextView 
    android:id="@+id/tv1" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:gravity="center" 
    android:layout_marginTop="47dp" 
    android:ems="10" 
    android:inputType="phone" 
    android:hint="yourid" 
    > 

    <requestFocus /> 
</TextView> 

<Button 
    android:id="@+id/button1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_below="@+id/tv1" 
    android:layout_centerHorizontal="true" 
    android:layout_marginTop="32dp" 
    android:text="Edit" 

    /> 

и, наконец, мой запрос xml макет

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@+id/layout_root" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:orientation="vertical" 
android:padding="10dp" > 

<TextView 
    android:id="@+id/textView1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="YOUR ID : " 
    android:textAppearance="?android:attr/textAppearanceLarge" /> 

<EditText 
    android:id="@+id/editTextDialogUserInput" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:inputType="phone" 
    > 

    <requestFocus /> 

</EditText> 

мои наилучшие пожелания ..

0

Как excep говорит, ваше предупреждение все еще привязано к представлению. Попробуйте отклонить диалог на положительной кнопке, а также отрицательный.

1

Вы получаете эту ошибку, потому что вы настраиваете свой EditText вход на другой номер Dialog, так как каждый раз, когда вы нажимаете кнопку, вы создаете новый Dialog, таким образом, ошибку.

В первый раз, когда ваш код запускается, ваш ввод задается как вид в диалоговом окне1, но когда вы вызываете его во второй раз, вы говорите, что EditText должен быть установлен как вид в диалоговом окне2, но у него уже есть родитель, который Dialog1.

Вместо этого установите глобальную переменную AlertDialog, затем создайте диалог, только если диалог еще не существует. Что-то вроде этого:

private AlertDialog myDialog; 

public void showDialog() { 
     if (myDialog == null) { 
      myDialog = new AlertDialog.Builder(this) 
        .setTitle("ID Number") 
        .setMessage("Please enter your ID") 
        .setView(input) 
        .setPositiveButton("OK", new DialogInterface.OnClickListener() { 
         @Override 
         public void onClick(DialogInterface dialog, int which) { 
          //your code 
         } 
        }) 
        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
         @Override 
         public void onClick(DialogInterface dialog, int which) { 
          dialog.dismiss(); 
         } 
        }) 
        .create(); 
     } 
     myDialog.show(); 
    } 

затем в вашем onClick звонка showDialog() метод вместо воссоздания в диалоговом окне каждый раз.

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

+0

еще я получил ошибку: java.lang.IllegalStateException: Не удалось выполнить метод деятельности –

+0

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

+0

Я уже обновил свой код, спасибо заранее. –