Принудительное закрытие при настройке onclick

Я создал кнопку и назначил ее 1, выполнив

remove.setId(0 + count);

Затем я попытался поместить эту кнопку в свой пакет onCreate, чтобы использовать его

Button remove = (Button)findViewById(1);

remove.setOnClickListener(new View.OnClickListener() {

 @Override
 public void onClick(View v) {
 // TODO Auto-generated method stub

 }
});

Когда я создаю кнопку remove в моем oncreate, она запускается, но как только я добавляю свой onclick-слушатель, я не получаю никаких ошибок, но когда я запускаю его, он заставляет закрывать

Журнал

12-12 13:42:06.172: D/AndroidRuntime(19502): Shutting down VM
12-12 13:42:06.172: W/dalvikvm(19502): threadid=1: thread exiting with uncaught exception (group=0x416bbd40)
12-12 13:42:06.178: E/AndroidRuntime(19502): FATAL EXCEPTION: main
12-12 13:42:06.178: E/AndroidRuntime(19502): Process: com.th3ramr0d.armytrooptotask, PID: 19502
12-12 13:42:06.178: E/AndroidRuntime(19502): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.th3ramr0d.armytrooptotask/com.th3ramr0d.armytrooptotask.MainActivity}: java.lang.NullPointerException
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.ActivityThread.access$800(ActivityThread.java:139)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.os.Handler.dispatchMessage(Handler.java:102)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.os.Looper.loop(Looper.java:136)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.ActivityThread.main(ActivityThread.java:5102)
12-12 13:42:06.178: E/AndroidRuntime(19502): at java.lang.reflect.Method.invokeNative(Native Method)
12-12 13:42:06.178: E/AndroidRuntime(19502): at java.lang.reflect.Method.invoke(Method.java:515)
12-12 13:42:06.178: E/AndroidRuntime(19502): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
12-12 13:42:06.178: E/AndroidRuntime(19502): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
12-12 13:42:06.178: E/AndroidRuntime(19502): at dalvik.system.NativeStart.main(Native Method)
12-12 13:42:06.178: E/AndroidRuntime(19502): Caused by: java.lang.NullPointerException
12-12 13:42:06.178: E/AndroidRuntime(19502): at com.th3ramr0d.armytrooptotask.MainActivity.onCreate(MainActivity.java:45)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.Activity.performCreate(Activity.java:5248)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2173)
12-12 13:42:06.178: E/AndroidRuntime(19502): ... 11 more

Вот мой полный файл

package com.th3ramr0d.armytrooptotask;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

public class MainActivity extends Activity {

public int count = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);

 Button addTroopBtn = (Button) findViewById(R.id.addTroop);

 addTroopBtn.setOnClickListener(new View.OnClickListener() {

 @Override
 public void onClick(View v) {
 // TODO Auto-generated method stub
 if(count <= 5)
 {
 inputName(v);
 }
 else
 {

 }
 }
 });

 Button remove = (Button)findViewById(1);

 remove.setOnClickListener(new View.OnClickListener() {

 @Override
 public void onClick(View v) {
 // TODO Auto-generated method stub

 }
 });
}

public void inputName(final View v){
 AlertDialog.Builder alert = new AlertDialog.Builder(this);

 //alert.setTitle("Enter Name and Rank");
 alert.setMessage("Please Enter A Name");

 // Set an EditText view to get user input 
 final EditText input = new EditText(this);
 alert.setView(input);

 alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
 public void onClick(DialogInterface dialog, int whichButton) {
 Editable name = input.getText();
 addTroop(name);
 }
 });

 alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
 public void onClick(DialogInterface dialog, int whichButton) {
 // Canceled.
 }
 });

 alert.show();
}

public void addTroop(Editable name){

 LinearLayout mainPage = (LinearLayout) findViewById(R.id.manageTroopsMain);

 if (count <= 5)
 {
 //CREATE NEW LINEAR LAYOUT
 LinearLayout addTroopLayout = new LinearLayout(this); 

 //CREATE LAYOUT PARAMS FOR LAYOUT
 LinearLayout.LayoutParams newLayout = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
 newLayout.bottomMargin = 10;

 //STYLE NEW LINEAR LAYOUT
 addTroopLayout.setTag("addTroopLayout" + count);
 addTroopLayout.setLayoutParams(newLayout);
 addTroopLayout.setOrientation(LinearLayout.HORIZONTAL); 

 //CREATE NEW BUTTONS
 Button newTroop = new Button(this);
 Button remove = new Button(this);
 Button change = new Button(this);

 //CREATE LAYOUT PARAMS FOR BUTTONS
 LinearLayout.LayoutParams newTroopParam = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 20f);
 LinearLayout.LayoutParams rmvBtnParam = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, .5f);
 LinearLayout.LayoutParams chngNameParam = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, .5f);


 //STYLE NEW BUTTONS
 newTroop.setText(name);
 newTroop.setGravity(Gravity.LEFT|Gravity.CENTER_VERTICAL);
 newTroop.setLayoutParams(newTroopParam);
 remove.setId(0 + count);
 remove.setText("-");
 remove.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
 remove.setLayoutParams(rmvBtnParam);
 change.setText("...");
 change.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
 change.setLayoutParams(chngNameParam);

 //ADD VIEWS TO NEW LAYOUT
 addTroopLayout.addView(newTroop);
 addTroopLayout.addView(remove);
 addTroopLayout.addView(change);

 //ADD NEW LAYOUT TO mainPage LAYOUT
 mainPage.addView(addTroopLayout);

 //Increment Counter
 count++;
 }
}

}
2 ответа

Это ваша проблема: Button remove = (Button) findViewById (1);

Это должно быть примерно так:

Button remove = (Button)findViewById(R.id.buttonRemove); // that should be a long int


Вероятно, авария происходит из этой строки:

Button remove = (Button)findViewById(1);

Вам нужно будет указать действительный идентификатор для Button в вашем раздутом макете. Значение 1 не имеет смысла.

licensed under cc by-sa 3.0 with attribution.