FATAL EXCEPTION: main....java.lang.RuntimeException: Unable to instantiate activity ComponentInfo.? [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm very new to Android Studio and I know a little java.So I'm trying a simple calculator app with simple layout.I hope all my code is correct but I don't know what's wrong in it.When I run the app it is not at all opening and showing a FATAL exception main.Here is the xml code,java code and logcat of my app.So please help me to make corrections.Thanks!
XML Code ::
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayoutxmlns: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:background="#color/colorPrimary"
tools:context="com.example.narendra.calculator.MainActivity"
tools:layout_editor_absoluteY="81dp"
tools:layout_editor_absoluteX="0dp">
<EditText
android:id="#+id/editText"
android:layout_width="360dp"
android:layout_height="159dp"
android:background="#android:color/holo_blue_light"
android:ems="10"
android:hint="#string/num"
android:inputType="number"
android:textAlignment="center"
android:textAllCaps="true"
android:textSize="50sp"
android:textStyle="bold"
tools:ignore="MissingConstraints,RtlHardcoded"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="16dp"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginRight="8dp"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp" />
<EditText
android:id="#+id/editText2"
android:layout_width="360dp"
android:layout_height="159dp"
android:background="#android:color/holo_green_light"
android:ems="10"
android:hint="#string/Num2"
android:inputType="number"
android:textAlignment="center"
android:textAllCaps="true"
android:textSize="50sp"
android:textStyle="bold"
tools:ignore="MissingConstraints,RtlHardcoded"
tools:layout_editor_absoluteY="180dp"
tools:layout_editor_absoluteX="26dp" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onAddButtonClick"
android:text="#string/a"
android:textSize="50sp"
app:layout_constraintLeft_toLeftOf="#+id/editText2"
app:layout_constraintTop_toTopOf="#+id/editText"
android:layout_marginTop="323dp"
tools:ignore="RtlHardcoded"
app:layout_constraintRight_toLeftOf="#+id/button3"
app:layout_constraintHorizontal_bias="0.0"
android:layout_marginRight="5dp"
android:layout_marginEnd="5dp" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onSubtractionButtonClick"
android:text="#string/m"
android:textSize="50sp"
android:layout_marginLeft="5dp"
app:layout_constraintTop_toTopOf="#+id/editText"
android:layout_marginTop="323dp"
tools:ignore="RtlHardcoded"
app:layout_constraintLeft_toRightOf="#+id/button"
app:layout_constraintHorizontal_bias="0.03"
android:layout_marginRight="5dp"
app:layout_constraintRight_toRightOf="#+id/button3"
android:layout_marginStart="5dp"
android:layout_marginEnd="5dp" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onMultiplicationButtonClick"
android:text="#string/p"
android:textSize="50sp"
android:layout_marginLeft="5dp"
app:layout_constraintTop_toTopOf="#+id/editText"
android:layout_marginTop="323dp"
tools:ignore="RtlHardcoded"
app:layout_constraintLeft_toRightOf="#+id/button2"
android:layout_marginRight="5dp"
app:layout_constraintRight_toRightOf="#+id/button4"
app:layout_constraintHorizontal_bias="0.0"
android:layout_marginStart="5dp"
android:layout_marginEnd="5dp" />
<Button
android:id="#+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onDivisionButtonClick"
android:text="#string/d"
android:textSize="50sp"
android:layout_marginLeft="5dp"
app:layout_constraintRight_toRightOf="#+id/editText2"
app:layout_constraintTop_toTopOf="#+id/editText"
android:layout_marginTop="323dp"
tools:ignore="RtlHardcoded"
app:layout_constraintLeft_toRightOf="#+id/button3"
app:layout_constraintHorizontal_bias="0.0"
android:layout_marginStart="5dp"
android:layout_marginRight="5dp" />
<TextView
android:id="#+id/textView"
android:layout_width="360dp"
android:layout_height="100dp"
android:layout_marginBottom="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="16dp"
android:layout_marginTop="8dp"
android:background="#color/colorAccent"
android:text="#string/Result"
android:textAlignment="center"
android:textAllCaps="true"
android:textSize="50sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.771"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.839"
tools:ignore="RtlHardcoded" />
Java Code ::
package com.example.narendra.calculator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
EditText e1=(EditText)findViewById(R.id.editText);
EditText e2=(EditText)findViewById(R.id.editText2);
TextView t1=(TextView)findViewById(R.id.textView);
int num1=Integer.parseInt(e1.getText().toString());
int num2=Integer.parseInt(e2.getText().toString());
public void conditionCheck(){
if(e1.getText().toString().isEmpty()){
e1.setError("Please Enter a valid number");
}
else if(e2.getText().toString().isEmpty()){
e2.setError("Please Enter a valid number");
}
}
public void onAddButtonClick(View v){
conditionCheck();
int sum=num1+num2;
t1.setText(sum);
Toast.makeText(MainActivity.this, " Thank You ", Toast.LENGTH_SHORT).show();
}
public void onSubtractionButtonClick(View v){
conditionCheck();
int diff=num1-num2;
t1.setText(diff);
Toast.makeText(MainActivity.this, " Thank You ", Toast.LENGTH_SHORT).show();
}
public void onMultiplicationButtonClick(View v){
conditionCheck();
int product=num1*num2;
t1.setText(product);
Toast.makeText(MainActivity.this, " Thank You ", Toast.LENGTH_SHORT).show();
}
public void onDivisionButtonClick(View v){
conditionCheck();
if(num2==0){
e2.setError(" Zero is not allowed here");
}
else {
int quotient = num1 / num2;
t1.setText(quotient);
Toast.makeText(MainActivity.this, " Thank You ", Toast.LENGTH_SHORT).show();
}
}
}
Logcat ::
06-14 12:31:23.216 4822-4822/? I/art: Not late-enabling -Xcheck:jni (already on)
06-14 12:31:23.216 4822-4822/? W/art: Unexpected CPU variant for X86 using defaults: x86
06-14 12:31:23.342 4822-4822/? W/System: ClassLoader referenced unknown path: /data/app/com.example.narendra.calculator-2/lib/x86
06-14 12:31:23.348 4822-4822/? I/InstantRun: starting instant run server: is main process
06-14 12:31:23.405 4822-4822/? D/AndroidRuntime: Shutting down VM
06-14 12:31:23.405 4822-4822/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.narendra.calculator, PID: 4822
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.narendra.calculator/com.example.narendra.calculator.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2548)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:120)
at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:155)
at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:31)
at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:55)
at android.support.v7.app.AppCompatDelegateImplV23.<init>(AppCompatDelegateImplV23.java:33)
at android.support.v7.app.AppCompatDelegateImplN.<init>(AppCompatDelegateImplN.java:33)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:201)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:185)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:519)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:190)
at com.example.narendra.calculator.MainActivity.<init>(MainActivity.java:17)
at java.lang.Class.newInstance(Native Method)
at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2538)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756) 

Your onCreate() is closed early
Change it to
package com.example.narendra.calculator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText e1,e2;
int num1,num2;
TextView t1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1 = (EditText) findViewById(R.id.editText);
e2 = (EditText) findViewById(R.id.editText2);
t1 = (TextView) findViewById(R.id.textView);
num1 = Integer.parseInt(e1.getText().toString());
num2 = Integer.parseInt(e2.getText().toString());
} public void conditionCheck(){
if(e1.getText().toString().isEmpty()){
e1.setError("Please Enter a valid number");
}
else if(e2.getText().toString().isEmpty()){
e2.setError("Please Enter a valid number");
}
}
public void onAddButtonClick(View v){
conditionCheck();
int sum=num1+num2;
t1.setText(sum);
Toast.makeText(MainActivity.this, " Thank You ", Toast.LENGTH_SHORT).show();
}
public void onSubtractionButtonClick(View v){
conditionCheck();
int diff=num1-num2;
t1.setText(diff);
Toast.makeText(MainActivity.this, " Thank You ", Toast.LENGTH_SHORT).show();
}
public void onMultiplicationButtonClick(View v){
conditionCheck();
int product=num1*num2;
t1.setText(product);
Toast.makeText(MainActivity.this, " Thank You ", Toast.LENGTH_SHORT).show();
}
public void onDivisionButtonClick(View v){
conditionCheck();
if(num2==0){
e2.setError(" Zero is not allowed here");
}
else {
int quotient = num1 / num2;
t1.setText(quotient);
Toast.makeText(MainActivity.this, " Thank You ", Toast.LENGTH_SHORT).show();
}
}
}

Just modify the code of (view init) position,
like this:
MainActivity{
onCreate(){
View view = findViewById(id);
}
}
Note: the Activity is a component that has self life-cycle. so can't apply it as a simple Pojo

Related

Why is it giving me a "unfortunatley <app name > has ended" when I run the app on an external device

im building an app in android studio, and on my MainActivity, i have a button that when clicked leads to another activity. However, when i ran it on the actual external device, I got the message that it has unfortunatley stopped. However, on the virtual device, it works perfectly fine. Does anyone know what's happening?
This Is my Main Activity Code
public class MainActivity extends AppCompatActivity {
TextView greeting;
Button click;
Button slope;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//when the surprise button is clicked
greeting = (TextView) findViewById(R.id.tVGreeting);
click = (Button) findViewById(R.id.btnClick);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
greeting.setVisibility(View.VISIBLE); //make the result visible
}
});
//when the slope formula button is clicked
slope = (Button) findViewById(R.id.slopeBtn);
slope.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goToMathGraphical(); //go to the slope Activity
}
});
}
//button goes to new activity.
private void goToMathGraphical()
{
Intent intent = new Intent(MainActivity.this, ScrollMathGraph.class);
startActivity(intent);
}
This is the MainActivity XML file
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/tV"
android:layout_width="wrap_content"
android:layout_height="105dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:text="Welcome to the Fornula App!"
android:textSize="36sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.439"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.183" />
<Button
android:id="#+id/btnClick"
android:layout_width="112dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:text="SUPRISE"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.455"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tV"
app:layout_constraintVertical_bias="0.728" />
<TextView
android:id="#+id/tVGreeting"
android:layout_width="224dp"
android:layout_height="83dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:text="Good Morning"
android:textSize="20sp"
android:visibility="invisible"
app:layout_constraintBottom_toTopOf="#+id/btnClick"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.44"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/tV"
app:layout_constraintVertical_bias="0.525" />
<Button
android:id="#+id/slopeBtn"
android:layout_width="204dp"
android:layout_height="68dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:text="GRAPHICAL FORMULAS"
android:textAppearance="#style/TextAppearance.AppCompat.Large"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.46"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/btnClick"
app:layout_constraintVertical_bias="0.293" />
</android.support.constraint.ConstraintLayout>
This is the ScrollMathGraph class
package com.example.formulaapp;
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.view.View;
import android.widget.Button;
import android.widget.Toast;
public class ScrollMathGraph extends AppCompatActivity {
Button slope2d;
Button distance2d;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scroll_math_graph);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Let us Know If we are missing any Formulas", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"xxxx#yahoo.com" , "xxx#gmail.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "New Formula not in App");
i.putExtra(Intent.EXTRA_TEXT , "Hello! please let us know what formula we are missing! Thank you!");
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(ScrollMathGraph.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
});
slope2d = (Button) findViewById(R.id.Slope2D);
slope2d.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goToSlopeActivity(); //go to the slope Activity
}
});
distance2d = (Button) findViewById(R.id.Distance2D);
distance2d.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goToDistance2DActivity(); //go to the slope Activity
}
});
}
//button goes to new activity.
private void goToSlopeActivity()
{
Intent intent = new Intent(ScrollMathGraph.this, SlopeFormula.class);
startActivity(intent);
}
//button goes to new activity.
private void goToDistance2DActivity()
{
Intent intent = new Intent(ScrollMathGraph.this, Distance2D.class);
startActivity(intent);
}
}
This is the ScrollMathGraph XML file
<?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=".ScrollMathGraph">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="#dimen/app_bar_height"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:background="#drawable/formulas"
android:fitsSystemWindows="true"
android:theme="#style/AppTheme.AppBarOverlay"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:toolbarId="#+id/toolbar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="#dimen/fab_margin"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
app:layout_anchor="#id/app_bar"
app:layout_anchorGravity="bottom|end"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.22"
app:srcCompat="#android:drawable/ic_dialog_email" />
<ScrollView
android:layout_width="409dp"
android:layout_height="535dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="#+id/tv2DTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=" 2D Graphical Formulas "
android:textSize="25sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/Slope2D"
android:layout_width="112dp"
android:layout_height="wrap_content"
android:text="2D Slope"
tools:layout_editor_absoluteX="16dp"
tools:layout_editor_absoluteY="214dp" />
<Button
android:id="#+id/Distance2D"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2D Distance"
tools:layout_editor_absoluteX="15dp"
tools:layout_editor_absoluteY="303dp" />
<Button
android:id="#+id/Midpoint2D"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2D Midpoint" />
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=" 3D Graphical Formulas"
android:textSize="25sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/Slope3D"
android:layout_width="108dp"
android:layout_height="wrap_content"
android:text="3D Slope" />
<Button
android:id="#+id/Distance3D"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="3D Distance" />
<Button
android:id="#+id/Midpoint3D"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="3D Midpoint" />
</LinearLayout>
</ScrollView>
</android.support.constraint.ConstraintLayout>
This is the error that I am getting
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.formulaapp, PID: 9888
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.formulaapp/com.example.formulaapp.ScrollMathGraph}: android.view.InflateException: Binary XML file line #9: Error inflating class android.support.design.widget.AppBarLayout
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
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:5017)
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: android.view.InflateException: Binary XML file line #9: Error inflating class android.support.design.widget.AppBarLayout
at android.view.LayoutInflater.createView(LayoutInflater.java:663)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:739)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:798)
at android.view.LayoutInflater.inflate(LayoutInflater.java:520)
at android.view.LayoutInflater.inflate(LayoutInflater.java:425)
at android.view.LayoutInflater.inflate(LayoutInflater.java:381)
at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.example.formulaapp.ScrollMathGraph.onCreate(ScrollMathGraph.java:19)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 
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:5017) 
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.reflect.InvocationTargetException
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at android.view.LayoutInflater.createView(LayoutInflater.java:637)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:739) 
at android.view.LayoutInflater.rInflate(LayoutInflater.java:798) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:520) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:425) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:381) 
at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469) 
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140) 
at com.example.formulaapp.ScrollMathGraph.onCreate(ScrollMathGraph.java:19) 
at android.app.Activity.performCreate(Activity.java:5231) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 
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:5017) 
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: android.content.res.Resources$NotFoundException: Resource is not a Drawable (color or path): TypedValue{t=0x1/d=0x7f070063 a=-1 r=0x7f070063}
at android.content.res.Resources.loadDrawable(Resources.java:2068)
at android.content.res.TypedArray.getDrawable(TypedArray.java:602)
at android.view.View.<init>(View.java:3554)
at android.view.ViewGroup.<init>(ViewGroup.java:470)
at android.widget.LinearLayout.<init>(LinearLayout.java:176)
at android.widget.LinearLayout.<init>(LinearLayout.java:172)
at android.support.design.widget.AppBarLayout.<init>(AppBarLayout.java:173)
at java.lang.reflect.Constructor.constructNative(Native Method) 
at java.lang.reflect.Constructor.newInstance(Constructor.java:423) 
at android.view.LayoutInflater.createView(LayoutInflater.java:637) 
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:739) 
at android.view.LayoutInflater.rInflate(LayoutInflater.java:798) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:520) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:425) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:381) 
at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469) 
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140) 
at com.example.formulaapp.ScrollMathGraph.onCreate(ScrollMathGraph.java:19) 
at android.app.Activity.performCreate(Activity.java:5231) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 
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:5017) 
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) 
I saw that this error pertained to one of the classes that I wrote
at com.example.formulaapp.ScrollMathGraph.onCreate(ScrollMathGraph.java:19)
Anyone know whats going on?
The AppBarLayout has a background drawable (android:background="#drawable/formulas") and the error message says specifically
Caused by: android.content.res.Resources$NotFoundException: Resource is not a Drawable (color or path): TypedValue{t=0x1/d=0x7f070063 a=-1 r=0x7f070063}
at android.content.res.Resources.loadDrawable(Resources.java:2068)
So since your app works fine on one device and crashes on another, it looks like you did not provide that drawable resource for every device type.
Without knowing more about your drawable resource folders, I can only suggest that you make sure that you have a version of the formulas drawable for every constellation.
More information on this topic can be found in the guide to Providing Resources

Spinner Selected Item getting NullpointerExceptionError [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I want to pass the value of the selected spinner item. In my activity there are 2 pairs of spinner and in every pair the second spinner is dependent on the value of the first spinner. As i need to pass the value to another activity, i took the values in different string variables and pass them to another activity. But the activity is maybe showing nullpointer execption in the Spinner.getSelectedItem().toString() method.
activityClass
package com.example.bohon_final__001;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.List;
public class SqlitemainActivity extends AppCompatActivity {
Spinner pickupspinner1,pickupspinner2,destspinner1,destspinner2;
Button selectbtn;
EditText inputLabel;
String pickdistrict,pickarea,destdistrict,destarea,vehicletype;
ArrayList<String>disarray;
ArrayAdapter<String>disarray_adapter;
ArrayList<String>sylhet,moulovibazar,sunamgonj,habiganj;
ArrayAdapter<String>area;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sqlitemain);
pickupspinner1 = (Spinner)findViewById(R.id.pickupspinner1);
pickupspinner2 = (Spinner)findViewById(R.id.pickupspinner2);
destspinner1=(Spinner)findViewById(R.id.destinationspinner1);
destspinner2=(Spinner)findViewById(R.id.destinationspinner2);
selectbtn=findViewById(R.id.selectbutton);
String vehicletype=getIntent().getStringExtra("vehicleType");
disarray=new ArrayList<>();
disarray.add("Sylhet");
disarray.add("Sunamgonj");
disarray.add("Moulovibazar");
disarray.add("Habiganj");
disarray_adapter=new ArrayAdapter<>(getApplicationContext(),android.R.layout.simple_spinner_item,disarray);
pickupspinner1.setAdapter(disarray_adapter);
destspinner1.setAdapter(disarray_adapter);
sylhet=new ArrayList<>();
sylhet.add("Sylhet Sadar");
sylhet.add("Dakshin Surma");
sylhet.add("Moglabazar");
sylhet.add("Kanaighat");
sylhet.add("Bishwanath");
sunamgonj=new ArrayList<>();
sunamgonj.add("Sunamganj Sadar");
sunamgonj.add("Chhatak");
sunamgonj.add("Jagannathpur");
sunamgonj.add("Jamalganj");
sunamgonj.add("Derai");
moulovibazar=new ArrayList<>();
moulovibazar.add("Barlekha");
moulovibazar.add("Kulawra");
moulovibazar.add("Moulovibazar Sadar");
moulovibazar.add("Rajnagar");
moulovibazar.add("Sreemongol");
habiganj=new ArrayList<>();
habiganj.add("Ajmiriganj");
habiganj.add("Baniachang");
habiganj.add("Bahubal");
habiganj.add("Chunarughat");
habiganj.add("Habiganj Sadar");
pickupspinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if(i==0)
{
area=new ArrayAdapter<>(getApplicationContext(),android.R.layout.simple_spinner_item,sylhet);
}
if(i==1)
{
area=new ArrayAdapter<>(getApplicationContext(),android.R.layout.simple_spinner_item,sunamgonj);
}
if(i==2)
{
area=new ArrayAdapter<>(getApplicationContext(),android.R.layout.simple_spinner_item,moulovibazar);
}
else
{
area=new ArrayAdapter<>(getApplicationContext(),android.R.layout.simple_spinner_item,habiganj);
}
pickupspinner2.setAdapter(area);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
destspinner1.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if(i==0)
{
area=new ArrayAdapter<>(getApplicationContext(),android.R.layout.simple_spinner_item,sylhet);
}
if(i==1)
{
area=new ArrayAdapter<>(getApplicationContext(),android.R.layout.simple_spinner_item,sunamgonj);
}
if(i==2)
{
area=new ArrayAdapter<>(getApplicationContext(),android.R.layout.simple_spinner_item,moulovibazar);
}
if(i==3)
{
area=new ArrayAdapter<>(getApplicationContext(),android.R.layout.simple_spinner_item,habiganj);
}
destspinner2.setAdapter(area);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
pickdistrict=pickupspinner1.getSelectedItem().toString();
pickarea=String.valueOf(pickupspinner2.getSelectedItem());
destdistrict=destspinner1.getSelectedItem().toString();
destarea=destspinner2.getSelectedItem().toString();
selectbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent submissionintent=new Intent(SqlitemainActivity.this,FinalRequestActivity.class);
submissionintent.putExtra("pickd",pickdistrict);
submissionintent.putExtra("picka",pickarea);
submissionintent.putExtra("desd",destdistrict);
submissionintent.putExtra("desa",destarea);
submissionintent.putExtra("vtype",vehicletype);
startActivity(submissionintent);
}
});
}
}
Activity Class Xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".SqlitemainActivity"
android:orientation="vertical"
android:background="#000000"
>
<TextView
android:layout_width="230dp"
android:layout_height="wrap_content"
android:text="Select Your District:"
android:layout_marginStart="0dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="50dp"
android:textStyle="italic"
android:textColor="#F44336"
android:textSize="15sp"
/>
<TextView
android:layout_width="171dp"
android:layout_height="wrap_content"
android:text="Area:"
android:layout_marginStart="0dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="120dp"
android:textStyle="italic"
android:textColor="#F44336"
android:textSize="15sp"
/>
<TextView
android:id="#+id/pickuplocationtext"
android:layout_width="355dp"
android:layout_height="wrap_content"
android:layout_marginVertical="20dp"
android:text="Select your Pickup Location"
android:textColor="#color/yellow"
android:textSize="20sp"
android:textStyle="bold" />
<Spinner
android:id="#+id/pickupspinner1"
android:layout_width="253dp"
android:layout_height="37dp"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_marginStart="0dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="70dp"
android:background="#FF8100" />
<Spinner
android:id="#+id/pickupspinner2"
android:layout_width="203dp"
android:layout_height="30dp"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_marginStart="0dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="150dp"
android:background="#FF8100" />
<Button
android:id="#+id/selectbutton"
android:layout_width="214dp"
android:layout_height="63dp"
android:layout_marginLeft="90dp"
android:layout_marginTop="600dp"
android:background="#drawable/selectart"
android:text="" />
<TextView
android:id="#+id/destlocationtext"
android:layout_width="355dp"
android:layout_height="wrap_content"
android:layout_marginVertical="230dp"
android:text="Select your Destination Location"
android:textColor="#color/yellow"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:layout_width="230dp"
android:layout_height="wrap_content"
android:text="Select Your District:"
android:layout_marginStart="0dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="260dp"
android:textStyle="italic"
android:textColor="#F44336"
android:textSize="15sp"
/>
<TextView
android:layout_width="171dp"
android:layout_height="wrap_content"
android:text="Area:"
android:layout_marginStart="0dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="320dp"
android:textStyle="italic"
android:textColor="#F44336"
android:textSize="15sp"
/>
<Spinner
android:id="#+id/destinationspinner1"
android:layout_width="251dp"
android:layout_height="37dp"
android:layout_marginStart="0dp"
android:background="#FF8100"
android:layout_marginLeft="0dp"
android:layout_marginTop="280dp" />
<Spinner
android:id="#+id/destinationspinner2"
android:layout_width="199dp"
android:layout_height="31dp"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_marginStart="0dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="350dp"
android:background="#FF8100" />
</RelativeLayout>
Here are the errors I'm getting
Process: com.example.bohon_final__001, PID: 1417
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bohon_final__001/com.example.bohon_final__001.SqlitemainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2952)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3087)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1817)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6746)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
at com.example.bohon_final__001.SqlitemainActivity.onCreate(SqlitemainActivity.java:181)
at android.app.Activity.performCreate(Activity.java:7144)
at android.app.Activity.performCreate(Activity.java:7135)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2932)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3087) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1817) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:6746) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 
You got NullPointerException or NPE, this is the most common exception you'll face that you must be aware of, from here you find fruitful answers and explanation about it
In your particular case, your NPE exception is due to calling toString() method on a null object, and this is not allowed to access fields and methods of an object that is is not instantiated.
Process: com.example.bohon_final__001, PID: 1417
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bohon_final__001/com.example.bohon_final__001.SqlitemainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
Looking into your code, you call toString() for the selected item of the spinner before an item is selected, and this is the cause of the NPE
pickdistrict=pickupspinner1.getSelectedItem().toString();
pickarea=String.valueOf(pickupspinner2.getSelectedItem());
destdistrict=destspinner1.getSelectedItem().toString();
destarea=destspinner2.getSelectedItem().toString();
so you can solve this either by:
Setting a default item before calling toString(), and this can be done by
pickupspinner1.setSelection(my_default_item); // replace my_default_item with one of your spinner items
// Then you can call toString() afterwards
destdistrict = String.valueOf(pickupspinner2.getSelectedItem());
or by calling toString() whenever the user selects a spinner item so are are certain that there is an item is selected; to do so implement the onItemSelected() callback of setOnItemSelectedListener of your spinner
pickupspinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selection = (String) parent.getItemAtPosition(position);
destdistrict = String.valueOf(selection);
}
}
Yeah i fixed the error. The only problem was assigning the values of the string should be inside the onCLick Button listener method instead of inside the Oncreate method.
selectbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pickdistrict=pickupspinner1.getSelectedItem().toString();
pickarea=String.valueOf(pickupspinner2.getSelectedItem());
destdistrict=destspinner1.getSelectedItem().toString();
destarea=destspinner2.getSelectedItem().toString();
Intent submissionintent=new Intent(SqlitemainActivity.this,FinalRequestActivity.class);
submissionintent.putExtra("pickd",pickdistrict);
submissionintent.putExtra("picka",pickarea);
submissionintent.putExtra("desd",destdistrict);
submissionintent.putExtra("desa",destarea);
submissionintent.putExtra("vtype",vehicletype);
startActivity(submissionintent);
}
});

I want to get Fragment data in MainActivity calling fragment method

I want to show current weather data in fragment on search CityName base. Mean if I entered any city name in searchbox it show me the current weather of that city. All work was performing correctly if I give static City name, but I want that which city I select it give me this current data.
The SearchBox (EditText) is on Main Activity and currentweather data Method where I want to show my currentweather data is in Fragment. How it is possible to search on Main Activity and show currentweather data in fragment layout.
MainActivity
package com.deitel.apiretrofitfragmentweatherapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.viewpager.widget.ViewPager;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.deitel.apiretrofitfragmentweatherapp.Adapter.FragementViewAdapter;
import com.deitel.apiretrofitfragmentweatherapp.Fragment.currentweather;
import com.google.android.material.tabs.TabLayout;
public class MainActivity extends AppCompatActivity {
private static FragmentManager fragmentManager;
public static String BaseUrl = "http://api.openweathermap.org/";
public static String AppId = "08fd7374790f2ccee9f1f1dbfae38fdf";
/* public static String lat = "33.69";
public static String lon = "73.06";*/
ViewPager viewPager;
FragementViewAdapter fragementViewAdapter;
TabLayout tabLayout;
EditText text_search;
ImageButton btn_search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentManager = getSupportFragmentManager();
text_search = findViewById(R.id.text_search_city);
tabLayout = findViewById(R.id.tab_layout);
viewPager = findViewById(R.id.fragment_container);
btn_search = findViewById(R.id.btn_search);
final currentweather currentweather = new currentweather();
btn_search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager manager=getSupportFragmentManager();
currentweather weather= (currentweather) manager.findFragmentById(R.id.current_weather);
assert weather != null;
weather.getCurrentData();
String City= text_search.getText().toString().trim();
Bundle bundle = new Bundle();
bundle.putString("search_city", City);
currentweather.setArguments(bundle);
fragmentManager.beginTransaction().replace(R.id.fragment_container, currentweather).commit();
currentweather.getCurrentData();
if (TextUtils.isEmpty(City)) {
text_search.setError("Enter City Name");
return;
}
}
});
fragementViewAdapter = new FragementViewAdapter(getSupportFragmentManager());
viewPager.setAdapter(fragementViewAdapter);
tabLayout.setupWithViewPager(viewPager);
fragmentManager = getSupportFragmentManager();
}
}
CurrentWeatherFragment
package com.deitel.apiretrofitfragmentweatherapp.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import com.deitel.apiretrofitfragmentweatherapp.CurrentWeather.WeatherResponse;
import com.deitel.apiretrofitfragmentweatherapp.R;
import com.deitel.apiretrofitfragmentweatherapp.Retrofit.WeatherService;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import static com.deitel.apiretrofitfragmentweatherapp.MainActivity.AppId;
import static com.deitel.apiretrofitfragmentweatherapp.MainActivity.BaseUrl;
public class currentweather extends Fragment {
public TextView text_country,text_city,text_pressure,text_humidity,text_temp;
public TextView textView_country, textView_city, textView_temp,
textView_pressure, textView_humidity, textview_date;
/*public TextView text_view;*/
public currentweather() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View itemview=inflater.inflate(R.layout.fragment_currentweather, container, false);
textView_country = itemview.findViewById(R.id.textView_country);
textView_city =itemview.findViewById(R.id.textView_city);
textView_temp =itemview.findViewById(R.id.textview_temp);
textView_pressure =itemview.findViewById(R.id.textView_pressure);
textView_humidity =itemview.findViewById(R.id.textView_humidity);
textview_date =itemview.findViewById(R.id.textView_date);
text_country= itemview.findViewById(R.id.text_country);
text_city=itemview. findViewById(R.id.text_city);
/*text_view=itemview.findViewById(R.id.text_view);*/
text_pressure=itemview. findViewById(R.id.text_pressure);
text_humidity=itemview.findViewById(R.id.text_humidity);
text_temp=itemview.findViewById(R.id.text_temp);
/* Bundle bundle=getArguments();
if (bundle!=null)
{
city=bundle.getString("search_city");
textView_country.setText(city);
Log.d("ass",""+city);
}*/
text_country.setVisibility(View.GONE);
text_city.setVisibility(View.GONE);
text_pressure.setVisibility(View.GONE);
text_humidity.setVisibility(View.GONE);
text_temp.setVisibility(View.GONE);
return itemview;
}
public void getCurrentData() {
String City1 = null;
if (getArguments() != null){
City1=getArguments().getString("search_city");
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BaseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
WeatherService weatherService = retrofit.create(WeatherService.class);
Call<WeatherResponse> call = weatherService.getCurrentWeatherDataCityName(City1, AppId);
call.enqueue(new Callback() {
#Override
public void onResponse(Call call, Response response) {
if (response.code() == 200) {
WeatherResponse weatherResponse = (WeatherResponse) response.body();
assert weatherResponse != null;
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE-dd-MM");
String formatedate = simpleDateFormat.format(calendar.getTime());
/* String stringbuilder= "Country : " +
weatherResponse.sys.country +
"\n" +
"City : " +weatherResponse.name +
"\n" +
"Tempreture : " + weatherResponse.main.temp +
"\n" +
"Tempreture(Min) : " +
weatherResponse.main.temp_min +
"\n" +
"Tempreture(Max) : " +
weatherResponse.main.temp_max +
"\n" +
"Humidity : " +
weatherResponse.main.humidity +
"\n" +
"Pressure : " +
weatherResponse.main.pressure;*/
String Country = weatherResponse.sys.country;
String City = weatherResponse.name;
String Temp = String.valueOf(weatherResponse.main.temp);
Double calcius = Double.parseDouble(Temp) - 273.0;
Integer i = calcius.intValue();
String Pressure = String.valueOf(weatherResponse.main.pressure);
String Humidity = String.valueOf(weatherResponse.main.humidity);
textView_country.setText(Country);
textView_city.setText(City);
textView_temp.setText(String.valueOf(i));
textView_pressure.setText(Pressure);
textView_humidity.setText(Humidity);
textview_date.setText(formatedate);
text_country.setVisibility(View.VISIBLE);
text_city.setVisibility(View.VISIBLE);
text_pressure.setVisibility(View.VISIBLE);
text_humidity.setVisibility(View.VISIBLE);
text_temp.setVisibility(View.VISIBLE);
Toast.makeText(getContext(), "Successfully", Toast.LENGTH_SHORT).show();
}
if (response.code()==404)
{
Toast.makeText(getContext(), "City Not Founded", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call call, Throwable t) {
textView_country.setText(t.getMessage());
textView_city.setText(t.getMessage());
textView_temp.setText(t.getMessage());
textView_pressure.setText(t.getMessage());
textView_humidity.setText(t.getMessage());
textview_date.setText(t.getMessage());
}
});
}
}
Currentweatherframent.XML File
<?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"
android:id="#+id/current_weather"
tools:context=".MainActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/text_country"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:text="Country"
android:textColor="#000"
android:textSize="25dp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView_date" />
<TextView
android:id="#+id/textView_country"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:text=""
android:textColor="#000"
android:textSize="17dp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/text_country" />
<TextView
android:id="#+id/text_city"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginEnd="10dp"
android:layout_marginRight="10dp"
android:text="City"
android:textColor="#000"
android:textSize="25dp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView_date" />
<TextView
android:id="#+id/textView_city"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginEnd="10dp"
android:layout_marginRight="10dp"
android:text=""
android:textColor="#000"
android:textSize="17dp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/text_city" />
<TextView
android:id="#+id/text_temp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="90dp"
android:text="Temperature"
android:textColor="#000"
android:textSize="25dp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="#+id/textView_country"
app:layout_constraintTop_toBottomOf="#id/textView_date" />
<TextView
android:id="#+id/textview_temp"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginTop="40dp"
android:gravity="center"
android:text=""
android:textColor="#000"
android:textSize="40dp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/text_temp" />
<TextView
android:id="#+id/text_pressure"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Pressure"
android:textColor="#000"
android:textSize="25dp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textview_temp" />
<TextView
android:id="#+id/textView_pressure"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text=""
android:textColor="#000"
android:textSize="17dp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/text_pressure" />
<TextView
android:id="#+id/text_humidity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Humidity"
android:textColor="#000"
android:textSize="25dp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView_pressure" />
<TextView
android:id="#+id/textView_humidity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:layout_marginBottom="32dp"
android:text=""
android:textColor="#000"
android:textSize="17dp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/text_humidity" />-->
<TextView
android:id="#+id/textView_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text=""
android:textColor="#000"
android:textSize="17dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
Error
1-03 19:35:10.586 1428-1428/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.deitel.apiretrofitfragmentweatherapp, PID: 1428
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.widget.Toast.<init>(Toast.java:107)
at android.widget.Toast.makeText(Toast.java:264)
at com.deitel.apiretrofitfragmentweatherapp.Fragment.currentweather$1.onResponse(currentweather.java:129)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5728)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
01-03 21:43:00.695 10885-10885/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.deitel.apiretrofitfragmentweatherapp, PID: 10885
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.deitel.apiretrofitfragmentweatherapp/com.deitel.apiretrofitfragmentweatherapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.deitel.apiretrofitfragmentweatherapp.Fragment.currentweather.getCurrentData()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2572)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2654)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1488)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5728)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.deitel.apiretrofitfragmentweatherapp.Fragment.currentweather.getCurrentData()' on a null object reference
at com.deitel.apiretrofitfragmentweatherapp.MainActivity.onCreate(MainActivity.java:43)
at android.app.Activity.performCreate(Activity.java:6301)

Error with new intent ANDROID STUDIO [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
package com.example.alex.askii;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
//Alex Levin
public class Login extends AppCompatActivity {
Button login;
Button signUp;
EditText userNameET;
EditText passWordET;
DatabaseHelper helper = new DatabaseHelper(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
login = (Button)findViewById(R.id.Login);
signUp = (Button)findViewById(R.id.signUp);
userNameET = (EditText)findViewById(R.id.username);
passWordET = (EditText)findViewById(R.id.password);
login.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
//get text valiues
String userName = userNameET.getText().toString();
String passWord = passWordET.getText().toString();
//Query in java the username
String actualPassword = helper.searchPass(userName);
//If Correct
if(passWord.equals(actualPassword)){
Toast.makeText(getApplicationContext(),
"Redirecting...", Toast.LENGTH_SHORT).show();
/*
Intent i = new Intent(mainActivity.this, display.class);
i.putExtra("UserName", str);
startActivity(i)
Example code to go to next activity ^^
*/
}else{
Toast.makeText(getApplicationContext(), "Invalid Username Or Password", Toast.LENGTH_SHORT).show();
}
}
});
signUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Login.this, signUP.class);
startActivity(i);
}
});
}
}
<?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.alex.askii.Login">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Askii Login"
android:textSize = "30dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.033"
tools:layout_constraintRight_creator="1"
tools:layout_constraintLeft_creator="1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text= "Username:"
android:textSize="20dp"
app:layout_constraintRight_toLeftOf="#+id/username"
tools:layout_constraintRight_creator="1"
tools:layout_constraintBottom_creator="1"
app:layout_constraintBottom_toBottomOf="#+id/username"
android:layout_marginEnd="7dp"
android:layout_marginBottom="4dp"
android:layout_marginRight="7dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text= "Password:"
android:textSize="20dp"
android:id="#+id/textView"
tools:layout_constraintBottom_creator="1"
android:layout_marginStart="16dp"
app:layout_constraintBottom_toBottomOf="parent"
tools:layout_constraintLeft_creator="1"
android:layout_marginBottom="169dp"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginLeft="16dp" />
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/Login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login"
android:onClick="login"
tools:layout_constraintRight_creator="1"
tools:layout_constraintBottom_creator="1"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginEnd="84dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginBottom="88dp"
android:layout_marginRight="130dp" />
<EditText
android:id="#+id/password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPassword"
tools:layout_constraintRight_creator="1"
app:layout_constraintRight_toRightOf="#+id/username"
app:layout_constraintBaseline_toBaselineOf="#+id/textView"
tools:layout_constraintBaseline_creator="1"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="#+id/username" />
<EditText
android:id="#+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:text="Enter Username"
tools:layout_constraintBottom_creator="1"
app:layout_constraintBottom_toTopOf="#+id/password"
android:layout_marginStart="11dp"
tools:layout_constraintLeft_creator="1"
android:layout_marginBottom="20dp"
app:layout_constraintLeft_toRightOf="#+id/textView"
android:layout_marginLeft="11dp" />
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/signUp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sign Up"
tools:layout_constraintRight_creator="1"
tools:layout_constraintBottom_creator="1"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_marginEnd="84dp"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginRight="216dp"
android:layout_marginBottom="47dp" />
</android.support.constraint.ConstraintLayout>
package com.example.alex.askii;
import android.app.Activity;
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.Toast;
/**
* Created by Alex on 12/30/2017.
*/
public class signUP extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
}
Button signUpOnPage = (Button)findViewById(R.id.signUpOnPage);
public void onSignUpOnPage(View v){
if(v.getId() == R.id.signUpOnPage){
EditText userName = (EditText)findViewById(R.id.newUserName);
EditText passWord = (EditText)findViewById(R.id.newPassWord);
EditText confPassword = (EditText)findViewById(R.id.newUserName);
String userNameString = userName.getText().toString();
String passWordString = passWord.getText().toString();
String confPasswordString = confPassword.getText().toString();
if(!passWordString.equals(confPasswordString)){
Toast check = Toast.makeText(signUP.this, "Passwords Don't Match", Toast.LENGTH_SHORT);
check.show();
}
}
}
}
For some reason I am getting the following error
12-30 02:39:59.308 1969-1969/com.example.alex.askii E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.alex.askii/com.example.alex.askii.signUP}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1880)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:118)
at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:152)
at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:29)
at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:53)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:204)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:184)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:518)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:189)
at com.example.alex.askii.signUP.<init>(signUP.java:16)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1319)
at android.app.Instrumentation.newActivity(Instrumentation.java:1023)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1871)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981) 
at android.app.ActivityThread.access$600(ActivityThread.java:123) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4424) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:511) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 
at dalvik.system.NativeStart.main(Native Method) 
I am really unsure why this is happening maybe it is something wrong with my manifests but I doubt it because the manifest was autogenerated. Please help I can't find the answer online because it seems like I followed everything online correctly this is the last place I came to for help I am so frustrated right now!
Move
signUpOnPage = (Button)findViewById(R.id.signUpOnPage);
to onCreate()

Android appilcation force stops on hitting the button

Im new to Android and having little problem while running this app. Whenever I hit the "ADD" button on my application it force stops. Please help me out. Im attaching my xml and java code along.
This is the error Im getting:
I/OpenGLRenderer: Initialized EGL, version 1.4
W/EGL_emulation: eglSurfaceAttrib not implemented
W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xe99d1f80, error=EGL_SUCCESS
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
Process: akshay.com.myfirstapp, PID: 13085
java.lang.NumberFormatException: Invalid int: ""
at java.lang.Integer.invalidInt(Integer.java:138)
at java.lang.Integer.parseInt(Integer.java:358)
at java.lang.Integer.parseInt(Integer.java:334)
at akshay.com.myfirstapp.Addition$1.onClick(Addition.java:28)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
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)
Application terminated.
Here is my Addition.java
package akshay.com.myfirstapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Addition extends AppCompatActivity {
EditText editText2,editText3;
Button button;
TextView textView3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addition);
editText2=(EditText)findViewById(R.id.editText2);
editText3=(EditText)findViewById(R.id.editText3);
button=(Button)findViewById(R.id.button);
textView3=(TextView)findViewById(R.id.textView3);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int i=Integer.parseInt(editText2.getText().toString());
int j=Integer.parseInt(editText3.getText().toString());
int ans=i+j;
textView3.setText(ans);
}
});
}
}
Here is my addition_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_addition"
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="akshay.com.myfirstapp.Addition">
<EditText
android:layout_width="150dp"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/editText2"
android:layout_alignParentTop="true"
android:layout_alignLeft="#+id/editText3"
android:layout_alignStart="#+id/editText3" />
<TextView
android:text="First Number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="36dp"
android:layout_marginStart="36dp"
android:id="#+id/textView"
android:textSize="20sp"
android:layout_alignBottom="#+id/editText2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:text="Second Number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="33dp"
android:id="#+id/textView2"
android:textSize="20sp"
android:layout_below="#+id/textView"
android:layout_alignLeft="#+id/textView"
android:layout_alignStart="#+id/textView" />
<EditText
android:layout_width="150dp"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/editText3"
android:layout_alignBaseline="#+id/textView2"
android:layout_alignBottom="#+id/textView2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:text="Add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:layout_below="#+id/editText3"
android:layout_centerHorizontal="true"
android:layout_marginTop="71dp" />
<TextView
android:text="Sum"
android:layout_height="wrap_content"
android:id="#+id/textView3"
android:textSize="25sp"
android:layout_width="100dp"
android:layout_below="#+id/button"
android:layout_centerHorizontal="true"
android:layout_marginTop="64dp" />
An empty string cannot be converted to an Integer, so you need to check that your EditTexts are not empty first.
And as pointed out by #csabapap, the setText method on your TextView should be passed a String.
Final code could look something like this:
if (editText2.getText().length() != 0 && editText3.getText().length() != 0) {
int i=Integer.parseInt(editText2.getText().toString());
int j=Integer.parseInt(editText3.getText().toString());
int ans=i+j;
textView3.setText(String.valueOf(ans));
}
You may also want to give your EditText variables meaningful names. It is very difficult to tell which one is which, and doing this will save you valuable debugging time later on.

Categories