NullPointerException in Android app (Bundle?) [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
In a class i am taking we have been learning some android app development and such, and i have managed to run into a problem that I, for the life of me, cannot figure out...
Basic background...
I get a nullpointerexception when I rotate the device... This error is located at Line 100 of QuizActivity.....
this Line is : mCheatButton.setOnClickListener(new View.OnClickListener() {//....
I suspect this has something to do with storing or retrieving information from the bundle...
Anyways here is the rest of The code....
Here is my quiz activity... Sorry for all the code blocks, I dont really know a better way to give you this information, or if you even need all of it.... But right now I just can figure out what is going on... so i have printed the error (stack trace? i think that is the right term...).. here as well...
03-02 09:49:28.858 7921-7921/com.example.ryan.ryans_quiz E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ryan.ryans_quiz, PID: 7921
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ryan.ryans_quiz/com.example.ryan.ryans_quiz.QuizActivity}: 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:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.ryan.ryans_quiz.QuizActivity.onCreate(QuizActivity.java:100)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
QuizActivity
package com.example.ryan.ryans_quiz;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class QuizActivity extends AppCompatActivity {
private static final String TAG = "QuizActivity";
private static final String KEY_INDEX = "index";
private static final int REQUEST_CODE_CHEAT = 0;
private Button mTrueButton;
private Button mFalseButton;
private ImageButton mNextButton;
private Button mCheatButton;
private TextView mQuestionTextView;
private Question[] mQuestionBank = new Question[] {
new Question(R.string.question_oceans, true),
new Question(R.string.question_mideast, false),
new Question(R.string.question_africa, false),
new Question(R.string.question_americas, true),
new Question(R.string.question_asia, true)
};
private int mCurrentIndex = 0;
private boolean mIsCheater;
private void updateQuestion() {
int question = mQuestionBank[mCurrentIndex].getTextResId();
mQuestionTextView.setText(question);
}
private void checkAnswer(boolean userPressedTrue) {
boolean answerIsTrue = mQuestionBank[mCurrentIndex].isAnswerTrue();
int messageResId = 0;
if (mIsCheater) {
messageResId = R.string.judgment_toast;
} else {
if (userPressedTrue == answerIsTrue) {
messageResId = R.string.correct_toast;
} else {
messageResId = R.string.incorrect_toast;
}
}
Toast.makeText(this, messageResId, Toast.LENGTH_SHORT)
.show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
if (savedInstanceState != null) {
mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, 0);
}
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate(Bundle) called");
setContentView(R.layout.activity_quiz);
mQuestionTextView = (TextView) findViewById(R.id.question_text_view);
mTrueButton = (Button) findViewById(R.id.trueButton);
mTrueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(true);
}
});
mFalseButton = (Button) findViewById(R.id.falseButton);
mFalseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(false);
}
});
mNextButton = (ImageButton) findViewById(R.id.nextButton);
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
mIsCheater = false;
updateQuestion();
}
});
mCheatButton = (Button)findViewById(R.id.cheatButton);
mCheatButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean answerIsTrue = mQuestionBank[mCurrentIndex].isAnswerTrue();
Intent i = CheatActivity.newIntent(QuizActivity.this, answerIsTrue);
startActivityForResult(i, REQUEST_CODE_CHEAT);
}
});
updateQuestion();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(KEY_INDEX, mCurrentIndex);
}
#Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart() called");
}
#Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause() called");
}
#Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume() called");
}
#Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop() called");
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy() called");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) {
return;
}
if (requestCode == REQUEST_CODE_CHEAT) {
if (data == null) {
return;
}
mIsCheater = CheatActivity.wasAnswerShown(data);
}
}
}
My CheatActivity class
package com.example.ryan.ryans_quiz;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
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.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewAnimationUtils;
import android.widget.Button;
import android.widget.TextView;
public class
CheatActivity extends AppCompatActivity {
private static final String EXTRA_ANSWER_IS_TRUE =
"com.bignerdranch.android.geoquiz.answer_is_true";
private static final String EXTRA_ANSWER_SHOWN =
"com.bignerdranch.android.geoquiz.answer_shown";
private boolean mAnswerIsTrue;
private TextView mAnswerTextView;
private Button mShowAnswer;
public static Intent newIntent(Context packageContext, boolean answerIsTrue) {
Intent i = new Intent(packageContext, CheatActivity.class);
i.putExtra(EXTRA_ANSWER_IS_TRUE, answerIsTrue);
return i;
}
public static boolean wasAnswerShown(Intent result) {
return result.getBooleanExtra(EXTRA_ANSWER_SHOWN, false);
}
private void setAnswerShownResult(boolean isAnswerShown) {
Intent data = new Intent();
data.putExtra(EXTRA_ANSWER_SHOWN, isAnswerShown);
setResult(RESULT_OK, data);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cheat);
mAnswerIsTrue = getIntent().getBooleanExtra(EXTRA_ANSWER_IS_TRUE, false);
mAnswerTextView = (TextView)findViewById(R.id.answer_text_view);
mShowAnswer = (Button)findViewById(R.id.show_answer_button);
mShowAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mAnswerIsTrue) {
mAnswerTextView.setText(R.string.trueButton);
} else {
mAnswerTextView.setText(R.string.falseButton);
}
setAnswerShownResult(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
int cx = mShowAnswer.getWidth() / 2;
int cy = mShowAnswer.getHeight() / 2;
float radius = mShowAnswer.getWidth();
Animator anim = ViewAnimationUtils
.createCircularReveal(mShowAnswer, cx, cy, radius, 0);
anim.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
mAnswerTextView.setVisibility(View.VISIBLE);
mShowAnswer.setVisibility(View.INVISIBLE);
}
});
anim.start();
} else {
mAnswerTextView.setVisibility(View.VISIBLE);
mShowAnswer.setVisibility(View.INVISIBLE);
}
}
});
}
my Question Class
package com.example.ryan.ryans_quiz;
/**
* Created by Ryan on 1/20/2016.
*/
public class Question {
private int mTextResId;
private boolean mAnswerTrue;
public Question(int _textResId, boolean _answerTrue) {
mTextResId = _textResId;
mAnswerTrue = _answerTrue;
}
public int getTextResId() {
return mTextResId;
}
public void setTextResId(int textResId) {
mTextResId = textResId;
}
public boolean isAnswerTrue() {
return mAnswerTrue;
}
public void setAnswerTrue(boolean answerTrue) {
mAnswerTrue = answerTrue;
}
}
And finally my xml Files....
activity_cheat
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical"
tools:context="com.example.ryan.ryans_quiz.CheatActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="24dp"
android:text="#string/warning_text"/>
<TextView
android:id="#+id/answer_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="24dp"
tools:text="Answer"/>
<Button
android:id="#+id/show_answer_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/show_answer_button"/>
</LinearLayout>
LandLayout - activity_quiz
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/question_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:padding="24dp"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center_vertical"
android:orientation="vertical">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center_vertical"
android:orientation="horizontal">
<Button
android:id="#+id/trueButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/trueButton"/>
<Button
android:id="#+id/falseButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/falseButton"/>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center"
android:text="#string/cheat_button"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center_vertical"
android:orientation="horizontal">
<ImageButton
android:id="#+id/previousButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription="#string/previousButton"
android:src="#drawable/arrow_left"/>
<ImageButton
android:id="#+id/nextButton"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal|center_vertical"
android:contentDescription="#string/nextButton"
android:src="#drawable/arrow_right"/>
</LinearLayout>
</LinearLayout>
</FrameLayout>
vertical layout- activity_quiz
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/question_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="24dp"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/trueButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/trueButton"/>
<Button
android:id="#+id/falseButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/falseButton"/>
</LinearLayout>
<Button
android:id="#+id/cheatButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/cheat_button"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageButton
android:id="#+id/previousButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/previousButton"
android:src="#drawable/arrow_left"/>
<ImageButton
android:id="#+id/nextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/nextButton"
android:src="#drawable/arrow_right"/>
</LinearLayout>
</LinearLayout>
Strings..
<resources>
<string name="app_name">RyanHull_Quiz</string>
<string name="action_settings">Settings</string>
<string name="trueButton">True</string>
<string name="falseButton">False</string>
<string name="nextButton">Next</string>
<string name="previousButton">Previous</string>
<string name="cheat_button">Cheat!</string>
<string name="correct_toast">Correct! :)</string>
<string name="incorrect_toast">Incorrect! :(</string>"
<string name="question_oceans">The Pacific Ocean is larger than the Atlantic Ocean.</string>
<string name="question_mideast">The Suez Canal connects the Red Sea and the Indian Ocean.</string>
<string name="question_africa">The source of the Nile River is in Egypt.</string>
<string name="question_americas">The Amazon River is the longest river in the Americas.</string>
<string name="question_asia">Lake Baikal is the world\'s oldest and deepest freshwater lake.</string>
<string name="warning_text">Are you sure you want to do this??</string>
<string name="show_answer_button">Show Answer</string>
<string name="judgment_toast">Cheating is Wrong 8/</string>
<string name="title_activity_cheat">Cheat</string>
and finally manifest....
<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.example.ryan.ryans_quiz"
xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".QuizActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!--
ATTENTION: This was auto-generated to add Google Play services to your project for
App Indexing. See https://g.co/AppIndexing/AndroidStudio for more information.
-->
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version"/>
<activity
android:name=".CheatActivity"
android:label="#string/title_activity_cheat"
android:theme="#style/AppTheme.NoActionBar">
</activity>
</application>
EDIT: its not a matter of me know what the exception is.. More of the matter of find where and why...

The lookup is failing for mCheatButton because you forgot to assign it an id in the landscape version of the activity_quiz.xml layout file.
When you then try to set a ClickListener on a null object that is where the NullPointerException is coming from.

when you rotate the device,the QuizActivity will destroy and then call onCreate,but your LandLayout file has no Button called 'cheatButton',so findViewById(R.id.cheatButton) will return null to mCheatButton, it can not call any method.

You haven't assigned any id to cheat button in LandLayout - activity_quiz
Change
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center"
android:text="#string/cheat_button"/>
to
<Button
android:id="#+id/cheatButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|center"
android:text="#string/cheat_button"/>

Related

Mapbox Fragment inside another activity

I'm trying to create an application that tracks a user's eyes while driving which will also show turn by turn navigation. There will be a camera preview on the same screen as the maps, similar to the image below, where the camera preview is in the top left and the maps is below
I have a MapBox activity working in a seperate file, MapsActivity.java. I want to run the Mapbox activity inside a fragment in an activty test.java which does the eye tracking.
I have looked at tutorials and online resources but cannot find out how to get it to work for my particular code. Apologies if this is a simple question, this is my first app.
MapsActivity.java
package com.example.drivesafely;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.mapbox.android.core.permissions.PermissionsListener;
import com.mapbox.android.core.permissions.PermissionsManager;
import com.mapbox.api.directions.v5.models.DirectionsResponse;
import com.mapbox.api.directions.v5.models.DirectionsRoute;
import com.mapbox.geojson.Feature;
import com.mapbox.geojson.Point;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.location.LocationComponent;
import com.mapbox.mapboxsdk.location.modes.CameraMode;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.maps.Style;
import com.mapbox.mapboxsdk.style.layers.SymbolLayer;
import com.mapbox.mapboxsdk.style.sources.GeoJsonSource;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncher;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncherOptions;
import com.mapbox.services.android.navigation.ui.v5.route.NavigationMapRoute;
import com.mapbox.services.android.navigation.v5.navigation.NavigationRoute;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconAllowOverlap;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconIgnorePlacement;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconImage;
// classes needed to initialize map
// classes needed to add the location component
// classes needed to add a marker
// classes to calculate a route
// classes needed to launch navigation UI
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback, MapboxMap.OnMapClickListener, PermissionsListener {
// variables for adding location layer
private MapView mapView;
private MapboxMap mapboxMap;
// variables for adding location layer
private PermissionsManager permissionsManager;
private LocationComponent locationComponent;
// variables for calculating and drawing a route
private DirectionsRoute currentRoute;
private static final String TAG = "DirectionsActivity";
private NavigationMapRoute navigationMapRoute;
// variables needed to initialize navigation
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this, getString(R.string.access_token));
setContentView(R.layout.activity_maps);
mapView = findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
}
#Override
public void onMapReady(#NonNull final MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
mapboxMap.setStyle(getString(R.string.navigation_guidance_day), new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
enableLocationComponent(style);
addDestinationIconSymbolLayer(style);
mapboxMap.addOnMapClickListener(MapsActivity.this);
button = findViewById(R.id.startButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean simulateRoute = true;
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.directionsRoute(currentRoute)
.shouldSimulateRoute(simulateRoute)
.build();
// Call this method with Context from within an Activity
NavigationLauncher.startNavigation(MapsActivity.this, options);
}
});
}
});
}
private void addDestinationIconSymbolLayer(#NonNull Style loadedMapStyle) {
loadedMapStyle.addImage("destination-icon-id",
BitmapFactory.decodeResource(this.getResources(), R.drawable.mapbox_marker_icon_default));
GeoJsonSource geoJsonSource = new GeoJsonSource("destination-source-id");
loadedMapStyle.addSource(geoJsonSource);
SymbolLayer destinationSymbolLayer = new SymbolLayer("destination-symbol-layer-id", "destination-source-id");
destinationSymbolLayer.withProperties(
iconImage("destination-icon-id"),
iconAllowOverlap(true),
iconIgnorePlacement(true)
);
loadedMapStyle.addLayer(destinationSymbolLayer);
}
#SuppressWarnings( {"MissingPermission"})
#Override
public boolean onMapClick(#NonNull LatLng point) {
Point destinationPoint = Point.fromLngLat(point.getLongitude(), point.getLatitude());
Point originPoint = Point.fromLngLat(locationComponent.getLastKnownLocation().getLongitude(),
locationComponent.getLastKnownLocation().getLatitude());
GeoJsonSource source = mapboxMap.getStyle().getSourceAs("destination-source-id");
if (source != null) {
source.setGeoJson(Feature.fromGeometry(destinationPoint));
}
getRoute(originPoint, destinationPoint);
button.setEnabled(true);
button.setBackgroundResource(R.color.mapboxBlue);
return true;
}
private void getRoute(Point origin, Point destination) {
NavigationRoute.builder(this)
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
// You can get the generic HTTP info about the response
Log.d(TAG, "Response code: " + response.code());
if (response.body() == null) {
Log.e(TAG, "No routes found, make sure you set the right user and access token.");
return;
} else if (response.body().routes().size() < 1) {
Log.e(TAG, "No routes found");
return;
}
currentRoute = response.body().routes().get(0);
// Draw the route on the map
if (navigationMapRoute != null) {
navigationMapRoute.removeRoute();
} else {
navigationMapRoute = new NavigationMapRoute(null, mapView, mapboxMap, R.style.NavigationMapRoute);
}
navigationMapRoute.addRoute(currentRoute);
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
Log.e(TAG, "Error: " + throwable.getMessage());
}
});
}
#SuppressWarnings( {"MissingPermission"})
private void enableLocationComponent(#NonNull Style loadedMapStyle) {
// Check if permissions are enabled and if not request
if (PermissionsManager.areLocationPermissionsGranted(this)) {
// Activate the MapboxMap LocationComponent to show user location
// Adding in LocationComponentOptions is also an optional parameter
locationComponent = mapboxMap.getLocationComponent();
locationComponent.activateLocationComponent(this, loadedMapStyle);
locationComponent.setLocationComponentEnabled(true);
// Set the component's camera mode
locationComponent.setCameraMode(CameraMode.TRACKING);
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
Toast.makeText(this, R.string.user_location_permission_explanation, Toast.LENGTH_LONG).show();
}
#Override
public void onPermissionResult(boolean granted) {
if (granted) {
enableLocationComponent(mapboxMap.getStyle());
} else {
Toast.makeText(this, R.string.user_location_permission_not_granted, Toast.LENGTH_LONG).show();
finish();
}
}
#Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
#Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
#Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
}
activity_maps
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:mapbox="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.mapbox.mapboxsdk.maps.MapView
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent"
mapbox:mapbox_cameraTargetLat="38.9098"
mapbox:mapbox_cameraTargetLng="-77.0295"
mapbox:mapbox_cameraZoom="12" />
<Button
android:id="#+id/startButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:background="#color/mapboxGrayLight"
android:enabled="false"
android:text="Start navigation"
android:textColor="#color/mapboxWhite"
mapbox:layout_constraintStart_toStartOf="parent"
mapbox:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
activity_test.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:mapbox="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/background"
android:background="#fcfcfc"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:keepScreenOn="true"
tools:context=".test">
<com.mapbox.mapboxsdk.maps.MapView
android:id="#+id/mapView"
android:layout_width="400dp"
android:layout_height="300dp"
android:background="#f567"
mapbox:layout_constraintTop_toBottomOf="#+id/preview"
mapbox:mapbox_cameraTargetLat="38.9098"
mapbox:mapbox_cameraTargetLng="-77.0295"
mapbox:mapbox_cameraZoom="12" />
<Button
android:id="#+id/startButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="260dp"
android:layout_marginEnd="16dp"
android:background="#color/mapboxGrayLight"
android:enabled="false"
android:text="Start navigation"
android:textColor="#color/mapboxWhite"
tools:layout_constraintStart_toStartOf="parent"
tools:layout_constraintTop_toTopOf="parent" />
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="bottom">
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="false"
android:layout_alignParentTop="false"
android:layout_alignParentBottom="true"
android:layout_weight="0"
android:background="#19b5fe"
android:gravity="center|center_horizontal"
android:weightSum="2">
<Button
android:id="#+id/button"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="35dp"
android:layout_marginRight="5dp"
android:background="#E0E0E0"
android:text="#string/end" />
<ToggleButton
android:id="#+id/toggleButton"
android:layout_width="200dp"
android:layout_height="40dp"
android:background="#drawable/rounded_corners"
android:checked="false"
android:text="New ToggleButton"
android:textColor="#ffff"
android:textOff="#string/turn_preview_off"
android:textSize="12dp" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="Status: "
android:textAppearance="?android:attr/textAppearanceSmall"
android:textStyle="bold" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall" />
</TableRow>
</RelativeLayout>
<com.example.drivesafely.CameraSourcePreview
android:id="#+id/preview"
android:layout_width="200dp"
android:layout_height="300dp"
android:layout_gravity="center_horizontal">
<com.example.drivesafely.GraphicOverlay
android:id="#+id/faceOverlay"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</com.example.drivesafely.CameraSourcePreview>
</androidx.constraintlayout.widget.ConstraintLayout>
It is not possible to run Activity inside another Activity, in your case you can't run MapsActivity in your TestActivity. This is possible with some other solutions but the easiest one for you is to use Fragments. What you can do is to convert your MakeActivity to Fragment and then place it inside TestActivity. Learn how Fragments and Activities work in Android since you'll be using them a lot.
Here are some links to read:
https://developer.android.com/reference/android/app/Fragment.html
https://developer.android.com/guide/fragments
You can put a Maps SDK for Android map fragment inside of your TestActivity or inside a separate fragment
https://docs.mapbox.com/android/maps/examples/support-map-fragment/
https://docs.mapbox.com/android/maps/examples/?search=fragment

New activity does not open on button click [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I can not understand why my application does not open a new activity on a button click.I have a button in my layout file(id is showButton),I need to open another activity when I click on that button.But it does not work and my application will crash.therefore I added a try catch block and get the android monitor result as following.
activity_place_picker.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".PlacePickerActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView2"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Launch Places API Picker"
android:id="#+id/pickerButton"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add to Place Holder"
android:id="#+id/saveButton"
android:layout_below="#+id/pickerButton"
android:layout_centerHorizontal="true"
android:visibility="gone"
android:layout_marginTop="20dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Place Holder"
android:id="#+id/showButton"
android:layout_below="#+id/saveButton"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView3"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView3"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/poweredBy"
android:src="#drawable/powered_by_google_light"/>
This is Place picker class where I have included the onClick listner to the button to open a new activity.
PlacePickerActivity
public class PlacePickerActivity extends AppCompatActivity {
private static final int PLACE_PICKER_REQUEST = 1;
private TextView mName;
private TextView mAddress;
private TextView mAttributions;
private static final LatLngBounds BOUNDS_MOUNTAIN_VIEW = new LatLngBounds(
new LatLng(37.398160, -122.180831), new LatLng(37.430610, -121.972090));
Context ctx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_place_picker);
mName = (TextView) findViewById(R.id.textView);
mAddress = (TextView) findViewById(R.id.textView2);
mAttributions = (TextView) findViewById(R.id.textView3);
Button showButton = (Button) findViewById(R.id.showButton);
Button pickerButton = (Button) findViewById(R.id.pickerButton);
pickerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
PlacePicker.IntentBuilder intentBuilder =
new PlacePicker.IntentBuilder();
intentBuilder.setLatLngBounds(BOUNDS_MOUNTAIN_VIEW);
Intent intent = intentBuilder.build(PlacePickerActivity.this);
startActivityForResult(intent, PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException
| GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
});
showButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
try {
Intent i = new Intent(ctx, PlacesActivity.class);
ctx.startActivity(i);
}catch (Exception e){
e.printStackTrace();
}
}
});
}
#Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST
&& resultCode == Activity.RESULT_OK) {
//Extracting place information from the API
final Place place = PlacePicker.getPlace(this, data);
final String place_Id = place.getId().toString();
final String place_Name = place.getName().toString();
final String place_Address = place.getAddress().toString();
final String place_PhoneNumber = place.getPhoneNumber().toString();
final String place_Website = place.getWebsiteUri().toString();
//Get rating as a float value and converting to string
final float rating = place.getRating();
final String place_Rating = String.valueOf(rating);
final String place_LatLng = place.getLatLng().toString();
final String function_Save = "save_Place";
final String function_Show = "show_Place";
String attributions = (String) place.getAttributions();
if (attributions == null) {
attributions = "";
}
mName.setText(place_Name);
mAddress.setText(place_Address);
mAttributions.setText(Html.fromHtml(attributions));
//Accessing the save button and show button in the view and making it visible after selecting a place
final View save = findViewById(R.id.saveButton);
save.setVisibility(View.VISIBLE);
//Passing the Extracted place details to the background worker class
save.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
BackgroundWorker backgroundWorker = new BackgroundWorker(PlacePickerActivity.this);
backgroundWorker.execute(function_Save,place_Id,place_Name,place_Address,place_PhoneNumber,place_Website,place_Rating,place_LatLng);
}
});
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
PlacesActivity.java
package com.truiton.placepicker;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class PlacesActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_places);
}
}
activity_places.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.truiton.placepicker.PlacesActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello world"
android:id="#+id/textView" />
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.truiton.placepicker">
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyBpIGvJfE8eKhoEFCMqV8NrFkWRjTAnNyQ" />
<activity
android:name=".PlacePickerActivity"
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=".PlacesActivity"></activity>
</application>
</manifest>
Android Monitor result when the button clicks
Android Monitor result
Edited : This is the crash log
Crash log
can anyone help me with this?
Write the class name PlacePickerActivity in the intent, your method should be
showButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
try {
Intent i = new Intent(PlacePickerActivity.this , PlacesActivity.class);
ctx.startActivity(i);
}catch (Exception e){
e.printStackTrace();
}
}
});
I found the answer for the question.
This
link helped me to find the answer for the problem. In PlacePickerActivity I have just declare Context ctx;and it does not contain any primitive value. But I have use the it as an argument to open a new activity which will give me a NullPointerException.So instead of
showButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent i = new Intent(ctx, PlacesActivity.class);
ctx.startActivity(i);
}
});
I used
showButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent i = new Intent(PlacePickerActivity.this, PlacesActivity.class);
PlacePickerActivity.this.startActivity(i);
}
});
And this fixed my problem.Thank you for every one.

passing user input (EditText) between activities, and then using that in formula

I want from user to input his name in one EditText widget, then to input his weight in other EditText widget, and after that to proceed that data from one activity to another one.
Weight input should later be included in one formula, and name input should be settled in TextView widget with result of the formula.
But, when i start my app, at the end Android Studio shows me NullPointerException. I suppose that err is somewhere in data sharing between activities.
So, here is the code. If you can, pls help me :)
ActivityOne (name of activity is InformacijeM) XML file:
<?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:id="#+id/activity_informacije_m"
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.example.alkometar.InformacijeM"
android:background="#drawable/activitybackground">
<TextView
android:text="Ukucaj svoje ime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="29dp"
android:textSize="25dp"
android:textColor="#android:color/black"
android:textStyle="bold"
android:id="#+id/UkucajIme" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="#drawable/strelamanja"
android:id="#+id/strelica"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="28dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text=""
android:ems="10"
android:id="#+id/ImeInput"
android:layout_marginTop="12dp"
android:layout_below="#+id/UkucajIme"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text=""
android:ems="10"
android:id="#+id/MasaInput"
android:layout_marginBottom="53dp"
android:layout_above="#+id/strelica"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
/>
<TextView
android:text="Ukucaj svoju masu u kg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/UkucajMasu"
android:textSize="25dp"
android:textColor="#android:color/black"
android:textStyle="bold"
android:layout_marginBottom="30dp"
android:layout_above="#+id/MasaInput"
android:layout_centerHorizontal="true" />
</RelativeLayout>
ActivityOne (InformacijeM) Java file:
package com.example.alkometar;
import android.content.Intent;
import android.content.res.Resources;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
public class InformacijeM extends AppCompatActivity {
EditText ImeTxt, MasaTxt ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_informacije_m);
// INICIRANJE VREDNOSTI
EditText ImeTxt = (EditText)findViewById(R.id.ImeInput);
final String str1 = ImeTxt.getText().toString();
EditText MasaTxt = (EditText)findViewById(R.id.MasaInput);
final String str2 = MasaTxt.getText().toString();
ImageButton btn = (ImageButton)findViewById(R.id.strelica);
// PREBACIVANJE AKTIVITIJA
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(InformacijeM.this, RezultatM.class);
intent1.putExtra("keyIme", str1);
intent1.putExtra("keyMasa", str2);
Intent intent = new Intent(InformacijeM.this, StanjeM.class);
startActivity(intent);
}
});
}}
ActivityTwo (Name of activity is RezultatM) XML file:
<?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_rezultat_m"
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.example.alkometar.RezultatM"
android:background="#drawable/activitybackground">
<TextView
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="97dp"
android:id="#+id/rezultatTekst" />
<Button
android:text="Rezultat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="26dp"
android:id="#+id/button" />
</RelativeLayout>
ActivityTwo (RezultatM) Java file:
package com.example.alkometar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class RezultatM extends AppCompatActivity {
TextView rezultat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rezultat_m);
rezultat = (TextView) findViewById(R.id.rezultatTekst);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Bundle extras = getIntent().getExtras();
{
String str1 = extras.getString("keyIme");
String str2 = extras.getString("keyMasa");
double masad = Double.valueOf(str2);
double nekibroj = 0.8;
double result = masad * nekibroj;
rezultat.setText(str1 + "Nivo alkohola u tvojoj krvi je:" + result);
}
};
});
}}
Strings.xml file:
<resources>
<string name="app_name">Alkometar</string>
<string name="ImeInput">ImeInput</string>
<string name="MasaInput">MasaInput</string>
</resources>
AndroidManifest XML file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.alkometar">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".Pol">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".InformacijeM" />
<activity android:name=".StanjeM" />
<activity android:name=".InformacijeZ" />
<activity android:name=".StanjeZ" />
<activity android:name=".PijemM" />
<activity android:name=".RezultatM"></activity>
</application>
</manifest>
And here is the exception in logCat:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.alkometar, PID: 30732
java.lang.NullPointerException
at com.example.alkometar.RezultatM$1.onClick(RezultatM.java:28)
at android.view.View.performClick(View.java:4463)
at android.view.View$PerformClick.run(View.java:18770)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5292)
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:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
Thank you very much once again! :)))
Change your Activity Two class to:
public class RezultatM extends AppCompatActivity {
TextView rezultat;
String str1,str2;
double masad;
public static final String MyPREFERENCES = "MyPrefs";
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rezultat_m);
rezultat = (TextView) findViewById(R.id.rezultatTekst);
Button button = (Button) findViewById(R.id.button);
//Intent intent = getIntent();
//str1 = intent.getStringExtra("keyIme");
//str2 = intent.getStringExtra("keyMasa");
//getting values from shared preferences
SharedPreferences shared = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
str1=shared.getString("keyIme", "");
str2=shared.getString("keyMasa", "");
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if(str2!=null){
masad = Double.parseDouble(str2);
}
double nekibroj = 0.8;
double result = masad * nekibroj;
rezultat.setText(str1 + "Nivo alkohola u tvojoj krvi je:" + result);
};
});
}}
Also in your Activity one you are starting wrong intent
Intent intent1 = new Intent(InformacijeM.this, RezultatM.class);
intent1.putExtra("keyIme", str1);
intent1.putExtra("keyMasa", str2);
Intent intent = new Intent(InformacijeM.this, StanjeM.class);
// startActivity(intent); //here you are starting another class..check it
//change it to
startActivity(intent1);
change your InformacijeM.java class:
public class InformacijeM extends AppCompatActivity {
EditText ImeTxt, MasaTxt ;
public static final String MyPREFERENCES = "MyPrefs";
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_informacije_m);
sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
// INICIRANJE VREDNOSTI
EditText ImeTxt = (EditText)findViewById(R.id.ImeInput);
final String str1 = ImeTxt.getText().toString();
EditText MasaTxt = (EditText)findViewById(R.id.MasaInput);
final String str2 = MasaTxt.getText().toString();
save_data(str1,str2);
ImageButton btn = (ImageButton)findViewById(R.id.strelica);
// PREBACIVANJE AKTIVITIJA
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(InformacijeM.this, RezultatM.class);
intent1.putExtra("keyIme", str1);
intent1.putExtra("keyMasa", str2);
Intent intent = new Intent(InformacijeM.this, StanjeM.class);
startActivity(intent);
}
});
}
public void save_data(String s1,String s2){
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("keyIme", s1);
editor.putString("keyMasa", s2);
editor.commit();
}
}

NullPointerException MainFragment facebook login

Pretty new to this. I am trying to make a simple facebook login app that once logged in show a few basic user details. When I try to run the app I get the message 'Unfortunately FacebookTest has stopped'. I seem to be getting a NullPointerException but can't for the life of me work out why. Here is my logcat output:
03-25 12:01:16.850 919-919/com.example.robert.facebooktest E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.robert.facebooktest, PID: 919
java.lang.NullPointerException
at com.example.robert.facebooktest.MainFragment$2.onCompleted(MainFragment.java:87)
at com.facebook.Request$1.onCompleted(Request.java:283)
at com.facebook.Request$4.run(Request.java:1668)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
My code is as follows:
MainActivity.java
package com.example.robert.facebooktest;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
public class MainActivity extends FragmentActivity {
private MainFragment mainFragment;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragment = new MainFragment();
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, mainFragment).commit();
} else {
// Or set the fragment from restored state info
mainFragment = (MainFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
}
}
MainFragment.java
package com.example.robert.facebooktest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
public class MainFragment extends Fragment {
TextView name;
TextView location;
TextView gender;
private static final String TAG = "MainFragment";
// Create, automatically open (if applicable), save, and restore the
// Active Session in a way that is similar to Android UI lifecycles.
private UiLifecycleHelper uiHelper;
private View otherView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// To maintain FB Login session
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
// Looks for Login button
LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
authButton.setFragment(this);
// Set View that should be visible after log-in invisible initially
otherView = view.findViewById(R.id.other_views);
otherView.setVisibility(View.GONE);
//authButton.setReadPermissions(Arrays.asList("user_likes", "user_status","email","user_birthday"));
return view;
}
// Called when session changes
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
onSessionStateChange(session, state, exception);
}
};
// When session is changed, this method is called from callback method
private void onSessionStateChange(Session session, SessionState state,Exception exception) {
final TextView name = (TextView) getView().findViewById(R.id.name);
final TextView gender = (TextView) getView().findViewById(R.id.gender);
final TextView location = (TextView) getView().findViewById(R.id.location);
if (state.isOpened()) {
Log.i(TAG, "Logged in...");
// make request to the /me API to get Graph user
Request.newMeRequest(session, new Request.GraphUserCallback() {
// callback after Graph API response with user
// object
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
// Set view visibility to true
otherView.setVisibility(View.VISIBLE);
// Set User name
name.setText("Hello " + user.getName());
// Set Gender
gender.setText("Your Gender: "
+ user.getProperty("gender").toString());
location.setText("Your Current Location: "
+ user.getLocation().getProperty("name").toString());
}else{
return;
}
}
}).executeAsync();
} else if (state.isClosed()) {
Log.i(TAG, "Logged out...");
otherView.setVisibility(View.GONE);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
Log.i(TAG, "OnActivityResult...");
}
#Override
public void onResume() {
super.onResume();
uiHelper.onResume();
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}
}
activity_main.xml
<LinearLayout 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:background="#drawable/bg_gradient"
android:orientation="vertical"
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.example.robert.facebooktest.MainActivity" >
<ImageView
android:layout_width="300dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:src="#drawable/voyager_logo" />
<LinearLayout
android:id="#+id/other_views"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical"
android:padding="5dp" >
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:gravity="left"
android:text="Name"
android:textColor="#color/white"
android:textSize="30dp" />
<TextView
android:id="#+id/gender"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:gravity="left"
android:text="Gender"
android:textColor="#color/white"
android:textSize="15dp" />
<TextView
android:id="#+id/location"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:gravity="left"
android:text="Location"
android:textColor="#color/white"
android:textSize="15dp" />
</LinearLayout>
<LinearLayout
android:id="#+id/fb_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:gravity="bottom"
android:orientation="vertical"
android:padding="5dp" >
<com.facebook.widget.LoginButton
android:id="#+id/authButton"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="30dp" />
</LinearLayout>
Which is the line no 87 exactly? Somewhere in onCompleted()

app cannot run after adding some listeners for three buttons

I just started studying Androdid programming and have come up with some problems. I was trying to implement an app with a textview and three buttons(true_button, false_button, next_question). This project runs well on AVD. Later I added a prev_button and its listener for linking to the previous question. I also added a listener for the textview question_text_view. The Eclipse Indigo reported no error, but when running on an AVD, this program stops immediately after it is launched. Where is the problem? Or, how can I find the problems in programs when using such an IDE? Thank you.
Below are some of the programs for this project. (MainActivity.java, activity_main.xml, TrueFalse.java, strings.xml)
MainActivity.java
package com.example1.geoquiz;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private Button mTrueButton;
private Button mFalseButton;
private Button mNextButton;
private TextView mQuestionTextView;
private Button mNextButton2;
private Button mPrevButton;
private TrueFalse[] mQuestionBank = new TrueFalse[] {
new TrueFalse(R.string.question2, true),
new TrueFalse(R.string.question3, false),
new TrueFalse(R.string.question4, false),
new TrueFalse(R.string.question5, true),
new TrueFalse(R.string.question6, true),
};
private int mCurrentIndex = 0;
private void updateQuestion() {
int question = mQuestionBank[mCurrentIndex].getQuestion();
mQuestionTextView.setText(question);
}
private void checkAnswer(boolean userPressedTrue) {
boolean answerIsTrue = mQuestionBank[mCurrentIndex].isTrueQuestion();
int messageResId = 0;
if(userPressedTrue == answerIsTrue) {
messageResId = R.string.correct_toast;
} else {
messageResId = R.string.incorrect_toast;
}
Toast.makeText(this, messageResId, Toast.LENGTH_SHORT).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mQuestionTextView = (TextView)findViewById(R.id.question_text_view);
mTrueButton = (Button)findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(true);
}
});
mFalseButton = (Button)findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(false);
}
});
mNextButton = (Button)findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
updateQuestion();
}
});
/*Click the textview to get to next question.*/
mNextButton2 = (Button)findViewById(R.id.question_text_view);
mNextButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
updateQuestion();
}
});
mPrevButton = (Button)findViewById(R.id.prev_button);
mPrevButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurrentIndex = (mCurrentIndex - 1) % mQuestionBank.length;
updateQuestion();
}
});
updateQuestion();
}
}
TrueFalse.java
package com.example1.geoquiz;
public class TrueFalse {
private int mQuestion;
private boolean mTrueQuestion;
public TrueFalse(int question, boolean trueQuestion) {
mQuestion = question;
mTrueQuestion = trueQuestion;
}
public int getQuestion() {
return mQuestion;
}
public void setQuestion(int question) {
mQuestion = question;
}
public boolean isTrueQuestion() {
return mTrueQuestion;
}
public void setTrueQuestion(boolean trueQuestion) {
mTrueQuestion = trueQuestion;
}
}
MainActivity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" >
<TextView
android:id="#+id/question_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="#+id/true_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginTop="180dp"
android:text="#string/true_button" />
<Button
android:id="#+id/false_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/true_button"
android:layout_alignLeft="#+id/true_button"
android:layout_marginLeft="130dp"
android:text="#string/false_button" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/next_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/prev_button"
android:layout_alignBottom="#+id/prev_button"
android:layout_alignParentRight="true"
android:layout_marginRight="45dp"
android:text="#string/next_button" />
<Button
android:id="#+id/prev_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="44dp"
android:text="#string/prev_button" />
</RelativeLayout>
</RelativeLayout>
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">GeoQuiz</string>
<string name="question1">Shenzhen is near Hong Kong.</string>
<string name="question2">The Pacific Ocean is larger than the Atlantic Ocean.</string>
<string name="question3">The Suez Canal connects the Red Sea and the Indian Ocean.</string>
<string name="question4">The source of the Nile River is in Egypt.</string>
<string name="question5">The Amazon River is the longest river in the Americas.</string>
<string name="question6">Lake Bakal is the world\'s oldest and deepest freshwater lake.</string>
<string name="true_button">true</string>
<string name="false_button">false</string>
<string name="next_button">Next</string>
<string name="prev_button">Prev</string>
<string name="correct_toast">correct</string>
<string name="incorrect_toast">incorrect</string>
</resources>
/*Click the textview to get to next question.*/
mNextButton2 = (Button)findViewById(R.id.question_text_view);
What did I just see?
TextView is not a button. If you're using TextView, you should cast to TextView in your code, not to Button; and set android:clickable="true" in your layout xml resource file

Categories