I am trying to develop a simple app that outputs the temperature using a SensorManager to read and set the value from the temperature sensor. But whenever I run the code, nothing outputs, and I get a message saying the SensorManager keeps stopping. Can someone please point out what the root of the problem is? Here is my code:
MainActivity.java
package com.zybooks.sensormanager;
import androidx.appcompat.app.AppCompatActivity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements SensorEventListener {
private SensorManager sensorManager;
private Sensor thermometer;
private TextView tempValues;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
thermometer = sensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
tempValues = findViewById(R.id.temperatureValues);
}
#Override
public final void onAccuracyChanged(Sensor sensor, int accuracy) {
// Do something here if sensor accuracy changes.
}
#Override
public final void onSensorChanged(SensorEvent event) {
tempValues.setText((int) event.values[0]);
}
#Override
protected void onResume() {
// Register a listener for the sensor.
super.onResume();
sensorManager.registerListener(this, thermometer, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause() {
// Be sure to unregister the sensor when the activity pauses.
super.onPause();
sensorManager.unregisterListener(this, thermometer);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="419dp"
android:layout_height="91dp"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/barTitle"
android:layout_width="179dp"
android:layout_height="36dp"
android:layout_marginBottom="23dp"
android:text="Thermometer"
android:textColor="#8BC34A"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="#+id/toolbar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="#+id/toolbar" />
<TextView
android:id="#+id/temperatureValues"
android:layout_width="191dp"
android:layout_height="77dp"
android:text="Temperature"
android:textAlignment="center"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/toolbar"
app:layout_constraintVertical_bias="0.44" />
</androidx.constraintlayout.widget.ConstraintLayout>
It looks like replacing the code in the onSensorChanged function with this code solved my problem:
float ambient_temperature = event.values[0];
tempValues.setText("Temperature:\n " + String.valueOf(ambient_temperature));
Plus, I had to move the bar in my virtual sensor so a number would actually output.
Related
I am trying to show results in text view but it's not showing temperature in text view. My device has a sensor,when I set text through the if statement inside oncreate it works. It's just onSensorchanged that is not working, even tried to make toast inside the onSensorChanged but it's not working.
package com.example.lab4sensor;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements SensorEventListener {
private TextView txtview;
private SensorManager sensormanager;
private Sensor sensOR;
private boolean sensorAvailable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtview = findViewById(R.id.txtTemp);
sensormanager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
if(sensormanager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE)!=null){
sensOR = sensormanager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
//txtview.setText("set temp");
sensorAvailable = true;
}else{
txtview.setText("Temparature Sensor is not available");
sensorAvailable = false;
}
}
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
txtview.setText(sensorEvent.values[0]+" °C");
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
protected void onResume() {
super.onResume();
if(sensorAvailable = true){
sensormanager.registerListener(this,sensOR,SensorManager.SENSOR_DELAY_NORMAL);
}else{
Toast.makeText(this,"Not available",Toast.LENGTH_LONG).show();
}
}
#Override
protected void onPause() {
super.onPause();
if(sensorAvailable =true){
sensormanager.unregisterListener(this);
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/txtTemp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
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
I cant operate with two relative layouts (one in another). my app doesn't starts. it keeps stopping. I am using a physical device (Samsung Galaxy On Max) for running my apps from android studio.
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"
tools:context=".MainActivity">
<Button
android:id="#+id/Next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="161dp"
android:layout_marginTop="340dp"
android:layout_marginEnd="162dp"
android:onClick="Next"
android:text="Next"
android:visibility="visible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/newLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="invisible">
<TextView
android:id="#+id/nextText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="132dp"
android:layout_marginTop="354dp"
android:layout_marginEnd="132dp"
android:background="#F30808"
android:text="There you Go!"
android:textColor="#0B0A0A"
android:textSize="24sp"
android:visibility="visible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Java file:
package com.example.twolayouts;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView nextText;
Button Next;
RelativeLayout newLayout;
public void Next(View view)
{
Next.setVisibility(View.INVISIBLE);
newLayout.setVisibility(View.VISIBLE);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nextText=(TextView)findViewById(R.id.nextText);
Next=(Button)findViewById(R.id.Next);
newLayout=(RelativeLayout)findViewById(R.id.newLayout);
}
}
Why you are creating object of relative layout while your layout in xml is constraint layout.
Try this :
public class MainActivity extends AppCompatActivity {
TextView nextText;
Button Next;
ConstraintLayout newLayout;
public void Next(View view)
{
Next.setVisibility(View.INVISIBLE);
newLayout.setVisibility(View.VISIBLE);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nextText=(TextView)findViewById(R.id.nextText);
Next=(Button)findViewById(R.id.Next);
newLayout=(ConstraintLayout)findViewById(R.id.newLayout);
}
}
You should try looking into your logcat windows it will help you out for what error you are facing.
Kindly check on which line of code the app is crashing. Post your error log here !
problem is you used constraint layout in your xml layout file and creating object of relative layout in java file
replace below line :
RelativeLayout newLayout;
with :
ConstraintLayout newLayout;
I am making an app an tried using setContentView in Android Studio when i used it the layout changed but the app is still using the first java it is not changing the code is given bellow
i tried changing the file up i also tried creating a new empty file but it didnt work
:-
import androidx.appcompat.app.AppCompatActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
private Handler mHandler = new Handler();
private int progress = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ProgressBar progressBar = findViewById(R.id.progressBar);
new Thread(new Runnable() {
#Override
public void run() {
while(progress < 100) {
progress++;
android.os.SystemClock.sleep(25);
mHandler.post(new Runnable() {
#Override
public void run() {
progressBar.setProgress(progress);
}
});
}
mHandler.post(new Runnable() {
#Override
public void run() {
setContentView(R.layout.activity_on_boarding);
}
});
}
}).start();
}
}
xml:-
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ImageView
android:id="#+id/imageView"
android:layout_width="187dp"
android:layout_height="141dp"
android:contentDescription="#string/logo"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.137"
app:srcCompat="#drawable/logo" />
<TextView
android:id="#+id/title"
android:layout_width="307dp"
android:layout_height="210dp"
android:text="#string/title"
android:textColor="#000000"
android:textSize="40sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.52"
tools:fontFamily="casual"
/>
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="300dp"
android:layout_height="32dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.795" />
</androidx.constraintlayout.widget.ConstraintLayout>
second java:-
package com.thebetterside.wallex;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.os.Bundle;
public class OnBoarding extends AppCompatActivity {
private Button go = findViewById(R.id.go);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_on_boarding);
go.setOnClickListener(
new Button.OnClickListener(){
#Override
public void onClick(View v) {
setContentView(R.layout.activity_name);
}
}
);
}
}
2nd xml:-
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".OnBoarding">
<Button
android:id="#+id/go"
android:layout_width="351dp"
android:layout_height="44dp"
android:background="#drawable/rounded_corner_peach"
android:text="#string/go"
android:textColor="#000046"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.504"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.945" />
</androidx.constraintlayout.widget.ConstraintLayout>
You want to do startActivity(this, OnBoarding.class) instead of calling the setContentView()
setContentView() sets the layout for the current activity, it does not start the second one.
And judging from the code you posted, you want to transfer control to your other java file (OnBoarding.java) and that must be done by starting that activity explicitly.
EDIT: in your case, it'll most probably be MainActivity.this.startActivity(MainActivity.this, OnBoarding.class) because just this will point to the thread, instead of the enclosing Context/Activity
I'm now trying something with a youtube custom player. I'm trying to have it play a video containing a playlist of a certain game's original soundtracks.
The thing is, everything was done by the book (again), yet I still have this concurring problem of force stopping every time I tried to open the APK. Here are the code :
XML :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="20dp"
android:orientation="vertical"
tools:context=".MainActivity">
<view
android:id="#+id/YoutubePlayView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/buttonPlay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Play Video" />
</LinearLayout>
Java :
package my.videoplayerapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
YouTubePlayerView mYoutubePlayerView;
Button PlayVidButton;
YouTubePlayer.OnInitializedListener mOnInitializedListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate: Starting.");
PlayVidButton = findViewById(R.id.buttonPlay);
mYoutubePlayerView = findViewById(R.id.YoutubePlayView);
mOnInitializedListener = new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
Log.d(TAG, "onClick: Initialization Done.");
youTubePlayer.loadVideo("DBToMwdYBME");
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
Log.d(TAG, "onClick: Initialization Failed.");
}
};
PlayVidButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: Initializing Youtube Player.");
mYoutubePlayerView.initialize((YoutubeVidPlayerConfig.getApiKey()), mOnInitializedListener);
Log.d(TAG, "onClick: Initialization Done.");
}
});
}
}
Logcat, linked : https://drive.google.com/open?id=1w5TfCIfyCWCrOZmrjb0lzTpndoQc2SJ0
I'm trying to actually be able to play the video through the button, I know the method of playing the next video or even playing sequence of videos, I just don't know why it keeps on crashing as I speak right now...
Any help would be appreciated in advance!
You have a view with the id of "YoutubePlayView" but your class is called "YoutubePlayerView". Change one of them and it should work (well it shouldn't force close at this spot).