TextView cannot be cast to SeekBar - java

I am experiencing issues relating my textview to my seekbar, and have received the below message as such. I am under the premises that it was due for the following reasons: 1) Trying to store the seekbar values information recorded by the user into parse to be able to retrieve it later. Storing the EditText such as name, age, headline and radiobox such as gender works fine, but its when I include the seek that the application fails to run.
I have tried doing a project clean, and rewording ID with the "right prefix" such as sb for seekbar, and tv for textview.
Below is the logcat message:
update logcat posted below
Below is the activity code
public class ProfileCreation extends Activity {
private static final int RESULT_LOAD_IMAGE = 1;
FrameLayout layout;
Button save;
protected EditText mName;
protected EditText mAge;
protected EditText mHeadline;
protected ImageView mprofilePicture;
RadioButton male, female;
String gender;
RadioButton lmale, lfemale;
String lgender;
protected SeekBar seekBarMinimum;
protected SeekBar seekBarMaximum;
protected SeekBar seekBarDistance;
protected Button mConfirm;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_creation);
RelativeLayout v = (RelativeLayout) findViewById(R.id.main);
v.requestFocus();
Parse.initialize(this, "ID", "ID");
mName = (EditText)findViewById(R.id.etxtname);
mAge = (EditText)findViewById(R.id.etxtage);
mHeadline = (EditText)findViewById(R.id.etxtheadline);
mprofilePicture = (ImageView)findViewById(R.id.profilePicturePreview);
male = (RadioButton)findViewById(R.id.rimale);
female = (RadioButton)findViewById(R.id.rifemale);
lmale = (RadioButton)findViewById(R.id.rlmale);
lfemale = (RadioButton)findViewById(R.id.rlfemale);
seekBarMinimum = (SeekBar) findViewById(R.id.sbseekBarMinimumAge);
seekBarMaximum = (SeekBar) findViewById(R.id.sbseekBarMaximumAge);
seekBarDistance = (SeekBar) findViewById(R.id.tvseekBarDistanceValue);
mConfirm = (Button)findViewById(R.id.btnConfirm);
mConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = mName.getText().toString();
String age = mAge.getText().toString();
String headline = mHeadline.getText().toString();
age = age.trim();
name = name.trim();
headline = headline.trim();
if (age.isEmpty() || name.isEmpty() || headline.isEmpty()) {
AlertDialog.Builder builder = new AlertDialog.Builder(ProfileCreation.this);
builder.setMessage(R.string.signup_error_message)
.setTitle(R.string.signup_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
else {
// create the new user!
setProgressBarIndeterminateVisibility(true);
ParseUser currentUser = ParseUser.getCurrentUser();
seekBarMaximum.getProgress();
seekBarMinimum.getProgress();
seekBarDistance.getProgress();
if(male.isChecked())
gender = "Male";
else
gender = "Female";
if(lmale.isChecked())
lgender = "Male";
else
lgender = "Female";
currentUser.put("Name", name);
currentUser.put("Age", age);
currentUser.put("Headline", headline);
currentUser.put("Gender", gender);
currentUser.put("Looking_Gender", lgender);
currentUser.put("Minimum_Age", seekBarMinimum);
currentUser.put("Maximum_Age", seekBarMaximum);
currentUser.put("Maximum_Distance_Age", seekBarDistance);
currentUser.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
setProgressBarIndeterminateVisibility(false);
if (e == null) {
// Success!
Intent intent = new Intent(ProfileCreation.this, MoodActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(ProfileCreation.this);
builder.setMessage(e.getMessage())
.setTitle(R.string.signup_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
}
});
SeekBar seekBar = (SeekBar) findViewById(R.id.sbseekBarDistance);
final TextView seekBarValue = (TextView) findViewById(R.id.tvseekBarDistanceValue);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
seekBarValue.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}); // Add this
Button mcancel = (Button)findViewById(R.id.btnBack);
mcancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ProfileCreation.this.startActivity(new Intent(ProfileCreation.this, LoginActivity.class));
}
});
SeekBar seekBarMinimum = (SeekBar) findViewById(R.id.sbseekBarMinimumAge);
final TextView txtMinimum = (TextView) findViewById(R.id.tvMinAge);
seekBarMinimum.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
txtMinimum.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}); // Add this
SeekBar seekBarMaximum = (SeekBar) findViewById(R.id.sbseekBarMaximumAge);
final TextView txtMaximum = (TextView) findViewById(R.id.tvMaxAge);
seekBarMaximum.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
txtMaximum.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}); // Add this
Button buttonLoadImage = (Button) findViewById(R.id.btnPictureSelect);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.profilePicturePreview);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
private byte[] readInFile(String path) throws IOException {
// TODO Auto-generated method stub
byte[] data = null;
File file = new File(path);
InputStream input_stream = new BufferedInputStream(new FileInputStream(
file));
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
data = new byte[16384]; // 16K
int bytes_read;
while ((bytes_read = input_stream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, bytes_read);
}
input_stream.close();
return buffer.toByteArray();
}
}
Below is the layout xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/scrollProfile"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/dark_texture_blue" >
<RelativeLayout
android:id="#+id/main"
android:layout_width="match_parent"
android:layout_height="797dp"
android:gravity="center"
android:orientation="vertical" >
<ImageView
android:id="#+id/profilePicturePreview"
android:layout_width="132dp"
android:layout_height="120dp"
android:layout_below="#+id/textView5"
android:layout_centerHorizontal="true"
android:layout_marginTop="7dp"
android:layout_marginBottom="9dp"
android:padding="3dp"
android:scaleType="centerCrop"
android:cropToPadding="true"
android:background="#drawable/border_image"
android:alpha="1" />
<Button
android:id="#+id/bRemove"
android:layout_width="120dp"
android:layout_height="60dp"
android:layout_above="#+id/etxtage"
android:layout_alignLeft="#+id/etxtname"
android:alpha="0.8"
android:background="#330099"
android:text="Upload from Facebook"
android:textColor="#ffffff"
android:textSize="17sp"
android:textStyle="bold" />
<Button
android:id="#+id/btnPictureSelect"
android:layout_width="118dp"
android:layout_height="60dp"
android:layout_alignRight="#+id/etxtname"
android:layout_below="#+id/profilePicturePreview"
android:layout_marginRight="8dp"
android:alpha="0.8"
android:background="#000000"
android:onClick="pickPhoto"
android:text="Select photo from gallery"
android:textColor="#ffffff"
android:textSize="17sp"
android:textStyle="bold" />
<TextView
android:id="#+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView4"
android:layout_centerHorizontal="true"
android:layout_marginTop="9dp"
android:text="Preferred Name"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#ADD8E6"
android:textSize="20sp"
android:textStyle="bold"
android:typeface="serif" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="39dp"
android:gravity="center"
android:text="Profile Creation"
android:textColor="#ffffff"
android:textSize="28sp"
android:textStyle="bold"
android:typeface="serif" />
<EditText
android:id="#+id/etxtname"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_below="#+id/textView6"
android:layout_centerHorizontal="true"
android:ems="10"
android:enabled="true"
android:hint="Please type your name here"
android:inputType="textPersonName"
android:textColor="#ffffff"
android:textSize="18sp" />
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/etxtname"
android:layout_centerHorizontal="true"
android:layout_marginTop="8dp"
android:text="Upload your Profile Picture"
android:textColor="#f2f2f2"
android:textSize="18sp"
android:textStyle="bold"
android:typeface="sans" />
<RadioGroup
android:id="#+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_alignLeft="#+id/etxtheadline"
android:layout_height="wrap_content"
android:layout_below="#+id/texperience"
android:layout_toLeftOf="#+id/textView3" >
<RadioButton
android:id="#+id/rimale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Male"
android:textColor="#f2f2f2" />
<RadioButton
android:id="#+id/rifemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:textColor="#f2f2f2" />
</RadioGroup>
<SeekBar
android:id="#+id/sbseekBarDistance"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_below="#+id/textView12"
android:layout_centerHorizontal="true"
android:layout_marginTop="11dp"
android:progress="50" />
<RadioGroup
android:id="#+id/radioGroup3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView4"
android:layout_alignTop="#+id/radioGroup2"
android:layout_marginTop="10dp" >
</RadioGroup>
<RadioGroup
android:id="#+id/radioGroup2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/etxtheadline"
android:layout_below="#+id/textView2" >
<RadioButton
android:id="#+id/rlmale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Male"
android:textColor="#f2f2f2" />
<RadioButton
android:id="#+id/rlfemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:textColor="#f2f2f2" />
</RadioGroup>
<SeekBar
android:id="#+id/sbseekBarMinimumAge"
android:layout_width="220dp"
android:layout_height="wrap_content"
android:layout_below="#+id/textView7"
android:layout_centerHorizontal="true"
android:layout_marginTop="11dp"
android:progress="25" />
<TextView
android:id="#+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/etxtage"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="Minimum Age Looking For"
android:textColor="#f2f2f2"
android:textSize="16sp"
android:textStyle="bold"
android:typeface="serif" />
<TextView
android:id="#+id/tvseekBarDistanceValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/tvMinAge"
android:layout_below="#+id/sbseekBarDistance"
android:text="50"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#f2f2f2"
android:textSize="20sp"
android:textStyle="bold"
android:typeface="serif" />
<TextView
android:id="#+id/textView12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/radioGroup1"
android:layout_centerHorizontal="true"
android:layout_marginTop="19dp"
android:text="Search Distance "
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#ADD8E6"
android:textSize="20sp"
android:textStyle="bold"
android:typeface="serif" />
<TextView
android:id="#+id/tvMinAge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/sbseekBarMinimumAge"
android:layout_centerHorizontal="true"
android:text="25"
android:textColor="#f2f2f2"
android:textSize="18sp" />
<TextView
android:id="#+id/textView8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvMaxAge"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:text="Headline"
android:textColor="#ADD8E6"
android:textSize="20sp"
android:textStyle="bold"
android:typeface="serif" />
<TextView
android:id="#+id/textView14"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvMinAge"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:text="Maximum Age Looking For"
android:textColor="#f2f2f2"
android:textSize="16sp"
android:textStyle="bold"
android:typeface="serif" />
<SeekBar
android:id="#+id/sbseekBarMaximumAge"
android:layout_width="221dp"
android:layout_height="wrap_content"
android:layout_below="#+id/textView14"
android:layout_centerHorizontal="true"
android:layout_marginTop="11dp"
android:progress="50" />
<TextView
android:id="#+id/tvMaxAge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/sbseekBarMaximumAge"
android:layout_centerHorizontal="true"
android:text="50"
android:textColor="#f2f2f2"
android:textSize="18sp" />
<TextView
android:id="#+id/conditions"
android:layout_width="280dp"
android:layout_height="130dp"
android:layout_below="#+id/btnConfirm"
android:layout_centerHorizontal="true"
android:layout_marginBottom="7dp"
android:layout_marginTop="7dp"
android:alpha="0.6"
android:gravity="center"
android:text="#string/disclaimer"
android:textColor="#99CCFF"
android:textSize="12sp" />
<Button
android:id="#+id/btnConfirm"
android:layout_width="120dp"
android:layout_height="60dp"
android:layout_below="#+id/tvseekBarDistanceValue"
android:layout_marginBottom="7dp"
android:layout_marginTop="14dp"
android:layout_toRightOf="#+id/tvseekBarDistanceValue"
android:alpha="0.8"
android:background="#151B54"
android:text="Confirm"
android:textColor="#ffffff"
android:textSize="17sp"
android:textStyle="bold" />
<EditText
android:id="#+id/etxtheadline"
android:layout_width="270dp"
android:layout_height="70dp"
android:layout_below="#+id/textView8"
android:layout_centerHorizontal="true"
android:hint="A quick description of yourself"
android:singleLine="true"
android:textAlignment="center"
android:textColor="#f2f2f2"
android:textSize="18dp" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/etxtage"
android:layout_width="230dp"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView4"
android:layout_below="#+id/btnPictureSelect"
android:layout_marginTop="48dp"
android:ems="10"
android:hint="Please type your age here"
android:inputType="number"
android:maxLength="2"
android:textAlignment="center"
android:textColor="#f2f2f2"
android:textSize="18dp" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/radioGroup1"
android:layout_alignRight="#+id/btnConfirm"
android:text="Looking for"
android:textColor="#ADD8E6"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/texperience"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/radioGroup1"
android:layout_below="#+id/etxtheadline"
android:layout_marginTop="39dp"
android:text="I am a"
android:textColor="#ADD8E6"
android:textSize="20sp"
android:textStyle="bold" />
/>
</RelativeLayout>
</ScrollView>
Any help would be greatly appreciated. All the best.
Update
Upon resolving the previous, another error related was triggered. I have tried resolving it, but is still experiencing issues. Below is the logcat
08-13 14:56:24.366: E/AndroidRuntime(1306): FATAL EXCEPTION: main
08-13 15:49:13.758: E/AndroidRuntime(1365): FATAL EXCEPTION: main
08-13 15:49:13.758: E/AndroidRuntime(1365): Process: com.dooba.beta, PID: 1365
08-13 15:49:13.758: E/AndroidRuntime(1365): java.lang.IllegalArgumentException: invalid type for value: class android.widget.SeekBar
08-13 15:49:13.758: E/AndroidRuntime(1365): at com.parse.ParseObject.put(ParseObject.java:2152)
08-13 15:49:13.758: E/AndroidRuntime(1365): at com.parse.ParseUser.put(ParseUser.java:315)
08-13 15:49:13.758: E/AndroidRuntime(1365): at com.dooba.beta.ProfileCreation$1.onClick(ProfileCreation.java:136)
08-13 15:49:13.758: E/AndroidRuntime(1365): at android.view.View.performClick(View.java:4438)
08-13 15:49:13.758: E/AndroidRuntime(1365): at android.view.View$PerformClick.run(View.java:18422)
08-13 15:49:13.758: E/AndroidRuntime(1365): at android.os.Handler.handleCallback(Handler.java:733)
08-13 15:49:13.758: E/AndroidRuntime(1365): at android.os.Handler.dispatchMessage(Handler.java:95)
08-13 15:49:13.758: E/AndroidRuntime(1365): at android.os.Looper.loop(Looper.java:136)
08-13 15:49:13.758: E/AndroidRuntime(1365): at android.app.ActivityThread.main(ActivityThread.java:5017)
08-13 15:49:13.758: E/AndroidRuntime(1365): at java.lang.reflect.Method.invokeNative(Native Method)
08-13 15:49:13.758: E/AndroidRuntime(1365): at java.lang.reflect.Method.invoke(Method.java:515)
08-13 15:49:13.758: E/AndroidRuntime(1365): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-13 15:49:13.758: E/AndroidRuntime(1365): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-13 15:49:13.758: E/AndroidRuntime(1365): at dalvik.system.NativeStart.main(Native Method)

Your XML has defined tvseekBarDistanceValue as a TextView, not a SeekBar. Since you're trying to change a TextView to a SeekBar (which is impossible), you are getting this error.
Based on your XML, I think you want to replace
seekBarDistance = (SeekBar) findViewById(R.id.tvseekBarDistanceValue);
with
seekBarDistance = (SeekBar) findViewById(R.id.sbseekBarDistance);

Related

Attempt to invoke virtual method .(context menu)... on a null object reference

Hello people Im always getting this error in debugger and the app will not start. If I am deleting the contextmenu it is working...
public class MainActivity extends AppCompatActivity {
public int[] buttonArray = {R.id.button1, R.id.button2, R.id.button3}; // Button Array
public int[] soundsArray = {R.raw.sound1, R.raw.sound2, R.raw.sound3}; // Sound Array
private int[] tabIcons = {
R.drawable.infoicon,
R.drawable.soundicon,
R.drawable.startop
};
int counters=1;
int counter=1;
final int REQ_CODE_EXTERNAL_STORAGE_PERMISSION = 45;
public String ordnerpfad = Environment.getExternalStorageDirectory() + "/Sounds";
public String soundpfad = ordnerpfad + "/sound.mp3";
public File ordnerfile = new File(ordnerpfad);
public File soundfile = new File(soundpfad);
public Uri urisound = Uri.parse(soundpfad);
public byte[] byte1 = new byte [1024];
public int zwischenspeicher = 0;
public InputStream is1;
public FileOutputStream fos;
public Intent teilintent;
InterstitialAd mInterstitialAd;
TabLayout tabLayout;
ViewPager viewPager;
MediaPlayer MainMMP;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
public void run() {
requestNewInterstitial();
}
}, 14000);
MobileAds.initialize(getApplicationContext(), "xxxxxxxxxxxxxxx");
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest request = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR) // All emulators
.addTestDevice("2BB7955A07F972AC2D1DA7617768CE01")
.build();
mAdView.loadAd(request);
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("xxxxxxxxxxxxxx");
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
mInterstitialAd.show();
}
});
for (int i = 0; i < buttonArray.length; i++) {
Button contextMenuButton = (Button) findViewById(buttonArray[i]);
registerForContextMenu(contextMenuButton);
}
MainMMP = MediaPlayer.create(this, R.raw.sound1);
viewPager = (ViewPager) findViewById(R.id.viewPager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
setupTabIcons();
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
});
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Close this App?\n\nWe are happy for each Feedback :) ")
.setCancelable(false)
.setNeutralButton("Rate Us", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int rate){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse("http...xxxx..xxx"));
startActivity(intent);
}
})
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainMMP.release();
finish();
System.exit(0);
}
})
.setNegativeButton("No", null)
.show();
}
private void requestNewInterstitial() {
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR) // All emulators
.addTestDevice("2BB7955A07F972AC2D1DA7617768CE01")
.build();
mInterstitialAd.loadAd(adRequest);
}
public void Share(View view){
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "Hey, check this Soundboard");
sendIntent.setType("text/plain");
startActivity(sendIntent);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, view, menuInfo);
menu.setHeaderTitle("Context Menu");
menu.add(0, view.getId(), 0, "Action 1");
menu.add(0, view.getId(), 0, "Action 2");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if(item.getTitle().equals("Action 1")){function1(item.getItemId());}
else if(item.getTitle().equals("Action 2")){function2(item.getItemId());}
else {return false;}
return true;
}
public void function1(int id){
for (int i=0; i<buttonArray.length; i++) {
if (id == buttonArray[i]) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
if (!ordnerfile.exists()) {
try {
ordnerfile.mkdir();
Toast.makeText(getApplicationContext(), "Created Folder", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_SHORT).show();
}
}
try {
is1 = getResources().openRawResource(soundsArray[i]);
fos = new FileOutputStream(soundfile);
while ((zwischenspeicher = is1.read(byte1)) > 0) {
fos.write(byte1, 0, zwischenspeicher);
}
is1.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_SHORT).show();
}
teilintent = new Intent(Intent.ACTION_SEND);
teilintent.setType("audio/*");
teilintent.putExtra(Intent.EXTRA_STREAM, urisound);
startActivity(Intent.createChooser(teilintent, "Share this Sound..."));
}
else {
ActivityCompat.requestPermissions(MainActivity.this,new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQ_CODE_EXTERNAL_STORAGE_PERMISSION);
}
return;
}
}
}
public void function2(int id){
Toast.makeText(this, "function 2 called", Toast.LENGTH_SHORT).show();}
public void MainMMP(View view) {
for (int i=0; i<buttonArray.length; i++) {
if (view.getId() == buttonArray[i]) {
MainMMP.release();
MainMMP = MediaPlayer.create(MainActivity.this, soundsArray[i]);
MainMMP.start();
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQ_CODE_EXTERNAL_STORAGE_PERMISSION && grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
ordnerfile.mkdir();
Toast.makeText(getApplicationContext(), "Ordner erstellt", Toast.LENGTH_SHORT).show();
}
}
private void setupTabIcons() {
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[2]);
tabLayout.getTabAt(2).setIcon(tabIcons[1]);
tabLayout.getTabAt(3).setIcon(tabIcons[1]);
tabLayout.getTabAt(4).setIcon(tabIcons[1]);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new FragmentFavourite(), "");
adapter.addFrag(new Fragment1(), "Top Sounds");
adapter.addFrag(new Fragment2(), "Sounds 1");
adapter.addFrag(new Fragment3(), "Sounds 2");
adapter.addFrag(new Fragment4(), "Sounds 3");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
private ViewPagerAdapter(FragmentManager manager) {
super(manager);}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
private void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
}
Now my tab1.xml
Actual there are more buttons but just for some tests I do it with the first 3
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_vertical|center_horizontal|center"
android:layout_margin="15dp"
android:minHeight="90dp">
<Button
android:id="#+id/button1"
android:onClick="MainMMP"
android:text="Fun Fun\nFun"
style="?android:attr/borderlessButtonStyle"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:layout_height="wrap_content"
android:background="#drawable/mybutton"
android:layout_marginEnd="15dp"
android:layout_marginRight="15dp"
android:layout_weight="1" />
<Button
android:id="#+id/button2"
android:onClick="MainMMP"
android:text="Sing, Dance,\nPretend"
style="?android:attr/borderlessButtonStyle"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:layout_height="wrap_content"
android:background="#drawable/mybutton"
android:layout_weight="1"
android:layout_marginStart="15dp"
android:layout_marginLeft="15dp" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="15dp"
android:layout_gravity="center_vertical|center_horizontal|center">
<Button
android:id="#+id/button3"
android:onClick="MainMMP"
android:text="Kazoo\nSound1"
style="?android:attr/borderlessButtonStyle"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:layout_height="wrap_content"
android:background="#drawable/mybutton"
android:layout_weight="1"
android:layout_marginEnd="15dp"
android:layout_marginRight="15dp" />
<Button
android:id="#+id/button4"
android:onClick="MainMMP"
android:text="Kaaaa-\nzooo"
style="?android:attr/borderlessButtonStyle"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:layout_height="wrap_content"
android:background="#drawable/mybutton"
android:layout_weight="1"
android:layout_marginStart="15dp"
android:layout_marginLeft="15dp"/>
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="15dp"
android:layout_gravity="center_vertical|center_horizontal|center">
<Button
android:id="#+id/button5"
android:onClick="MainMMP"
android:text="Kazoo\nSound2"
style="?android:attr/borderlessButtonStyle"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:layout_height="wrap_content"
android:background="#drawable/mybutton"
android:layout_weight="1"
android:layout_marginEnd="15dp"
android:layout_marginRight="15dp"/>
<Button
android:id="#+id/button6"
android:onClick="MainMMP"
android:text="Just Kazoo\nit"
style="?android:attr/borderlessButtonStyle"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:layout_height="wrap_content"
android:background="#drawable/mybutton"
android:layout_weight="1"
android:layout_marginStart="15dp"
android:layout_marginLeft="15dp"/>
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="15dp"
android:layout_gravity="center_vertical|center_horizontal|center">
<Button
android:id="#+id/button7"
android:onClick="MainMMP"
android:text="Special-\nfriends"
style="?android:attr/borderlessButtonStyle"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:layout_height="wrap_content"
android:background="#drawable/mybutton"
android:layout_weight="1"
android:layout_marginEnd="15dp"
android:layout_marginRight="15dp"/>
<Button
android:id="#+id/button8"
android:onClick="MainMMP"
android:text="I just \n wanna say"
style="?android:attr/borderlessButtonStyle"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:layout_height="wrap_content"
android:background="#drawable/mybutton"
android:layout_weight="1"
android:layout_marginStart="15dp"
android:layout_marginLeft="15dp"/>
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="15dp"
android:layout_gravity="center_vertical|center_horizontal|center">
<Button
android:id="#+id/button9"
android:onClick="MainMMP"
android:text="Before I\n met you"
style="?android:attr/borderlessButtonStyle"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:layout_height="wrap_content"
android:background="#drawable/mybutton"
android:layout_weight="1"
android:layout_marginEnd="15dp"
android:layout_marginRight="15dp"/>
<Button
android:id="#+id/button10"
android:onClick="MainMMP"
android:text="Right\n by my side"
style="?android:attr/borderlessButtonStyle"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:layout_height="wrap_content"
android:background="#drawable/mybutton"
android:layout_weight="1"
android:layout_marginStart="15dp"
android:layout_marginLeft="15dp"/>
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="15dp"
android:layout_gravity="center_vertical|center_horizontal|center">
<Button
android:id="#+id/button11"
android:onClick="MainMMP"
android:text="Sing a Song\n for you"
style="?android:attr/borderlessButtonStyle"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:layout_height="wrap_content"
android:background="#drawable/mybutton"
android:layout_weight="1"
android:layout_marginEnd="15dp"
android:layout_marginRight="15dp"/>
<Button
android:id="#+id/button12"
android:onClick="MainMMP"
android:text="Your my\n Friend"
style="?android:attr/borderlessButtonStyle"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:layout_height="wrap_content"
android:background="#drawable/mybutton"
android:layout_weight="1"
android:layout_marginStart="15dp"
android:layout_marginLeft="15dp"/>
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="15dp"
android:layout_gravity="center_vertical|center_horizontal|center">
<Button
android:id="#+id/button13"
android:onClick="MainMMP"
android:text="I was \n alone"
style="?android:attr/borderlessButtonStyle"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:layout_height="wrap_content"
android:background="#drawable/mybutton"
android:layout_weight="1"
android:layout_marginEnd="15dp"
android:layout_marginRight="15dp"/>
<Button
android:id="#+id/button14"
style="?android:attr/borderlessButtonStyle"
android:onClick="MainMMP"
android:text="Looking\n for a friend"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:layout_height="wrap_content"
android:background="#drawable/mybutton"
android:layout_weight="1"
android:layout_marginStart="15dp"
android:layout_marginLeft="15dp"/>
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="15dp"
android:layout_gravity="center_vertical|center_horizontal|center">
<Button
android:id="#+id/button15"
android:onClick="MainMMP"
style="?android:attr/borderlessButtonStyle"
android:text="Speeeecial-\nfrieeeend"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:layout_height="wrap_content"
android:background="#drawable/mybutton"
android:layout_weight="1"
android:layout_marginEnd="15dp"
android:layout_marginRight="15dp"/>
</TableRow>
</TableLayout>
</ScrollView>
E/AndroidRuntime: FATAL EXCEPTION: main Process: com.apsps.someappsa..Soundboard, PID: 10970 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.apsps.someappsa.Soundboard/com.apsps.someappsa.Soundboard.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnCreateContextMenuListener(android.view.View$OnCreateContextMenuListener)' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) at android.app.ActivityThread.-wrap11(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnCreateContextMenuListener(android.view.View$OnCreateContextMenuListener)' on a null object reference at android.app.Activity.registerForContextMenu(Activity.java:3227) at com.apsps.someappsa.Soundboard.MainActivity.onCreate(MainActivity.java:86) at android.app.Activity.performCreate(Activity.java:6237) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) at android.app.ActivityThread.-wrap11(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Your code for pointing to the button by calling findViewById is throwing a null point exception.
Button contextMenuButton = (Button) findViewById(buttanArray[i]);
registerForContextMenu(contextMenuButton);
Make sure that your buttonArray[i] has got the correct ID of the button and there exist a button in your xml file with that ID.

Android: app crashing after adding a method to MainActvity

I am working on an app to time and score basketball games, when I added the countdown part and a button to control the count to the MainActivity.java file, the app builds fine but crashes every time. Here are codes I used.
Here is the error generated every time i try to launch the app
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.abdulkarim.courtcounter, PID: 19740
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.abdulkarim.courtcounter/com.example.abdulkarim.courtcounter.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2306)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471)
at android.app.ActivityThread.access$900(ActivityThread.java:175)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5603)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:116)
at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:147)
at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:27)
at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:50)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:201)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:181)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:521)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:190)
at com.example.abdulkarim.courtcounter.MainActivity.<init>(MainActivity.java:14)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2297)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471) 
at android.app.ActivityThread.access$900(ActivityThread.java:175) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:146) 
at android.app.ActivityThread.main(ActivityThread.java:5603) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099) 
at dalvik.system.NativeStart.main(Native Method)
MainActivity.java
package com.example.abdulkarim.courtcounter;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int scoreTeamA = 0, scoreTeamB = 0;
TextView minutes = (TextView) findViewById(R.id.min_counter);
TextView seconds = (TextView) findViewById(R.id.sec_counter);
long milliLeft, min, sec;
CountDownTimer gameTime;
final Button timeoutButton = (Button) findViewById(R.id.timeout_button);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* This method is called when the +3 points button is clicked
*/
public void threePointsA(View view){
scoreTeamA = scoreTeamA + 3;
displayScoreA(scoreTeamA);
}
/**
* This method is called when the +2 points button is clicked
*/
public void twoPointsA(View view){
scoreTeamA = scoreTeamA + 2;
displayScoreA(scoreTeamA);
}
/**
* This method is called when the Free Throw button is clicked
*/
public void freeThrowA(View view){
scoreTeamA = scoreTeamA + 1;
displayScoreA(scoreTeamA);
}
/**
* This method is called when the +3 points button is clicked
*/
public void threePointsB(View view){
scoreTeamB = scoreTeamB + 3;
displayScoreB(scoreTeamB);
}
/**
* This method is called when the +2 points button is clicked
*/
public void twoPointsB(View view){
scoreTeamB = scoreTeamB + 2;
displayScoreB(scoreTeamB);
}
/**
* This method is called when the Free Throw button is clicked
*/
public void freeThrowB(View view){
scoreTeamB = scoreTeamB + 1;
displayScoreB(scoreTeamB);
}
/**
* This method is called when the reset button is clicked
*/
public void reset(View view){
scoreTeamA = 0;
scoreTeamB = 0;
displayScoreA(scoreTeamA);
displayScoreB(scoreTeamB);
}
/**
* This method initializes the countdown timer
*/
public void gameTime(long timeLengthMilli) {
gameTime = new CountDownTimer(timeLengthMilli, 1000) {
#Override
public void onTick(long milliTillFinish) {
milliLeft = milliTillFinish;
min = (milliTillFinish / (1000 * 60));
sec = ((milliTillFinish / 1000) - min * 60);
minutes.setText(Long.toString(min));
seconds.setText(Long.toString(sec));
Log.i("Tick", "Tock");
}
public void onFinish() {
minutes.setText("00");
seconds.setText("00");
}
}.start();
}
public void timerPause() {
gameTime.cancel();
}
private void timerResume() {
Log.i("min", Long.toString(min));
Log.i("Sec", Long.toString(sec));
gameTime(milliLeft);
}
/**
*This method is called when the timeOut button is clicked
*/
public void timeOut(View view){
timeoutButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(timeoutButton.getText().equals("Start")){
Log.i("Started", timeoutButton.getText().toString());
timeoutButton.setText("Timeout");
gameTime(60*1000);
} else if (timeoutButton.getText().equals("Pause")){
Log.i("Timeout", timeoutButton.getText().toString());
timeoutButton.setText("Resume");
timerPause();
} else if (timeoutButton.getText().equals("Resume")){
timeoutButton.setText("Timeout");
timerResume();
}
}
});
}
/**
* This method handles the display of scores for team A
*/
private void displayScoreA(int score){
TextView scoreTextView = (TextView) findViewById(R.id.teamA_score_text_view);
scoreTextView.setText(String.valueOf(score));
}
/**
* This method handles the display of scores for team A
*/
private void displayScoreB(int score){
TextView scoreTextView = (TextView) findViewById(R.id.teamB_score_text_view);
scoreTextView.setText(String.valueOf(score));
}
}
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.abdulkarim.courtcounter.MainActivity">
<RelativeLayout
android:id="#+id/r1_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true">
<TextView
android:id="#+id/min_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="75dp"
android:paddingTop="16dp"
android:text="Mins"
android:textAllCaps="true"
android:textColor="#android:color/black"
android:textSize="10sp" />
<TextView
android:id="#+id/sec_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:paddingTop="16dp"
android:layout_toRightOf="#id/min_text_view"
android:text="Secs"
android:textAllCaps="true"
android:textColor="#android:color/black"
android:textSize="10sp" />
<TextView
android:id="#+id/min_counter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/min_text_view"
android:layout_marginTop="8dp"
android:fontFamily="sans-serif-light"
android:text="00"
android:textColor="#000000"
android:textSize="56sp" />
<TextView
android:id="#+id/blinker_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/min_text_view"
android:layout_marginTop="8dp"
android:layout_toRightOf="#id/min_counter"
android:fontFamily="sans-serif-light"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:text=":"
android:textColor="#000000"
android:textSize="56sp" />
<TextView
android:id="#+id/sec_counter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/min_text_view"
android:layout_marginTop="8dp"
android:layout_toRightOf="#id/blinker_text_view"
android:fontFamily="sans-serif-light"
android:text="00"
android:textColor="#000000"
android:textSize="56sp" />
</RelativeLayout>
<LinearLayout
android:id="#+id/l1_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/r1_layout"
android:orientation="horizontal">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:fontFamily="sans-serif-medium"
android:gravity="center_horizontal"
android:text="Team A"
android:textColor="#616161"
android:textSize="14sp" />
<TextView
android:id="#+id/teamA_score_text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:fontFamily="sans-serif-light"
android:gravity="center_horizontal"
android:text="0"
android:textColor="#000000"
android:textSize="56sp" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginLeft="24dp"
android:layout_marginRight="24dp"
android:layout_marginTop="24dp"
android:fontFamily="sans-serif-medium"
android:onClick="threePointsA"
android:text="+3 Points"
android:textAllCaps="true"
android:textColor="#616161"
android:textSize="14sp" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginLeft="24dp"
android:layout_marginRight="24dp"
android:fontFamily="sans-serif-medium"
android:onClick="twoPointsA"
android:text="+2 Points"
android:textAllCaps="true"
android:textColor="#616161"
android:textSize="14sp" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginLeft="24dp"
android:layout_marginRight="24dp"
android:fontFamily="sans-serif-medium"
android:onClick="freeThrowA"
android:text="Free Throw"
android:textAllCaps="true"
android:textColor="#616161"
android:textSize="14sp" />
</LinearLayout>
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:layout_marginTop="16dp"
android:background="#android:color/darker_gray"></View>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:fontFamily="sans-serif-medium"
android:gravity="center_horizontal"
android:text="Team B"
android:textColor="#616161"
android:textSize="14sp" />
<TextView
android:id="#+id/teamB_score_text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:fontFamily="sans-serif-light"
android:gravity="center_horizontal"
android:text="0"
android:textColor="#000000"
android:textSize="56sp" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginLeft="24dp"
android:layout_marginRight="24dp"
android:layout_marginTop="24dp"
android:fontFamily="sans-serif-medium"
android:onClick="threePointsB"
android:text="+3 Points"
android:textAllCaps="true"
android:textColor="#616161"
android:textSize="14sp" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginLeft="24dp"
android:layout_marginRight="24dp"
android:fontFamily="sans-serif-medium"
android:onClick="twoPointsB"
android:text="+2 Points"
android:textAllCaps="true"
android:textColor="#616161"
android:textSize="14sp" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginLeft="24dp"
android:layout_marginRight="24dp"
android:fontFamily="sans-serif-medium"
android:onClick="freeThrowB"
android:text="Free Throw"
android:textAllCaps="true"
android:textColor="#616161"
android:textSize="14sp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true">
<Button
android:id="#+id/timeout_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="8dp"
android:layout_marginBottom="32dp"
android:layout_marginLeft="16dp"
android:text="Start"
android:fontFamily="sans-serif-medium"
android:textAllCaps="true"
android:textColor="#616161"
android:textSize="14sp"
android:onClick="timeOut"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="32dp"
android:layout_marginRight="16dp"
android:layout_marginLeft="8dp"
android:fontFamily="sans-serif-medium"
android:onClick="Reset"
android:text="Reset"
android:textAllCaps="true"
android:textColor="#616161"
android:textSize="14sp" />
</LinearLayout>
</RelativeLayout>
You can't call findViewById before the onCreate method.
Move the initialization of your view references inside onCreate.
public class MainActivity extends AppCompatActivity {
int scoreTeamA = 0, scoreTeamB = 0;
TextView minutes;
TextView seconds;
long milliLeft, min, sec;
CountDownTimer gameTime;
Button timeoutButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
minutes = (TextView) findViewById(R.id.min_counter);
seconds = (TextView) findViewById(R.id.sec_counter);
timeoutButton = (Button) findViewById(R.id.timeout_button);
}
Declare all the variable in global
Move findViewById in onCreate method. You should initialize them inside onCreate method, not in global.
public class MainActivity extends AppCompatActivity {
int scoreTeamA = 0, scoreTeamB = 0;
TextView minutes;
TextView seconds;
long milliLeft, min, sec;
CountDownTimer gameTime;
final Button timeoutButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
minutes = (TextView) findViewById(R.id.min_counter);
seconds = (TextView) findViewById(R.id.sec_counter);
timeoutButton = (Button) findViewById(R.id.timeout_button);
}
// others code...
}

Non-responsive button

I have included a button known as "btnConfirm" in my activity layout, and has referred to it in the code below(mConfirm), however, when the button is clicked no action is triggered. I have even looked into logcat, where no new message is shown upon button click. The code below shows the action that the button was suppose to trigger - transmit the user entered information to parse, and redirect users to another activity page.
If you need any clarification, let me know.
Thanks in advance.
public class ProfileCreation extends Activity {
private static final int RESULT_LOAD_IMAGE = 1;
FrameLayout layout;
Button save;
protected EditText mName;
protected EditText mAge;
protected EditText mHeadline;
protected Button mConfirm;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_creation);
Parse.initialize(this, "ID", "ID");
mName = (EditText)findViewById(R.id.etxtname);
mAge = (EditText)findViewById(R.id.etxtage);
mHeadline = (EditText)findViewById(R.id.etxtheadline);
mConfirm = (Button)findViewById(R.id.btnConfirm);
mConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = mName.getText().toString();
String age = mAge.getText().toString();
String headline = mHeadline.getText().toString();
age = age.trim();
name = name.trim();
headline = headline.trim();
if (age.isEmpty() || name.isEmpty() || headline.isEmpty()) {
AlertDialog.Builder builder = new AlertDialog.Builder(ProfileCreation.this);
builder.setMessage(R.string.signup_error_message)
.setTitle(R.string.signup_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
else {
// create the new user!
setProgressBarIndeterminateVisibility(true);
ParseUser currentUser = ParseUser.getCurrentUser();
currentUser.put("name", name);
currentUser.put("age", age);
currentUser.put("headline", headline);
currentUser.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
setProgressBarIndeterminateVisibility(false);
if (e == null) {
// Success!
Intent intent = new Intent(ProfileCreation.this, MoodActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
else {
AlertDialog.Builder builder = new AlertDialog.Builder(ProfileCreation.this);
builder.setMessage(e.getMessage())
.setTitle(R.string.signup_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
}
});
setContentView(R.layout.activity_profile_creation);
save = (Button) findViewById(R.id.button2);
String picturePath = PreferenceManager.getDefaultSharedPreferences(this).getString("picturePath", "");
if (!picturePath.equals("")) {
ImageView imageView = (ImageView) findViewById(R.id.profilePicturePreview);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
SeekBar seekBar = (SeekBar) findViewById(R.id.seekBarDistance);
final TextView seekBarValue = (TextView) findViewById(R.id.seekBarDistanceValue);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
seekBarValue.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}); // Add this
SeekBar seekBarMinimum = (SeekBar) findViewById(R.id.seekBarMinimumAge);
final TextView txtMinimum = (TextView) findViewById(R.id.tMinAge);
seekBarMinimum.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
txtMinimum.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}); // Add this
SeekBar seekBarMaximum = (SeekBar) findViewById(R.id.seekBarMaximumAge);
final TextView txtMaximum = (TextView) findViewById(R.id.tMaxAge);
seekBarMaximum.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
txtMaximum.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}); // Add this
Button buttonLoadImage = (Button) findViewById(R.id.btnPictureSelect);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// Locate the image in res >
Bitmap bitmap = BitmapFactory.decodeFile("picturePath");
// Convert it to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Compress image to lower quality scale 1 - 100
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
Object image = null;
try {
String path = null;
image = readInFile(path);
} catch (Exception e) {
e.printStackTrace();
}
// Create the ParseFile
ParseFile file = new ParseFile("picturePath", (byte[]) image);
// Upload the image into Parse Cloud
file.saveInBackground();
// Create a New Class called "ImageUpload" in Parse
ParseObject imgupload = new ParseObject("Image");
// Create a column named "ImageName" and set the string
imgupload.put("Image", "picturePath");
// Create a column named "ImageFile" and insert the image
imgupload.put("ImageFile", file);
// Create the class and the columns
imgupload.saveInBackground();
// Show a simple toast message
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.profilePicturePreview);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
private byte[] readInFile(String path) throws IOException {
// TODO Auto-generated method stub
byte[] data = null;
File file = new File(path);
InputStream input_stream = new BufferedInputStream(new FileInputStream(
file));
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
data = new byte[16384]; // 16K
int bytes_read;
while ((bytes_read = input_stream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, bytes_read);
}
input_stream.close();
return buffer.toByteArray();
}
}
xml code
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/dark_texture_blue" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="797dp"
android:gravity="center"
android:orientation="vertical" >
<com.mikhaellopez.circularimageview.CircularImageView
android:id="#+id/profilePicturePreview"
android:layout_width="132dp"
android:layout_height="120dp"
android:layout_below="#+id/textView5"
android:layout_centerHorizontal="true"
android:layout_marginTop="7dp"
android:alpha="1" />
<Button
android:id="#+id/button2"
android:layout_width="120dp"
android:layout_height="60dp"
android:layout_above="#+id/etxtage"
android:layout_alignLeft="#+id/etxtname"
android:alpha="0.8"
android:background="#330099"
android:text="Upload from Facebook"
android:textColor="#ffffff"
android:textSize="17sp"
android:textStyle="bold" />
<Button
android:id="#+id/btnPictureSelect"
android:layout_width="118dp"
android:layout_height="60dp"
android:layout_alignRight="#+id/etxtname"
android:layout_below="#+id/profilePicturePreview"
android:layout_marginRight="8dp"
android:alpha="0.8"
android:background="#000000"
android:onClick="pickPhoto"
android:text="Select photo from gallery"
android:textColor="#ffffff"
android:textSize="17sp"
android:textStyle="bold" />
<TextView
android:id="#+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView4"
android:layout_centerHorizontal="true"
android:layout_marginTop="9dp"
android:text="Preferred Name"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#ADD8E6"
android:textSize="20sp"
android:textStyle="bold"
android:typeface="serif" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="39dp"
android:gravity="center"
android:text="Profile Creation"
android:textColor="#ffffff"
android:textSize="28sp"
android:textStyle="bold"
android:typeface="serif" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/button2"
android:layout_centerHorizontal="true"
android:layout_marginTop="14dp"
android:text="Age"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#ADD8E6"
android:textSize="20sp"
android:textStyle="bold"
android:typeface="serif" />
<EditText
android:id="#+id/etxtage"
android:layout_width="230dp"
android:layout_height="wrap_content"
android:layout_below="#+id/btnPictureSelect"
android:layout_centerHorizontal="true"
android:layout_marginTop="35dp"
android:ems="10"
android:hint="Please type your age here"
android:inputType="number"
android:maxLength="2"
android:textAlignment="center"
android:textColor="#f2f2f2"
android:textSize="18dp" />
<EditText
android:id="#+id/etxtname"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_below="#+id/textView6"
android:layout_centerHorizontal="true"
android:ems="10"
android:enabled="true"
android:hint="Please type your name here"
android:inputType="textPersonName"
android:textColor="#ffffff"
android:textSize="18sp" />
<TextView
android:id="#+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/etxtname"
android:layout_centerHorizontal="true"
android:layout_marginTop="8dp"
android:text="Upload your Profile Picture"
android:textColor="#f2f2f2"
android:textSize="18sp"
android:textStyle="bold"
android:typeface="sans" />
<RadioGroup
android:id="#+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_toLeftOf="#+id/textView3" >
<RadioButton
android:id="#+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:textColor="#f2f2f2"
android:text="Male" />
<RadioButton
android:id="#+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#f2f2f2"
android:text="Female" />
</RadioGroup>
<SeekBar
android:id="#+id/seekBarDistance"
android:layout_width="250dp"
android:progress="50"
android:layout_centerHorizontal="true"
android:layout_height="wrap_content"
android:layout_below="#+id/textView12"
android:layout_marginTop="11dp" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView5"
android:layout_below="#+id/etxtheadline"
android:layout_marginTop="38dp"
android:text="I am a"
android:textColor="#ADD8E6"
android:textSize="20sp"
android:textStyle="bold" />
<RadioGroup
android:id="#+id/radioGroup3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView4"
android:layout_alignTop="#+id/radioGroup2"
android:layout_marginTop="10dp" >
</RadioGroup>
<RadioGroup
android:id="#+id/radioGroup2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/etxtheadline"
android:layout_below="#+id/textView2" >
<RadioButton
android:id="#+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Male"
android:textColor="#f2f2f2" />
<RadioButton
android:id="#+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"
android:textColor="#f2f2f2" />
</RadioGroup>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView1"
android:layout_alignBottom="#+id/textView1"
android:layout_alignRight="#+id/radioGroup2"
android:text="Looking for"
android:textColor="#ADD8E6"
android:textSize="20sp"
android:textStyle="bold" />
<SeekBar
android:id="#+id/seekBarMinimumAge"
android:layout_width="220dp"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView7"
android:layout_marginTop="11dp"
android:progress="25" />
<TextView
android:id="#+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/etxtage"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="Minimum Age Looking For"
android:textColor="#f2f2f2"
android:textSize="16sp"
android:textStyle="bold"
android:typeface="serif" />
<EditText
android:id="#+id/etxtheadline"
android:layout_width="270dp"
android:layout_height="70dp"
android:layout_alignLeft="#+id/button2"
android:layout_below="#+id/textView8"
android:ems="10"
android:hint="A quick description of yourself"
android:singleLine="true"
android:textAlignment="center"
android:textColor="#f2f2f2"
android:textSize="18dp" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/seekBarDistanceValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/tMinAge"
android:layout_below="#+id/seekBarDistance"
android:text="50"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#f2f2f2"
android:textSize="20sp"
android:textStyle="bold"
android:typeface="serif" />
<TextView
android:id="#+id/textView12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/radioGroup1"
android:layout_centerHorizontal="true"
android:layout_marginTop="19dp"
android:text="Search Distance (100KM)"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#ADD8E6"
android:textSize="20sp"
android:textStyle="bold"
android:typeface="serif" />
<TextView
android:id="#+id/tMinAge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/seekBarMinimumAge"
android:layout_centerHorizontal="true"
android:text="25"
android:textColor="#f2f2f2"
android:textSize="18sp" />
<TextView
android:id="#+id/textView8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tMaxAge"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:text="Headline"
android:textColor="#ADD8E6"
android:textSize="20sp"
android:textStyle="bold"
android:typeface="serif" />
<TextView
android:id="#+id/textView14"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tMinAge"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:text="Maximum Age Looking For"
android:textColor="#f2f2f2"
android:textSize="16sp"
android:textStyle="bold"
android:typeface="serif" />
<SeekBar
android:id="#+id/seekBarMaximumAge"
android:layout_width="221dp"
android:progress="50"
android:layout_centerHorizontal="true"
android:layout_height="wrap_content"
android:layout_below="#+id/textView14"
android:layout_marginTop="11dp" />
<TextView
android:id="#+id/tMaxAge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/seekBarMaximumAge"
android:layout_centerHorizontal="true"
android:text="50"
android:textColor="#f2f2f2"
android:textSize="18sp" />
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView16"
android:layout_centerHorizontal="true"
android:text="I agree to the terms and Conditions"
android:textColor="#D2D2D2"
android:textColorHint="#ffffff" />
<TextView
android:id="#+id/textView16"
android:layout_width="280dp"
android:layout_height="40dp"
android:layout_alignLeft="#+id/checkBox1"
android:layout_below="#+id/seekBarDistanceValue"
android:layout_marginTop="14dp"
android:gravity="center"
android:text="Click here to review the terms and conditions"
android:textColor="#99CCFF"
android:textSize="16sp" />
<Button
android:id="#+id/btnReset"
android:layout_width="120dp"
android:layout_height="60dp"
android:layout_marginBottom="7dp"
android:layout_below="#+id/checkBox1"
android:layout_toLeftOf="#+id/btnPictureSelect"
android:alpha="0.8"
android:background="#660000"
android:layout_marginTop="14dp"
android:text="Reset"
android:textColor="#ffffff"
android:textSize="17sp"
android:textStyle="bold" />
<Button
android:id="#+id/btnConfirm"
android:layout_width="120dp"
android:layout_height="60dp"
android:layout_below="#+id/checkBox1"
android:layout_toRightOf="#+id/seekBarDistanceValue"
android:alpha="0.8"
android:layout_marginTop="14dp"
android:layout_marginBottom="7dp"
android:background="#330099"
android:text="Confirm"
android:textColor="#ffffff"
android:textSize="17sp"
android:textStyle="bold" />
</RelativeLayout>
</ScrollView>
As I saw in your code ..You have set the same content view setContentView(R.layout.activity_profile_creation); twice..
1st one (perfect):
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_creation);`
2nd one(makes problem): Just before the save button
setContentView(R.layout.activity_profile_creation);
save = (Button) findViewById(R.id.button2);
Delete the second one i.e which is just before save button.

Android application crashes every time on startup

I started coding my first app in Android Studio, what it should do at this stage is that you click a button with the digit and it outputs it into the textfield. When i run this code the application crashes right on startup and I have no idea what's wrong.
MyActivity.java
package com.example.david.calculator;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import org.w3c.dom.Text;
public class MyActivity extends Activity {
EditText results;
private int number;
final EditText result = (EditText) findViewById(R.id.number);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
Button one = (Button) findViewById(R.id.button);
one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
BtnPressed(1);
}
});
}
private void BtnPressed(int i) {
result.setText(Integer.toString(i));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_my.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"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MyActivity">
<EditText
android:layout_width="fill_parent"
android:layout_height="50dp"
android:id="#+id/number"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:hint="0"
android:background="#ffe7e7e7"
android:textSize="30sp"
android:gravity="center_vertical|right"
android:paddingRight="20dp"
android:editable="true"
android:enabled="true"
android:numeric="integer|signed|decimal" />
<Button
android:layout_width="75dp"
android:layout_height="75dp"
android:text="1"
android:id="#+id/button"
android:layout_below="#+id/number"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textSize="50sp"
android:background="#ff0fdf22"
android:layout_marginTop="10dp" />
<Button
android:layout_width="75dp"
android:layout_height="75dp"
android:text="2"
android:id="#+id/button2"
android:textSize="50sp"
android:background="#ff0fdf22"
android:layout_alignTop="#+id/button"
android:layout_toRightOf="#+id/button"
android:layout_marginLeft="10dp" />
<Button
android:layout_width="75dp"
android:layout_height="75dp"
android:text="3"
android:id="#+id/button3"
android:textSize="50sp"
android:background="#ff0fdf22"
android:layout_alignTop="#+id/button2"
android:layout_toRightOf="#+id/button2"
android:layout_marginLeft="10dp" />
<Button
android:layout_width="75dp"
android:layout_height="75dp"
android:text="4"
android:id="#+id/button4"
android:textSize="50sp"
android:background="#ff0fdf22"
android:layout_below="#+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="10dp" />
<Button
android:layout_width="75dp"
android:layout_height="75dp"
android:text="5"
android:id="#+id/button5"
android:textSize="50sp"
android:background="#ff0fdf22"
android:layout_alignTop="#+id/button4"
android:layout_toRightOf="#+id/button4"
android:layout_marginLeft="10dp" />
<Button
android:layout_width="75dp"
android:layout_height="75dp"
android:text="6"
android:id="#+id/button6"
android:textSize="50sp"
android:background="#ff0fdf22"
android:layout_alignTop="#+id/button5"
android:layout_toRightOf="#+id/button5"
android:layout_marginLeft="10dp" />
<Button
android:layout_width="75dp"
android:layout_height="75dp"
android:text="7"
android:id="#+id/button7"
android:textSize="50sp"
android:background="#ff0fdf22"
android:layout_below="#+id/button4"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="10dp" />
<Button
android:layout_width="75dp"
android:layout_height="75dp"
android:text="8"
android:id="#+id/button8"
android:textSize="50sp"
android:background="#ff0fdf22"
android:layout_alignTop="#+id/button7"
android:layout_toRightOf="#+id/button7"
android:layout_marginLeft="10dp" />
<Button
android:layout_width="75dp"
android:layout_height="75dp"
android:text="9"
android:id="#+id/button9"
android:textSize="50sp"
android:background="#ff0fdf22"
android:layout_alignTop="#+id/button8"
android:layout_toRightOf="#+id/button8"
android:layout_marginLeft="10dp" />
<Button
android:layout_width="75dp"
android:layout_height="75dp"
android:text="0"
android:id="#+id/button11"
android:textSize="50sp"
android:background="#ff0fdf22"
android:layout_below="#+id/button7"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="10dp" />
<Button
android:layout_width="160dp"
android:layout_height="75dp"
android:text="="
android:id="#+id/button12"
android:textSize="50sp"
android:background="#ff0fdf22"
android:layout_alignTop="#+id/button11"
android:layout_toRightOf="#+id/button11"
android:layout_marginLeft="10dp" />
<Button
android:layout_width="75dp"
android:layout_height="75dp"
android:text="+"
android:id="#+id/button13"
android:textSize="50sp"
android:background="#ff0fdf22"
android:layout_alignTop="#+id/button3"
android:layout_toRightOf="#+id/button3"
android:layout_marginLeft="10dp" />
<Button
android:layout_width="75dp"
android:layout_height="75dp"
android:text="-"
android:id="#+id/button14"
android:textSize="50sp"
android:background="#ff0fdf22"
android:layout_alignTop="#+id/button6"
android:layout_toRightOf="#+id/button6"
android:layout_marginLeft="10dp" />
<Button
android:layout_width="75dp"
android:layout_height="75dp"
android:text="*"
android:id="#+id/button15"
android:textSize="50sp"
android:background="#ff0fdf22"
android:layout_alignTop="#+id/button9"
android:layout_toRightOf="#+id/button9"
android:layout_marginLeft="10dp" />
<Button
android:layout_width="75dp"
android:layout_height="75dp"
android:text="/"
android:id="#+id/button16"
android:textSize="50sp"
android:background="#ff0fdf22"
android:layout_alignTop="#+id/button12"
android:layout_toRightOf="#+id/button12"
android:layout_marginLeft="10dp" />
Logcat:
07-24 16:30:07.894 26564-26564/com.example.david.calculator D/AndroidRuntime﹕ Shutting down VM
07-24 16:30:07.894 26564-26564/com.example.david.calculator W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4190aba8)
07-24 16:30:07.899 26564-26564/com.example.david.calculator E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.david.calculator, PID: 26564
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.david.calculator/com.example.david.calculator.MyActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.app.Activity.findViewById(Activity.java:1884)
at com.example.david.calculator.MyActivity.<init>(MyActivity.java:18)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2101)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Thank you very much for all the replies.
            
You are setting your EditText in your main class and not in your classes onCreate method. You can't find a view if the activity hasn't been created yet.
public class MyActivity extends Activity {
EditText results;
private int number;
final EditText result = (EditText) findViewById(R.id.number);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
Button one = (Button) findViewById(R.id.button);
one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
BtnPressed(1);
}
});
}
Should become
public class MyActivity extends Activity {
EditText results;
private int number;
private EditText result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
result = (EditText) findViewById(R.id.number);
Button one = (Button) findViewById(R.id.button);
one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
BtnPressed(1);
}
});
}
You were getting a NullPointerException in your log, this should fix it.
You should move
final EditText result = (EditText) findViewById(R.id.number);
inside onCreate(...) after setContentView(..)
Corrected Code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
EditText result = (EditText) findViewById(R.id.number);
Button one = (Button) findViewById(R.id.button);
one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
BtnPressed(1);
}
});
}
Check your code:
final EditText result = (EditText) findViewById(R.id.number);
This should come after setContentView() method just like with the button.
You should do this:
final EditText result = (EditText) findViewById(R.id.number);
in your onCreate after the setContentView.

Getting NullPointerException in code which was working earlier

I have a code to check PNR number. Because of internet issues, i thought to give users to check PNR by SMS. So I added 2 Radio Buttons, one for internet and one for SMS. But the problem is now when I click the PNR Button, it gives nullPointer Exception.
Here is my Main Activity.java
public class MainActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
private EditText pnrNumber;
private TextView errMsg;
private Button getPnr;
private Button pnrClear;
Button Yes, No;
RadioButton checkbyinternet, checkbysms;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
errMsg = (TextView) findViewById(R.id.errMsg);
pnrNumber = (EditText) findViewById(R.id.pnrNumber_p01);
getPnr = (Button) findViewById(R.id.checkPNRButton);
pnrClear = (Button) findViewById(R.id.pnrClear);
getPnr.setOnClickListener(this);
pnrClear.setOnClickListener(this);
}
public void onClick(View src) {
// Perform action on click
if (src.getId() == R.id.checkPNRButton)
{
if (checkbyinternet.isChecked())
{
int pnr2 = pnrNumber.getEditableText().length();
if (pnr2 != 10)
{
errMsg.setText("Length of PNR is Invalid.");
}
else
{
String pnr = pnrNumber.getEditableText().toString();
Bundle b = new Bundle();
b.putString("pnr", pnr);
System.out.println("Connectivity : "
+ this.isNetworkAvailable());
PNRStatus pnrStatus = null;
// Connect to the Server and Get the PNR status
try
{
String captcha = "37819";
String pnr1 = pnrNumber.getText().toString();
String reqStr = "lccp_pnrno1=" + pnr1
+ "&lccp_cap_val=" + captcha
+ "&lccp_capinp_val=" + captcha
+ "&submitpnr=Get+Status";
PNRStatusCheck check = new PNRStatusCheck();
StringBuffer data = check
.getPNRResponse(reqStr,
"http://www.indianrail.gov.in/cgi_bin/inet_pnstat_cgi_28688.cgi");
// String pnr1 = pnr; //"1154177041";
// String reqStr = "lccp_pnrno1=" + pnr1 +
// "&submitpnr=Get+Status";
// PNRStatusCheck check = new PNRStatusCheck();
// StringBuffer data = check.getPNRResponse(reqStr,
// "http://www.indianrail.gov.in/cgi_bin/inet_pnrstat_cgi.cgi");
if (data != null)
{
pnrStatus = check.parseHtml(data);
b.putSerializable("pnrStatus", pnrStatus);
}
else
{
// error
}
}
catch (Exception e)
{
e.printStackTrace();
}
Intent to = null;
if (pnrStatus != null)
{
to = new Intent(this, PNRStatusActivity.class);
to.putExtras(b);
startActivity(to);
}
else
{
errMsg.setText("Error prcessing PNR. Please try again.");
}
}
}
else if (checkbysms.isChecked())
{
// Toast.makeText(this, "SMS", Toast.LENGTH_SHORT).show();
int pnr2 = pnrNumber.getEditableText().length();
if (pnr2 != 10)
{
errMsg.setText("Length of PNR is Invalid.");
}
else
{
openSMSWarningDialog(src);
}
}
}
else if (src.getId() == R.id.pnrClear)
{
errMsg.setText("");
pnrNumber.setText("");
}
}
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
// if no network is available networkInfo will be null, otherwise check
// if we are connected
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}
public void openSMSWarningDialog(View view) {
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.smsdialog);
dialog.setTitle("Are you sure to use SMS.?");
Yes = (Button) dialog.findViewById(R.id.yes);
No = (Button) dialog.findViewById(R.id.no);
Yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String PnrNum = pnrNumber.getText().toString();
String messageToSend = ("PNR " + PnrNum);
String number = "139";
SmsManager.getDefault().sendTextMessage(number, null,
messageToSend, null, null);
dialog.dismiss();
Toast.makeText(
getBaseContext(),
"Please check your inbox in sometime for your PNR Status",
Toast.LENGTH_LONG).show();
}
});
No.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
dialog.show();
}
}
And here is my layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center_horizontal"
android:background="#drawable/background"
android:gravity="center_horizontal"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="17dp"
android:layout_marginLeft="7dp"
android:layout_marginRight="7dp"
android:text="#string/title"
android:gravity="center_horizontal"
android:textColor="#android:color/black"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/errMsg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="17dp"
android:layout_marginLeft="7dp"
android:layout_marginRight="7dp"
android:textColor="#android:color/black"
android:text="10 Digits Mandatory" />
<EditText
android:id="#+id/pnrNumber_p01"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_gravity="center_horizontal"
android:paddingLeft="10dp"
android:background="#drawable/edittextellipsedbackground"
android:layout_marginTop="17dp"
android:layout_marginBottom="7dp"
android:layout_marginLeft="7dp"
android:layout_marginRight="7dp"
android:hint="#string/pnrTextView" >
<requestFocus />
</EditText>
<Button
android:id="#+id/checkPNRButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="#drawable/bluebutton"
android:layout_marginTop="17dp"
android:layout_marginLeft="7dp"
android:layout_marginRight="7dp"
android:padding="10dp"
android:shadowColor="#000000"
android:shadowRadius="5.9"
android:text="#string/checkPNRButton"
android:textColor="#ffffff"
android:textSize="20sp" />
<Button
android:id="#+id/pnrClear"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/bluebutton"
android:layout_marginTop="7dp"
android:layout_marginLeft="7dp"
android:layout_marginRight="7dp"
android:padding="10dp"
android:shadowColor="#000000"
android:shadowRadius="5.9"
android:text="Clear"
android:textColor="#ffffff"
android:textSize="20sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="7dp"
android:layout_marginRight="7dp"
android:layout_marginTop="20dp"
android:background="#drawable/roundlayoutborder"
android:gravity="center"
android:paddingBottom="5dp" >
<RadioGroup
android:id="#+id/checkvia"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:orientation="vertical" >
<RadioButton
android:id="#+id/internet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:textColor="#android:color/black"
android:text="#string/CheckByInternet"
android:textAppearance="?android:attr/textAppearanceSmall" />
<RadioButton
android:id="#+id/sms"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/black"
android:text="#string/CheckBySMS"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RadioGroup>
</LinearLayout>
</LinearLayout>
SMS Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#9bafb0"
android:orientation="vertical" >
<TextView
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:textColor="#ff0000"
android:ems="27"
android:text="#string/CheckThroughSMSWarning" >
</TextView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:layout_marginTop="15dp"
android:layout_marginBottom="15dp" >
<Button
android:id="#+id/yes"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="2dp"
android:textColor="#android:color/white"
android:layout_weight="1"
android:background="#drawable/bluebutton"
android:text="Yes" />
<Button
android:id="#+id/no"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:layout_marginLeft="2dp"
android:layout_marginRight="5dp"
android:textColor="#android:color/white"
android:layout_weight="1"
android:background="#drawable/bluebutton"
android:text="No" />
</LinearLayout>
</LinearLayout>
Here is my LOG:
02-06 13:54:22.810: E/AndroidRuntime(858): FATAL EXCEPTION: main
02-06 13:54:22.810: E/AndroidRuntime(858): java.lang.NullPointerException
02-06 13:54:22.810: E/AndroidRuntime(858): at akshat.jaiswal.indianrailways.MainActivity.onClick(MainActivity.java:50)
02-06 13:54:22.810: E/AndroidRuntime(858): at android.view.View.performClick(View.java:4084)
02-06 13:54:22.810: E/AndroidRuntime(858): at android.view.View$PerformClick.run(View.java:16966)
02-06 13:54:22.810: E/AndroidRuntime(858): at android.os.Handler.handleCallback(Handler.java:615)
02-06 13:54:22.810: E/AndroidRuntime(858): at android.os.Handler.dispatchMessage(Handler.java:92)
02-06 13:54:22.810: E/AndroidRuntime(858): at android.os.Looper.loop(Looper.java:137)
02-06 13:54:22.810: E/AndroidRuntime(858): at android.app.ActivityThread.main(ActivityThread.java:4745)
02-06 13:54:22.810: E/AndroidRuntime(858): at java.lang.reflect.Method.invokeNative(Native Method)
02-06 13:54:22.810: E/AndroidRuntime(858): at java.lang.reflect.Method.invoke(Method.java:511)
02-06 13:54:22.810: E/AndroidRuntime(858): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
02-06 13:54:22.810: E/AndroidRuntime(858): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-06 13:54:22.810: E/AndroidRuntime(858): at dalvik.system.NativeStart.main(Native Method)
Please help, I am not able to get any solution for this.
Your checkbyinternet and checkbysms buttons are uninitialized and that is why you're getting the NullPointerException when if (checkbyinternet.isChecked()) is executed in the onClick() method.
if (src.getId() == R.id.checkPNRButton) // true if you pressed the getPnr button
{
if (checkbyinternet.isChecked()) // checkbyinternet is uninitialized yet, so it'll throw a NPE
You need to initialize them as well in the onCreate() method.
checkbyinternet = (RadioButton) findViewById(R.id.internet);
checkbysms = (RadioButton) findViewById(R.id.sms);

Categories