Crashes probably due to bad activity layout - java

I've been developing an application and it has been working good until I added a LinearLayout (id = 'toolbar') and some functions in that activity's corresponding Java file. Here are my codes:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.com.myapplication">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".EditPhotoActivity"
android:parentActivityName=".MainActivity">
<meta-data android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity" />
</activity>
</application>
</manifest>
MainActivty is working good and I don't think the problem is in it. Please let me know if you want me add its code.
EditPhotoActivity.java
package com.example.com.myapplication;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import java.io.IOException;
public class EditPhotoActivity extends AppCompatActivity {
public ImageView image_view = findViewById(R.id.image_display) ;
public boolean toolbar_is_open = false ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_photo);
ImageView imageView = findViewById(R.id.image_display);
Intent intent = getIntent();
Uri content;
if(intent.getStringExtra(MainActivity.DATA_TYPE).equals("Uri")) {
Bundle bundle = intent.getExtras();
if(bundle != null) {
content = (Uri) bundle.get(MainActivity.IMAGE_KEY);
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), content);
imageView.setImageBitmap(bitmap);
} catch(IOException e) {
e.printStackTrace();
Toast.makeText(this, "Failed to fetch image data!", Toast.LENGTH_LONG).show() ;
}
}
} else if(intent.getStringExtra(MainActivity.DATA_TYPE).equals("Bundle")) {
Bundle bundle = intent.getBundleExtra(MainActivity.IMAGE_KEY);
Bitmap bitmap = (Bitmap)bundle.get("data");
imageView.setImageBitmap(bitmap);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.publish_menu, menu);
return true ;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.share_button:
// Save the photo
break;
case R.id.save_button:
// Open Share Photo Activity
break;
}
return super.onOptionsItemSelected(item);
}
private void setToolbarState(boolean open) {
LinearLayout toolbar = findViewById(R.id.toolbar);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)toolbar.getLayoutParams();
params.height = open? 50 : 0;
toolbar.setLayoutParams(params);
toolbar_is_open = open ;
}
public void openRotateToolbar(View view) {
Button right = new Button(this), left = new Button(this);
right.setText(R.string.right); left.setText(R.string.left);
right.setBackgroundResource(R.drawable.custom_button);
left.setBackgroundResource(R.drawable.custom_button);
right.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View view) {
image_view.setRotation(90f);
}
});
left.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View view) {
image_view.setRotation(-90f);
}
});
if(!toolbar_is_open)
setToolbarState(true);
}
public void closeToolbar(View view) {
if(toolbar_is_open)
setToolbarState(false);
}
}
activity_edit_photo.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.com.myapplication.EditPhotoActivity"
tools:layout_editor_absoluteY="81dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:weightSum="2"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/image_display"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:adjustViewBounds="true"
android:background="#color/black"
android:padding="0dp"
android:scaleType="fitCenter"
app:layout_constraintBottom_toTopOf="#+id/toolbar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_launcher_background"
tools:ignore="contentDescription" />
<LinearLayout
android:id="#+id/toolbar"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#111"
android:orientation="horizontal"
app:layout_constraintBottom_toTopOf="#+id/scrollView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintStart_toStartOf="parent">
<Button
android:id="#+id/button4"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/close"
android:background="#drawable/custom_button"
android:textColor="#fff"
android:onClick="closeToolbar" />
</LinearLayout>
<HorizontalScrollView
android:id="#+id/scrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="#color/darkGrey"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#drawable/custom_button"
android:text="#string/add_sticker"
android:textColor="#fff"
android:textSize="12sp"
tools:ignore="ButtonStyle" />
<Button
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_marginTop="-15dp"
android:background="#drawable/custom_button"
android:gravity="center"
android:text="#string/create_sticker"
android:textSize="12sp"
tools:ignore="ButtonStyle" />
<Button
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#drawable/custom_button"
android:gravity="center"
android:text="#string/cut_sticker"
android:textSize="12sp"
tools:ignore="ButtonStyle" />
<Button
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#drawable/custom_button"
android:gravity="center"
android:text="#string/apply_filter"
android:textSize="12sp"
tools:ignore="ButtonStyle" />
<Button
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#drawable/custom_button"
android:gravity="center"
android:text="#string/rotate"
android:textSize="12sp"
tools:ignore="ButtonStyle"
android:onClick="openRotateToolbar" />
<Button
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#drawable/custom_button"
android:gravity="center"
android:text="#string/flip"
android:textSize="12sp"
tools:ignore="ButtonStyle" />
<Button
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#drawable/custom_button"
android:gravity="center"
android:text="#string/crop"
android:textSize="12sp"
tools:ignore="ButtonStyle" />
</LinearLayout>
</HorizontalScrollView>
</android.support.constraint.ConstraintLayout>
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
I am not getting any errors but when the app is transitioning to EditPhoto Activity it crashes. Please let me know if you need me to provide you with any other information.
Note: I can not post the logcat because I am not using ADB and I am not using a computer that is all mine (it's my family's) so I don't want to enable x-vt in BIOS and so I am not able to use an Emulator also. To test my app I build the apk then I install it on my phone.

I have found my mistake. I will let this answer here for anyone that comes into the same problem.
The line:
public ImageView image_view = findViewById(R.id.image_display) ;
causes NullPointerException because at the time the app is opening the activity it does not yet have all the view and id's. It gets them only when it calls onCreate so I replaced the line to
public ImageView image_view ;
and inside onCreate after the super.onCreate(savedInstanceState) and the setContentView(R.layout.activity_edit_photo) calls I added
image_view = findViewById(R.id.image_display) ;

Related

My Activity comes out as a Blank even though it shouldn't?

I'm a complete beginner with coding and decided to try out android studios for fun without having formal training or lessons for the basics so I'm sorry if this seems like a dumb problem but whenever I try to run my code it just comes off as blank? Any idea how to solve this?
Here's a screenshot of what comes up
package com.example.trtalpha17;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import org.jetbrains.annotations.NotNull;
public class Register_Tutor extends AppCompatActivity {
private static final String[] SCHOOLS = new String[]{
"A", "B", "C"
};
private static final String[] COURSE = new String[]{
"Bachelor of Science in Social Work (BS Social Work)",
"Bachelor of Science in Marine Transportation (BSMT)",
"Bachelor of Science in Food Technology (BS Food Tech)",
"Bachelor of Science in Nutrition and Dietetics (BS Nutrition and Dietetics)"
};
private static final String[] EDUCA = new String[]{
"Grade 9", "Grade 10", "Grade 11", "Grade 12", "1st Year College", "2nd Year College", "3rd Year College", "4th Year College", "5th Year College", "Graduate"
};
private static final String[] TITLES = new String[]{
"Mr.", "Ms.", "Mrs.", "Mx."
};
EditText metEmail, metPhone, metPassword, metPasswordconfirm, metNamefirst, metNamelast;
Button mbutton;
ProgressBar progressBar2;
FirebaseAuth fAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register_tutor2);
final AutoCompleteTextView metTitle = (AutoCompleteTextView)findViewById(R.id.etTitle);
final AutoCompleteTextView mautoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
final AutoCompleteTextView meduc = (AutoCompleteTextView) findViewById(R.id.educ);
final AutoCompleteTextView metcourse = (AutoCompleteTextView) findViewById(R.id.etcourse);
metTitle.setThreshold(2);
mautoCompleteTextView.setThreshold(1);
meduc.setThreshold(1);
metcourse.setThreshold(1);
ImageView marrow = (ImageView) findViewById(R.id.arrow);
ArrayAdapter<String> adapterarrow = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, TITLES);
metTitle.setAdapter(adapterarrow);
ArrayAdapter<String> adapterschools = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, SCHOOLS);
mautoCompleteTextView.setAdapter(adapterschools);
ArrayAdapter<String> adapteredu = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, EDUCA);
meduc.setAdapter(adapteredu);
ArrayAdapter<String> adaptercourse = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, COURSE);
metcourse.setAdapter(adaptercourse);
marrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
metTitle.showDropDown();
}
});
metNamefirst = findViewById(R.id.etNamefirst);
metNamelast = findViewById(R.id.etNamelast);
metEmail = findViewById(R.id.etEmail);
metPhone =findViewById(R.id.etPhone);
metPassword = findViewById(R.id.etPassword);
metPasswordconfirm =findViewById(R.id.etPasswordconfirm);
mbutton = findViewById(R.id.button);
progressBar2 = findViewById(R.id.progressBar2);
fAuth = FirebaseAuth.getInstance();
if(fAuth.getCurrentUser() != null){
startActivity(new Intent(getApplicationContext(),MainActivity.class));
finish();
}
mbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = metEmail.getText().toString().trim();
String password = metPassword.getText().toString().trim();
if(TextUtils.isEmpty(email)){
metEmail.setError("Email is required.");
return;
}
if(TextUtils.isEmpty(password)){
metPassword.setError("Password is required.");
return;
}
if(password.length()<6){
metPassword.setError("Password length must be at least 6 characters.");
return;
}
fAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull #NotNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(Register_Tutor.this, "Registration complete.", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}else {
Toast.makeText(Register_Tutor.this, "There was an error making your that request. Please try again later." + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
}
LAYOUT
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Register_Tutor">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:fontFamily="cursive"
android:text="Register as a Tutor"
android:textColor="#000000"
android:textSize="28sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TableRow
android:id="#+id/tableRow"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView2">
<AutoCompleteTextView
android:id="#+id/etTitle"
android:layout_width="68dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:drawableLeft="#drawable/ic_baseline_person_24"
android:drawablePadding="5dp"
android:hint="Title"
android:inputType="textPersonName" />
<ImageView
android:id="#+id/arrow"
android:layout_width="16dp"
android:layout_height="45dp"
android:layout_marginStart="4dp"
android:layout_marginLeft="4dp"
android:drawablePadding="5dp"
android:src="#mipmap/outline_arrow_drop_down_black_18" />
<EditText
android:id="#+id/etNamefirst"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:hint="First name"
android:inputType="textPersonName" />
<EditText
android:id="#+id/etNamelast"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:hint="Last name"
android:inputType="textPersonName" />
</TableRow>
<LinearLayout
android:id="#+id/linear1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintTop_toBottomOf="#+id/tableRow">
<EditText
android:id="#+id/etEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:drawableLeft="#drawable/ic_baseline_email_24"
android:drawablePadding="5dp"
android:hint="Email address"
android:inputType="textEmailAddress" />
<EditText
android:id="#+id/etPhone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:drawableLeft="#drawable/ic_baseline_local_phone_24"
android:drawablePadding="5dp"
android:hint="Phone number"
android:inputType="phone" />
</LinearLayout>
<LinearLayout
android:id="#+id/linear2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/linear1">
<AutoCompleteTextView
android:id="#+id/autoCompleteTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:completionThreshold="1"
android:drawableLeft="#drawable/ic_baseline_school_24"
android:drawablePadding="5dp"
android:hint="School" />
<AutoCompleteTextView
android:id="#+id/educ"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:completionThreshold="1"
android:drawableLeft="#drawable/ic_baseline_article_24"
android:drawablePadding="5dp"
android:hint="Educational Attainment" />
<AutoCompleteTextView
android:id="#+id/etcourse"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:completionThreshold="1"
android:drawableLeft="#drawable/ic_baseline_article_24"
android:drawablePadding="5dp"
android:hint="Course" />
</LinearLayout>
<LinearLayout
android:id="#+id/linear3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintTop_toBottomOf="#+id/linear2">
<EditText
android:id="#+id/etPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:drawableLeft="#drawable/ic_baseline_lock_24"
android:drawablePadding="5dp"
android:hint="Password"
android:inputType="textPassword" />
<EditText
android:id="#+id/etPasswordconfirm"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:drawableLeft="#drawable/ic_baseline_lock_open_24"
android:drawablePadding="5dp"
android:hint="Confirm Password"
android:inputType="textPassword" />
<Button
android:id="#+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="24dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="10dp"
android:background="#drawable/button"
android:gravity="center"
android:hint="SIGN UP"
android:textColorHint="#FDFCFC"
app:backgroundTint="#315E8C" />
<ProgressBar
android:id="#+id/progressBar2"
style="?android:attr/progressBarStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="invisible" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
ANDROID MANIFEST
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.trtalpha17">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.TRTAlpha17"
>
<activity android:name=".Register_Tutor">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Login" />
<activity android:name=".RegisterStudent" />
<activity android:name=".RegistrationHome" />
<activity android:name=".MainActivity" />
</application>
</manifest>
Did you clean and rebuild your project or Invalid caches/restart from IDE?You will find it in under File menu.
It seems like your code is fine , so I decided to run in IDE its compiling and running perfectly .
Firebase console-
So you can do some checks in your side -
1.
setContentView(R.layout.activity_register_tutor2);
is layout.activity_register_tutor2 your main/default layout? Or any other layout`?
2.
if(fAuth.getCurrentUser() != null){
startActivity(new Intent(getApplicationContext(),MainActivity.class));
finish();
}
If you already sign in at least one time , this code will take you in MainActivity . Is that blank activity MainActivity? Make sure . You did not share your layout file of MainActivity , so I'm not sure .
You can Implement logout to test/debug your app easier by -
private Button mLogOutBtn;
mLogOutBtn = findViewById(R.id.log_out_btn);
mAuth = FirebaseAuth.getInstance();
mLogOutBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAuth.signOut();
startActivity(new Intent(MainActivity.this, Register_Tutor.class));
finish();
}
});

App Crash when i click button to change activity [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
What is a NullPointerException, and how do I fix it?
(12 answers)
Null pointer Exception - findViewById()
(12 answers)
Closed 4 years ago.
I'm sorry if i'm not so accurate but this is my first app.
The problem is: when i press a button to change activity the app crash.
Can someone help me? Thanks for all!!
If you wanna have more information tell me and I try to explain better.
CODE:
MAIN ACTIVITY
package com.example.principale.designazioni;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button invia = (Button) findViewById(R.id.buttInvia);
invia.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openActivityPage1();
}
});
}
public void openActivityPage1() {
Intent intent = new Intent (getApplicationContext(), Page1.class);
startActivity(intent);
}
}
XML MAIN ACTIVITY
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:layout_editor_absoluteY="73dp">
<ImageView
android:id="#+id/imageView4"
android:layout_width="231dp"
android:layout_height="229dp"
android:layout_marginEnd="8dp"
android:adjustViewBounds="false"
android:contentDescription='#string tools:ignore="ContentDescription"'
android:cropToPadding="false"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.146"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.04"
app:srcCompat="#mipmap/logo_grigio" />
<TextView
android:id="#+id/textView2"
android:layout_width="272dp"
android:layout_height="51dp"
android:fontFamily="monospace"
android:text="Disponibilità"
android:textAlignment="center"
android:textColor="#android:color/holo_orange_dark"
android:textSize="30sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.818"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView4"
app:layout_constraintVertical_bias="0.093" />
<Button
android:id="#+id/buttInvia"
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="monospace"
android:text="Invia"
android:textAlignment="center"
android:textAllCaps="true"
android:textColor="#android:color/holo_orange_dark"
android:textSize="36sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.502"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView2"
app:layout_constraintVertical_bias="0.482" />
</android.support.constraint.ConstraintLayout>
ACTIVITY PAGE1
package com.example.principale.designazioni;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Page1 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page1);
EditText mail = (EditText) findViewById(R.id.editTextMail);
EditText nome = (EditText) findViewById(R.id.editTextNome);
EditText cognome = (EditText) findViewById(R.id.editTextCognome);
EditText tessera = (EditText) findViewById(R.id.editTextTessera);
Button avanti = (Button) findViewById(R.id.buttInvia);
Bundle bundle = new Bundle();
bundle.putString("mail", mail.getText().toString());
bundle.putString("nome", nome.getText().toString());
bundle.putString("cognome", cognome.getText().toString());
bundle.putString("tessera", tessera.getText().toString());
avanti.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openActivityPage2();
}
});
}
public void openActivityPage2() {
Intent intent = new Intent (getApplicationContext(), Page2.class);
startActivity(intent);
}
}
XML ACTIVITY PAGE1
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Page1">
<TextView
android:id="#+id/textView3"
android:layout_width="71dp"
android:layout_height="27dp"
android:fontFamily="monospace"
android:text="E-Mail"
android:textAlignment="textStart"
android:textColor="#android:color/holo_orange_dark"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.093"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.06" />
<TextView
android:id="#+id/textView4"
android:layout_width="96dp"
android:layout_height="27dp"
android:fontFamily="monospace"
android:text="Cognome"
android:textAlignment="textStart"
android:textColor="#android:color/holo_orange_dark"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.102"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.44" />
<TextView
android:id="#+id/textView6"
android:layout_width="71dp"
android:layout_height="27dp"
android:fontFamily="monospace"
android:text="Numero di Tessera"
android:textAlignment="textStart"
android:textColor="#android:color/holo_orange_dark"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.093"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.629" />
<TextView
android:id="#+id/textView5"
android:layout_width="71dp"
android:layout_height="27dp"
android:fontFamily="monospace"
android:text="Nome"
android:textAlignment="textStart"
android:textColor="#android:color/holo_orange_dark"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.093"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.251" />
<EditText
android:id="#+id/editTextMail"
android:layout_width="306dp"
android:layout_height="50dp"
android:ems="10"
android:fontFamily="monospace"
android:inputType="textEmailAddress"
android:textColor="#android:color/background_light"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView3"
app:layout_constraintVertical_bias="0.0" />
<EditText
android:id="#+id/editTextCognome"
android:layout_width="306dp"
android:layout_height="50dp"
android:ems="10"
android:inputType="textPersonName"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/editTextNome"
app:layout_constraintVertical_bias="0.17" />
<EditText
android:id="#+id/editTextNome"
android:layout_width="306dp"
android:layout_height="50dp"
android:ems="10"
android:inputType="textPersonName"
app:layout_constraintBottom_toTopOf="#+id/textView4"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView5"
app:layout_constraintVertical_bias="0.0" />
<EditText
android:id="#+id/editTextTessera"
android:layout_width="306dp"
android:layout_height="50dp"
android:ems="10"
android:inputType="number"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView6"
app:layout_constraintVertical_bias="0.0" />
<Button
android:id="#+id/button"
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="monospace"
android:text="Avanti"
android:textAlignment="center"
android:textColor="#android:color/holo_orange_dark"
android:textSize="36sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/editTextTessera"
app:layout_constraintVertical_bias="0.487" />
</android.support.constraint.ConstraintLayout>
ACTIVITY PAGE2
package com.example.principale.designazioni;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class Page2 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page2);
final TextView nome = (TextView) findViewById(R.id.textViewPage2);
Bundle bundle = this.getIntent().getExtras();
nome.setText(bundle.getString("nome"));
}
}
XML ACTIVITY PAGE2
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Page2">
<TextView
android:id="#+id/textViewPage2"
android:layout_width="180dp"
android:layout_height="47dp"
android:fontFamily="monospace"
android:text="TextView"
android:textAlignment="center"
android:textColor="#android:color/holo_orange_dark"
android:textSize="30sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
ANDROID MANIFEST
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.principale.designazioni">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Page1" />
<activity android:name=".Page2"></activity>
</application>
</manifest>
STACK TRACE
08-24 10:21:07.370 6819-6819/com.example.principale.designazioni E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.principale.designazioni, PID: 6819
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.principale.designazioni/com.example.principale.designazioni.Page1}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3194)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3302)
at android.app.ActivityThread.-wrap12(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1891)
at android.os.Handler.dispatchMessage(Handler.java:108)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7425)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.principale.designazioni.Page1.onCreate(Page1.java:30)
at android.app.Activity.performCreate(Activity.java:7372)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1218)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3147)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3302) 
at android.app.ActivityThread.-wrap12(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1891) 
at android.os.Handler.dispatchMessage(Handler.java:108) 
at android.os.Looper.loop(Looper.java:166) 
at android.app.ActivityThread.main(ActivityThread.java:7425) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921) 
Change this line in Page1.java
from
Button avanti = (Button) findViewById(R.id.buttInvia);
to
Button avanti = (Button) findViewById(R.id.button);

Simple App Crashes

Hey so I'm building a math game from an educational book. I had asked a similar question, and uninstalling then reinstalling android helped, the same code ran. Now, I've gotten further in the code and can't seem to find an error. I have a feeling it may be the placement of my setQuestion() method in the onClick method of the GameActivity.java. Also, the score and level elements aren't updating, not sure if that's part of the problem, but I feel like the code is just crashing before it updates them. If runs (in both an emulator and on my phone) until the user selects an answer, and then it crashes. Here is my code:
activity_main.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:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.baylamafia.snzyt.mathgamechapter2.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="My Math Game"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30sp" />
<ImageView
android:layout_width="150dp"
android:layout_height="150dp"
android:id="#+id/imageView"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Play"
android:id="#+id/buttonPlay"
android:layout_centerVertical="true"
android:layout_alignEnd="#+id/button2"
android:layout_alignStart="#+id/button2" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="High Scores"
android:id="#+id/button2"
android:layout_below="#+id/buttonPlay"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Quit"
android:id="#+id/button3"
android:layout_below="#+id/button2"
android:layout_alignStart="#+id/button2"
android:layout_alignEnd="#+id/button2" />
MainActivity.java
package com.baylamafia.snzyt.mathgamechapter2;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonPlay = (Button)findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Intent i;
i = new Intent(this, GameActivity.class);
startActivity(i);
}
}
activity_game.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:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.baylamafia.snzyt.mathgamechapter2.GameActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="2"
android:id="#+id/textPartA"
android:textSize="70sp"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_alignBottom="#+id/textOperator" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="x"
android:id="#+id/textOperator"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="70sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="2"
android:id="#+id/textPartB"
android:textSize="70sp"
android:layout_alignTop="#+id/textOperator"
android:layout_alignParentEnd="true"
android:layout_alignBottom="#+id/textOperator" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="="
android:id="#+id/textView2"
android:textIsSelectable="true"
android:layout_below="#+id/textOperator"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="3"
android:id="#+id/buttonChoice1"
android:layout_alignTop="#+id/buttonChoice2"
android:layout_toStartOf="#+id/buttonChoice2"
android:textSize="40sp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="4"
android:id="#+id/buttonChoice2"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="164dp"
android:textSize="40sp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="7"
android:id="#+id/buttonChoice3"
android:layout_alignTop="#+id/buttonChoice2"
android:layout_toEndOf="#+id/buttonChoice2"
android:textSize="40sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Score: 999"
android:id="#+id/textScore"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Level: 4"
android:id="#+id/textLevel"
android:layout_alignTop="#+id/textScore"
android:layout_alignEnd="#+id/textPartB" />
GameActivity.java
package com.baylamafia.snzyt.mathgamechapter2;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.util.Random;
public class GameActivity extends AppCompatActivity implements View.OnClickListener{
int correctAnswer;
Button buttonObjectChoice1;
Button buttonObjectChoice2;
Button buttonObjectChoice3;
TextView textObjectPartA;
TextView textObjectPartB;
TextView textObjectScore;
TextView textObjectLevel;
int currentScore = 0;
int currentLevel = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
/*here we get a working object based on either the button or TextView class and base as well
as link our new objects directly to the appropriate UI elements that we created previously
*/
textObjectPartA =
(TextView)findViewById(R.id.textPartA);
textObjectPartB =
(TextView)findViewById(R.id.textPartB);
buttonObjectChoice1 =
(Button)findViewById(R.id.buttonChoice1);
buttonObjectChoice2 =
(Button)findViewById(R.id.buttonChoice2);
buttonObjectChoice3 =
(Button)findViewById(R.id.buttonChoice3);
buttonObjectChoice1.setOnClickListener(this);
buttonObjectChoice2.setOnClickListener(this);
buttonObjectChoice3.setOnClickListener(this);
setQuestion();
}
void setQuestion(){
//generate the parts of the question
int numberRange = currentLevel * 3;
Random randInt = new Random();
int partA = randInt.nextInt(numberRange);
partA++;
int partB = randInt.nextInt(numberRange);
partB++;
correctAnswer = partA * partB;
int wrongAnswer1 = correctAnswer-2;
int wrongAnswer2 = correctAnswer+2;
textObjectPartA.setText(""+partA);
textObjectPartB.setText(""+partB);
//set the multi choice button
int buttonLayout = randInt.nextInt(3);
switch (buttonLayout){
case 0:
buttonObjectChoice1.setText(""+correctAnswer);
buttonObjectChoice2.setText(""+wrongAnswer1);
buttonObjectChoice3.setText(""+wrongAnswer2);
break;
case 1:
buttonObjectChoice1.setText(""+wrongAnswer1);
buttonObjectChoice2.setText(""+correctAnswer);
buttonObjectChoice3.setText(""+wrongAnswer2);
break;
case 2:
buttonObjectChoice1.setText(""+wrongAnswer1);
buttonObjectChoice2.setText(""+wrongAnswer2);
buttonObjectChoice3.setText(""+correctAnswer);
break;
}
}
void updateScoreAndLevel (int answerGiven) {
if(isCorrect(answerGiven)){
for(int i = 1; i < currentLevel; i++){
currentScore = currentScore + i;
}
currentLevel++;
}else{
currentScore = 0;
currentLevel = 1;
}
textObjectScore.setText("Score: " + currentScore);
textObjectLevel.setText("Level: " + currentLevel);
}
boolean isCorrect(int answerGiven){
boolean correctTrueOrFalse;
if (answerGiven == correctAnswer){
Toast.makeText(getApplicationContext(), "Well done!", Toast.LENGTH_LONG).show();
correctTrueOrFalse=true;
}else{
Toast.makeText(getApplicationContext(), "Sorry", Toast.LENGTH_LONG).show();
correctTrueOrFalse=false;
}
return correctTrueOrFalse;
}
#Override
public void onClick(View view){
int answerGiven = 0;
switch (view.getId()) {
case R.id.buttonChoice1:
answerGiven = Integer.parseInt("" + buttonObjectChoice1.getText());
break;
case R.id.buttonChoice2:
answerGiven = Integer.parseInt("" + buttonObjectChoice2.getText());
break;
case R.id.buttonChoice3:
answerGiven = Integer.parseInt("" + buttonObjectChoice3.getText());
break;
}
updateScoreAndLevel(answerGiven);
setQuestion();
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.baylamafia.snzyt.mathgamechapter2">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".GameActivity"></activity>
</application>
Don't use getApplicationContext here:
Toast.makeText(getApplicationContext(), "Well done!", Toast.LENGTH_LONG).show();
Use this to use the current activity:
Toast.makeText(this, "Well done!", Toast.LENGTH_LONG).show();
Difference between getContext() , getApplicationContext() , getBaseContext() and "this"
For starters, get rid of all these extraneous ""+ they serve no purpose. You are adding nothing to the string:
buttonObjectChoice1.setText(""+correctAnswer);
answerGiven = Integer.parseInt("" + buttonObjectChoice1.getText());
Also this
answerGiven = Integer.parseInt("" + buttonObjectChoice1.getText());
will fail if there is not the correct input i.e. int.
Also, I'm not sure what you are using this for import org.w3c.dom.Text.

when I click on Register here, it does not go to the next activity

when I click on Logout button it goes to the next activity but, On the next activity when I click on the "Register here" to go to the next activity it says unfortunately , Login has stopped. Please help me out.
Main Activity
package com.example.namrata.login;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button blogout;
EditText uname1, name1, age1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uname1 =(EditText) findViewById(R.id.uname1);
name1 = (EditText) findViewById(R.id.name1);
age1 = (EditText) findViewById(R.id.age1);
blogout = (Button) findViewById(R.id.blogout);
blogout.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()){
case R.id.blogout:
startActivity(new Intent(this, Login.class));
break;
}
}
}
Login Activity
package com.example.namrata.login;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Login extends AppCompatActivity implements View.OnClickListener {
Button blogin;
EditText uname, pass;
TextView registerLink;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
uname =(EditText) findViewById(R.id.uname);
pass = (EditText) findViewById(R.id.pass);
registerLink = (TextView) findViewById(R.id.registerLink);
blogin = (Button) findViewById(R.id.blogin);
blogin.setOnClickListener(this);
registerLink.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.registerLink:
startActivity(new Intent(this, Register.class));
break;
case R.id.blogin:
break;
}
}
}
Register Acitvity
package com.example.namrata.login;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Register extends AppCompatActivity implements View.OnClickListener {
Button bregister;
EditText uname2, pass1, name2, age2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
uname2 =(EditText) findViewById(R.id.uname2);
pass1 = (EditText) findViewById(R.id.pass1);
name2 = (EditText) findViewById(R.id.name2);
age2 = (EditText) findViewById(R.id.age2);
bregister = (Button) findViewById(R.id.blogin);
bregister.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()){
case R.id.bregister:
break;
}
}
}
activity_login layout file
<?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:orientation="vertical"
android:padding="10dp"
android:background="#28e317"
android:backgroundTint="#ffffff">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Username"
android:id="#+id/username"
android:textSize="20dp"
android:textStyle="bold" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:id="#+id/uname"
android:layout_marginBottom="15dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"
android:id="#+id/password"
android:textSize="20dp"
android:textStyle="bold"
android:background="#ffffff" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="#+id/pass"
android:layout_marginBottom="15dp"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:id="#+id/blogin"
android:layout_gravity="center_horizontal"
android:background="#7c82f9"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Register Here."
android:id="#+id/registerLink"
android:layout_gravity="center_horizontal"
android:textSize="20dp"
android:textStyle="italic" />
activity_main layout file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:id="#+id/name"
android:textSize="20dp"
android:textStyle="bold" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:ems="10"
android:id="#+id/name2"
android:layout_marginBottom="15dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Age"
android:id="#+id/age"
android:textSize="20dp"
android:textStyle="bold"
android:background="#ffffff" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/age2"
android:layout_marginBottom="15dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Username"
android:id="#+id/username1"
android:textSize="20dp"
android:textStyle="bold"
android:background="#ffffff" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:id="#+id/uname2"
android:layout_marginBottom="15dp"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Logout"
android:id="#+id/blogout"
android:layout_gravity="center_horizontal"
android:background="#7c82f9"
android:layout_marginTop="20dp"/>
activity_register layout file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp"
android:background="#28e317"
android:backgroundTint="#ffffff">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:id="#+id/name"
android:textSize="20dp"
android:textStyle="bold" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:ems="10"
android:id="#+id/name1"
android:layout_marginBottom="15dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Age"
android:id="#+id/age"
android:textSize="20dp"
android:textStyle="bold"
android:background="#ffffff" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/age1"
android:layout_marginBottom="15dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Username"
android:id="#+id/username1"
android:textSize="20dp"
android:textStyle="bold"
android:background="#ffffff" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:id="#+id/uname1"
android:layout_marginBottom="15dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"
android:id="#+id/password1"
android:textSize="20dp"
android:textStyle="bold"
android:background="#ffffff" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="#+id/pass1"
android:layout_marginBottom="15dp"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Register"
android:id="#+id/bregister"
android:layout_gravity="center_horizontal"
android:background="#7c82f9"
android:layout_marginTop="20dp"/>
Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.namrata.login">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Login"
android:label="#string/title_activity_login"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".Register"
android:label="#string/title_activity_register"
android:theme="#style/AppTheme.NoActionBar"></activity>
</application>
In register activity xml you have android:id="#+id/bregister"
but in RegisterActivity you searching for login button
bregister = (Button) findViewById(R.id.blogin);
which is null that is why you are getting null pointer exception i think change it to
bregister = (Button) findViewById(R.id.bregister);
In your layout file for register activity (activity_register) you have:
android:id="#+id/bregister"
but in Register Activity.java you're doing:
bregister = (Button) findViewById(R.id.blogin);
so register is set to null. Hence it crashes on:
bregister.setOnClickListener(this);
Your onClick method in MainActivity is not the overrided one that's why it's not getting called automatically.Create it as you have create onClick method in LoginActivity
In your First Activity class MainActivity you are using this layout class
setContentView(R.layout.activity_main)
You should use
setContentView(R.layout.activity_login)
and in this activity_login layout you should
change TextView is Register here To Button
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Register Here."
android:id="#+id/registerLink"
android:layout_gravity="center_horizontal"
android:textSize="20dp"
android:textStyle="italic" />
Remove this and use button instead of TextView.

The app I am working on crashes when i try to go from one intent to the other, I've tried everything. code:

The Start class:
It as a very simple program, i designed two screen, and by pressing a button on the main screen i wanted the app to open the second screen, but unfortunately its not happening, the app keeps crushing over and over again.
package com.example.snakesnladders;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class Start extends Activity implements OnClickListener {
Button start, settings;
TextView snakes, and, ladders;
ImageView snakePic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainscreen);
init();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
private void init() {
start = (Button) findViewById(R.id.btStart);
settings = (Button) findViewById(R.id.btSettings);
snakes = (TextView) findViewById(R.id.tvSnakes);
and = (TextView) findViewById(R.id.tvAnd);
ladders = (TextView) findViewById(R.id.tvLadders);
snakePic = (ImageView) findViewById(R.id.snakePic);
start.setOnClickListener(this);
settings.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btStart:
break;
case R.id.btSettings:
Intent i = new Intent("com.example.snakesnladders.SET");
startActivity(i);
break;
default: break;
}
}
}
The Set class:
package com.example.snakesnladders;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class Set extends Activity implements OnClickListener {
Button sound, difficulty, back;
TextView settings;
ImageView snakePic;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.setscreen);
init();
}
private void init() {
sound = (Button) findViewById(R.id.btSound);
difficulty = (Button) findViewById(R.id.btDifficulty);
back = (Button) findViewById(R.id.btBack);
settings = (TextView) findViewById(R.id.tvSetPage);
snakePic = (ImageView) findViewById(R.id.setSnakePic);
sound.setOnClickListener(this);
difficulty.setOnClickListener(this);
back.setOnClickListener(this);
}
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
switch (view.getId()) {
case R.id.btSound:
String s = sound.getText().toString();
if (s.equals("Sound:on")) {
sound.setText("Sound:off");
ControlSounds.player.stop();
} else {
sound.setText("Sound:on");
ControlSounds.player.start();
}
break;
case R.id.btDifficulty:
break;
case R.id.btBack:
Intent i = new Intent(Set.this, Start.class);
startActivity(i);
finish();
break;
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}
The manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.snakesnladders"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Start"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Set"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.example.snakesnladders.SET" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
mainscreen.xml:
<?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="#color/black"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="175dp"
android:orientation="vertical" >
<TextView
android:id="#+id/tvSnakes"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_gravity="center"
android:text="Snakes"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/green"
android:textSize="30sp" />
<TextView
android:id="#+id/tvAnd"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_gravity="center"
android:text="#string/and"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/green"
android:textSize="30sp" />
<TextView
android:id="#+id/tvLadders"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_gravity="center"
android:text="Ladders"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/green"
android:textSize="30sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="125dp"
android:orientation="vertical" >
<Button
android:id="#+id/btStart"
android:layout_width="250dp"
android:layout_height="60dp"
android:layout_gravity="center"
android:background="#drawable/buttonshape"
android:shadowColor="#A8A8A8"
android:shadowDx="0"
android:shadowDy="0"
android:shadowRadius="10"
android:text="Start New Game"
android:textColor="#FFFFFF"
android:textSize="30sp" />
<Button
android:id="#+id/btSettings"
android:layout_width="250dp"
android:layout_height="60dp"
android:layout_gravity="center"
android:background="#drawable/buttonshape"
android:shadowColor="#A8A8A8"
android:shadowDx="0"
android:shadowDy="0"
android:shadowRadius="10"
android:text="Settings"
android:textColor="#FFFFFF"
android:textSize="30sp" />
</LinearLayout>
<ImageView
android:id="#+id/snakePic"
android:layout_width="wrap_content"
android:layout_height="125dp"
android:layout_gravity="center"
android:layout_weight="0.47"
android:background="#color/black"
android:src="#drawable/snake" />
</LinearLayout>
setscreen.xml:
<?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="#color/black"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/black"
android:orientation="vertical" >
<TextView
android:id="#+id/tvSetPage"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_gravity="center"
android:text="Settings"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/green"
android:textSize="40sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/black"
android:orientation="vertical" >
<Button
android:id="#+id/btSound"
android:layout_width="250dp"
android:layout_height="60dp"
android:layout_gravity="center"
android:background="#drawable/buttonshape"
android:shadowColor="#A8A8A8"
android:shadowDx="0"
android:shadowDy="0"
android:shadowRadius="10"
android:text="Sound:on"
android:textColor="#FFFFFF"
android:textSize="30sp" />
<Button
android:id="#+id/btDifficulty"
android:layout_width="250dp"
android:layout_height="60dp"
android:layout_gravity="center"
android:background="#drawable/buttonshape"
android:shadowColor="#A8A8A8"
android:shadowDx="0"
android:shadowDy="0"
android:shadowRadius="10"
android:text="Difficulty:easy"
android:textColor="#FFFFFF"
android:textSize="30sp" />
<Button
android:id="#+id/btBack"
android:layout_width="250dp"
android:layout_height="60dp"
android:layout_gravity="center"
android:background="#drawable/buttonshape"
android:shadowColor="#A8A8A8"
android:shadowDx="0"
android:shadowDy="0"
android:shadowRadius="10"
android:text="Back To Menu"
android:textColor="#FFFFFF"
android:textSize="30sp" />
</LinearLayout>
<ImageView
android:id="#+id/setSnakePic"
android:layout_width="wrap_content"
android:layout_gravity="center"
android:layout_weight="0.25"
android:background="#color/black"
android:src="#drawable/snake1" />
</LinearLayout>
Change this
Intent i = new Intent("com.example.snakesnladders.SET");
startActivity(i);
To
Intent i = new Intent(Start.this,Set.class);
startActivity(i);
And Change this
<activity
android:name=".Set"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.example.snakesnladders.SET" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
To
<activity
android:name=".Set"
android:label="#string/app_name" >
</activity>
Use Explicit Intent's
To know why read
http://developer.android.com/guide/components/intents-filters.html
Explicit intents specify the component to start by name (the
fully-qualified class name). You'll typically use an explicit intent
to start a component in your own app, because you know the class name
of the activity or service you want to start. For example, start a new
activity in response to a user action or start a service to download a
file in the background.

Categories

Resources