How I can show Google Maps V2 into a custom dialog android - java

Hello my name is Hernan so and I am a Android Developer. I make this question because I need insert a google map into a custom dialog I already have my dialog working ok but when I am adding the google map it throws an error in code. This is my code.
Java Code:
package com.sigetdriver.view.popup;
import android.app.Dialog;
import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.sigetdriver.R;
public class InsertarDestinoPopup {
private GoogleMap googleMap;
private Context context;
public Dialog dialog;
private Button btnCerrar;
public void dialog(Context _context) {
context = _context;
dialog = new Dialog(_context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.popup_destino);
dialog.getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
try {
// Loading map
initilizeMap();
pintarMapa();
} catch (Exception e) {
e.printStackTrace();
}
btnCerrar = (Button) dialog.findViewById(R.id.btnCerrar);
btnCerrar.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
dialog.show();
}
/**
* function to load map. If map is not created it will create it for you
* */
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap(); // *******ERROR HERE*******
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(context,
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
private void pintarMapa() {
googleMap.setMyLocationEnabled(true); // false to disable
}
}
XML Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<Button
android:id="#+id/btnCerrar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cerrar" />
</LinearLayout>
I dont know if it is the best way to make a dialog or showing a map into dialog, please I need solve this thanks in advance.
Hernan

You can also use activity as a dialog.Here you can do all normal activity methods.
XML Coding
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map_view"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />
</RelativeLayout>
Java Coding
public class Map extends FragmentActivity {
private View rootView;
GoogleMap map;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setBackgroundDrawable(new ColorDrawable(0));
setContentView(R.layout.map);
this.rootView=findViewById(R.id.map_view);
FragmentManager myFragmentManager = getSupportFragmentManager();
SupportMapFragment mySupportMapFragment = (SupportMapFragment)myFragmentManager.findFragmentById(R.id.map);
map = mySupportMapFragment.getMap();
}
#SuppressLint("NewApi")
#Override
public boolean onTouchEvent(MotionEvent event) {
Rect rect = new Rect();
rootView.getHitRect(rect);
if (!rect.contains((int)event.getX(), (int)event.getY())){
setFinishOnTouchOutside(false);
return true;
}
return false;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
finish();
}
return true;
}
}
Manifest File
Here You change the activity as dialog.
<activity
android:name="com.example.mapindialog.Map"
android:excludeFromRecents="true"
android:launchMode="singleInstance"
android:screenOrientation="landscape"
android:theme="#android:style/Theme.Dialog" >
</activity>

base on your png, it seems like you're using support v4 package,in this case you'll need to replace getFragmentManager with getSupportFragmentManager

Related

Was trying to show the ambient temparature inside the textView, but onSensorChanged method is not working, its not setting the text of textview

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>

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

ProgressBar does not appear in WebView located in Fragment ,how to show ProgressBar in WebView android?

Whenever, I enter the fragment, I am shown a blank space for a few seconds, then the webpage in the WebView shows up. It seems that the ProgressBar does not show.
Here's my XML file for the Fragment the WebView and ProgressBar is in
<?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:orientation="vertical"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".FragmentThree">
<ProgressBar
android:id="#+id/progressbar"
style="#style/Widget.AppCompat.ProgressBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"/>
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent">
</WebView>
</RelativeLayout>
Here is the Java file for the Fragment Java implementation:
package com.example.task1;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class FragmentThree extends Fragment {
private WebView webView;
private String URL;
private ProgressBar progressBar;
private OnFragmentInteractionListener mListener;
public FragmentThree(String url) {
// Required empty public constructor
this.URL = url;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_three, container, false);
initMain(view);
return view;
}
private void initMain(View view) {
webView = view.findViewById(R.id.webview);
progressBar = view.findViewById(R.id.progressbar);
progressBar.setMax(100);
webView.loadUrl(URL);
webView.setWebViewClient(new WebViewClient());
webView.setWebChromeClient(new WebChromeClient(){
#Override
public void onProgressChanged(WebView view, int newProgress) {
progressBar.setProgress(newProgress);
}
});
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
The code is mostly located under the initMain() function for clarification.
Any advice is greatly appreciated, thank you for reading!
Just declare ProgressBar below Webview like this
<?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:orientation="vertical"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".FragmentThree">
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent">
</WebView>
<ProgressBar
android:id="#+id/progressbar"
style="#style/Widget.AppCompat.ProgressBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"/>
</RelativeLayout>

xml layout crashes on loading for android app

enter image description hereHey guys I'm at the end of my Java 1 class working on my project. We are making a memory/concentration game. My issue is that when I click the easy button for the next activity the app crashes. I have tried using fragments and activities and just can't seem to get it right. I have also tried using the layout I need on my main activity just to see if I could get it to display. Even then it just crashes on startup of the app. Any help would be appreciated.
Startup Screen activity.
package com.bignerdranch.android.memory;
import android.app.Activity;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
public class MemoryActivity extends Activity {
private Button mEasy;
private Button mMedium;
private Button mHard;
private CheckBox mSilence;
public MediaPlayer player;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_memory);
player = new MediaPlayer();
player = MediaPlayer.create(this, R.raw.mkstartmusic);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setLooping(true);
player.start();
mEasy = (Button)findViewById(R.id.easy);
mEasy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent easy = new Intent(getApplicationContext(), EasyGame.class);
startActivity(easy);
}
});
mMedium = (Button)findViewById(R.id.medium);
mMedium.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
mHard = (Button)findViewById(R.id.hard);
mHard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
mSilence = (CheckBox)findViewById(R.id.silence);
mSilence.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mSilence.isChecked()) {
player.pause();
} else if(mSilence.isChecked() == false) {
player.start();
}
}
});
}
#Override
protected void onStop() {
super.onPause();
if (player != null){
player.stop();
if (isFinishing()){
player.stop();
player.release();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.layout.activity_memory, menu);
return true;
}
}
Second Activity (Easy option)
package com.bignerdranch.android.memory;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
public class EasyGame extends Activity {
private ImageButton buttOne;
private ImageButton buttTwo;
private ImageButton buttThree;
private ImageButton buttFour;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_easy);
buttOne = (ImageButton)findViewById(R.id.ImageButton01);
buttOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
buttTwo = (ImageButton)findViewById(R.id.ImageButton02);
buttTwo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
buttThree = (ImageButton)findViewById(R.id.ImageButton03);
buttThree.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
buttFour = (ImageButton)findViewById(R.id.ImageButton04);
buttFour.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.layout.activity_easy, menu);
return true;
}
}
This is the layout for the Easy option
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/easyback"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:background="#drawable/easyback"
android:clickable="false"
android:duplicateParentState="false"
android:longClickable="false"
android:scaleType="centerCrop" />
<ImageButton
android:id="#+id/ImageButton04"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_below="#+id/ImageButton01"
android:layout_toRightOf="#+id/ImageButton01"
android:layout_toEndOf="#+id/ImageButton01"
android:maxHeight="25dp"
android:maxWidth="25dp"
android:scaleType="fitXY"
android:src="#drawable/dragonemb" />
<ImageButton
android:id="#+id/ImageButton02"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_above="#+id/ImageButton04"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="22dp"
android:layout_marginEnd="22dp"
android:maxHeight="25dp"
android:maxWidth="25dp"
android:scaleType="fitXY"
android:src="#drawable/dragonemb" />
<ImageButton
android:id="#+id/ImageButton03"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_alignTop="#+id/ImageButton04"
android:layout_toLeftOf="#+id/ImageButton04"
android:layout_toStartOf="#+id/ImageButton04"
android:maxHeight="25dp"
android:maxWidth="25dp"
android:scaleType="fitXY"
android:src="#drawable/dragonemb" />
<ImageButton
android:id="#+id/ImageButton01"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_alignParentTop="true"
android:layout_marginTop="152dp"
android:layout_toLeftOf="#+id/ImageButton02"
android:maxHeight="25dp"
android:maxWidth="25dp"
android:scaleType="fitXY"
android:src="#drawable/dragonemb" />
</RelativeLayout>
OK It's not the full crash log you posted but at the top of it I saw roidManifest.xml?. And It's sure that you didn't defined your EasyGame Activity in your androidmanifest.xml so add this line inside application tag,
<manifest package="com....." . . . >
<application . . . >
<activity
android:name=".EasyGame"
android:label="easygame">
</activity>
. . .
</application>
</manifest>
In addition you are trying to cast your ImageButton into Button consider fixing that as well.
Add code below to AndroidManfest
<activity
android:name=".EasyGame"
/>
its simple just add this line to your AndroidManifest
<activity android:name="Activity"/>
The logcat did mentioned that you need to declare your activity within the Android Manifest which you didn't. please read the logcat carefully as it really helps to find what went wrong.
OK, so I had tried all of your guys suggestions which I had were part of the issue, the final issue turned out to that I needed to add my images to the drawable-xhdpi. Thanks for all your help.

Binary XML file line #13 :Error inflating class fragment

Can anyone please help me resolve this error?
What I'm trying to do is to get current location using google play services and display city name in edit text inside a fragment.
MainActivity.java
package com.example.mylocationwiki;
import java.util.List;
import java.util.Locale;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.app.Activity;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends FragmentActivity implements ConnectionCallbacks,
OnConnectionFailedListener {
private static final String TAG = MainActivity.class.getSimpleName();
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
private Location mLastLocation;
private GoogleApiClient mGoogleApiClient;
private boolean mRequestingLocationUpdates = false;
private LocationRequest mLocationRequest;
String cityname="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (checkPlayServices()) {
buildGoogleApiClient();
}
try {
getLocation();
}
catch (Exception e) {
e.printStackTrace();
}
if(cityname!=null)Log.d("pathanor thik agey ", cityname);
new FragmentA(cityname);
}
private void getLocation() throws Exception{
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
Geocoder gc=new Geocoder(this,Locale.getDefault());
List<Address> addresses=gc.getFromLocation(latitude, longitude, 1);
cityname=addresses.get(0).getLocality();
if(cityname!=null)Log.d("calculate holo ", cityname );
new FragmentA(cityname);
} else{
}
return;
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Toast.makeText(getApplicationContext(),
"This device is not supported.", Toast.LENGTH_LONG)
.show();
finish();
}
return false;
}
return true;
}
#Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
#Override
protected void onResume() {
super.onResume();
checkPlayServices();
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
#Override
public void onConnected(Bundle arg0) {
try {
getLocation();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnectionSuspended(int arg0) {
mGoogleApiClient.connect();
}
}
activity_main.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:background="#00BBFF"
android:gravity="center"
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.mylocationwiki.MainActivity" >
<fragment
android:id="#+id/fragment1"
android:name="com.example.mylocationwiki.FragmentA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" /></RelativeLayout>
FragmentA.java
package com.example.mylocationwiki;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class FragmentA extends Fragment implements View.OnClickListener{
String cityname="";
Button button;
EditText field;
FragmentA(String cityname){
cityname=this.cityname;
if(cityname!=null)Log.d("received ", cityname);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_a, container,false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
button=(Button) getActivity().findViewById(R.id.button1);
field=(EditText)getActivity().findViewById(R.id.editText1);
field.setText(cityname);
}
#Override
public void onClick(View v) {
//
}
}
fragment_a.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFBB00" >
<EditText
android:id="#+id/editText1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_margin="20dp"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText1"
android:layout_below="#+id/editText1"
android:layout_marginTop="37dp"
android:text="Button" />
</RelativeLayout>
What I have tried so far:
Read this this link :
similar question on SO and made the following changes in my project:
1) Included the following imports:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
2) Made sure that MainActivity extends FragmentActivity
3) Decared getActivity() method inside onActivityCreated() method as nicely suggested here
4) Even the following part is included in my manifest as suggested Here
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
Still I fail to resolve the issue. Any more insights please?
Thanks!
I guess the reason is that you don't have a default constructor in your Fragment class. You overloaded the constructor, but Fragment needs an empty one.
Empty Constructor for Extended Fragment
If you need to receive arguments in your fragment, do it using a Bundle:
public static YourFragment getInstance(String argument)
{
YourFragment fragment = new YourFragment();
Bundle bundle = new Bundle();
bundle.putString("argument", argument);
fragment.setArguments(bundle);
return fragment;
}
And from activity:
YourFragment fragment = YourFragment.getInstance(argument);
getFragmentManager().beginTransaction().add(R.id.container, fragment, "fragmentTag").commit();
R.id.container has to be an id of your RelativeLayout (remove <fragment/> from it).
If you still want to use a <fragment/> in xml, then here is a suggestion, how to pass an argument there: If I declare a fragment in an XML layout, how do I pass it a Bundle?

Categories