Android onCreate of Activity class is not triggered - java

I am trying to write a plugin for Capacitor. It should pass the accelerometer data to the JavaScript. The bridge works fine.
However, the heading class does not seem to be initialized. The onCreate function does not seem to be executed, so do all the other functions. Nothing is logged to the console.
In AndroidManifest.xml I have requested the following feature:
<uses-feature android:name="android.hardware.sensor.accelerometer" android:required="true" />
The file looks like this:
package de.example.capmap;
import android.app.Activity;
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.util.Log;
import com.getcapacitor.BridgeActivity;
import de.example.Compass;
public class MainActivity extends BridgeActivity {
private Heading heading;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerPlugin(Compass.class);
heading = new Heading();
}
}
class Heading extends Activity implements SensorEventListener {
private SensorManager sensorManager;
private Sensor mAccelerometer;
private static final String TAG = "Heading";
#Override
public final void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(TAG, "onCreate: Initializing");
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mAccelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(Heading.this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
public void onSensorChanged(SensorEvent event){
Log.i(TAG, "onSensorChanged: " + event.values[0]);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
Log.i(TAG, "onAccuracyChanged:" + accuracy);
}
#Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
}
and the Compass Plugin, which gets executed:
import com.getcapacitor.JSObject;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginHandle;
import com.getcapacitor.PluginMethod;
import com.getcapacitor.annotation.CapacitorPlugin;
import com.getcapacitor.Bridge;
#CapacitorPlugin(name = "Compass")
public class Compass extends Plugin {
public static Bridge staticBridge = null;
#Override
public void load() {
staticBridge = this.bridge;
java.lang.System.out.println("Compass successfully started");
}
public static void onMagneticHeading(float magneticHeading){
Compass pushPlugin = Compass.getCompassInstance();
if (pushPlugin != null) {
pushPlugin.sendMagneticHeading(magneticHeading);
}
}
#PluginMethod()
public void getMagneticHeading(PluginCall call) {
String value = call.getString("value");
JSObject ret = new JSObject();
ret.put("magneticHeading", value);
call.resolve(ret);
}
public void sendMagneticHeading(float magneticHeading) {
JSObject data = new JSObject();
data.put("magneticHeading", magneticHeading);
notifyListeners("heading", data, true);
}
public static Compass getCompassInstance() {
if (staticBridge != null && staticBridge.getWebView() != null) {
PluginHandle handle = staticBridge.getPlugin("Compass");
if (handle == null) {
return null;
}
return (Compass) handle.getInstance();
}
return null;
}
}

How come you're extending an Activity instead of just using a plain class? If it's because you want access to a Context, just pass one in through the constructor (you have one when you create the Heading).
If it's because you want the onPause and onResume lifecycle callbacks, so you know when to register/unregister with the SensorManager, there's a couple of things you could do.
First you can just create some methods the activity can call during onPause/onResume:
class Heading(Context context) {
...
public void sleep() {
sensorManager.unregisterListener(this);
}
public void wake() {
sensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
}
class MainActivity extends BridgeActivity {
...
#Override
protected void onResume() {
super.onResume();
heading.wake();
}
#Override
protected void onPause() {
super.onPause();
heading.sleep();
}
}
The other approach is to make Heading implement DefaultLifecycleObserver, which basically lets you implement onResume and onPause etc like you're doing, and you make it observe the Activity's lifecycle, instead of the Activity having to manually call stuff to be like "hey onPause just happened". I'll just link the example page, but it basically covers what you're doing here (and the earlier, manual example too) as well as some more advanced stuff

Related

How can I show the places suggestions below text box?

I am using mapbox for my apllication where I want to to show the suggestions of places below the textbox...
Below is my code,
In my code what was happening is after clicking on the search button which is a floatingaction button, a search bar opens and it allow us to search for places...
and after that a marker is placed to that location
It looks like this
package com.example.mapboxwithmarker;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import com.google.gson.JsonObject;
import com.mapbox.api.geocoding.v5.models.CarmenFeature;
import com.mapbox.geojson.Feature;
import com.mapbox.geojson.FeatureCollection;
import com.mapbox.geojson.Point;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.camera.CameraPosition;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.geometry.LatLng;
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.plugins.places.autocomplete.PlaceAutocomplete;
import com.mapbox.mapboxsdk.plugins.places.autocomplete.model.PlaceOptions;
import com.mapbox.mapboxsdk.style.layers.SymbolLayer;
import com.mapbox.mapboxsdk.style.sources.GeoJsonSource;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconImage;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.iconOffset;
public class Locationsearch extends AppCompatActivity implements OnMapReadyCallback {
private static final int REQUEST_CODE_AUTOCOMPLETE = 1;
private MapView mapView;
private MapboxMap mapboxMap;
private CarmenFeature home;
private CarmenFeature work;
private String geojsonSourceLayerId = "geojsonSourceLayerId";
private String symbolIconId = "symbolIconId";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Mapbox access token is configured here. This needs to be called either in your application
// object or in the same activity which contains the mapview.
Mapbox.getInstance(this, getString(R.string.mapbox_access_token));
// This contains the MapView in XML and needs to be called after the access token is configured.
setContentView(R.layout.activity_locationsearch);
mapView = findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(this);
}
#Override
public void onMapReady(#NonNull final MapboxMap mapboxMap) {
this.mapboxMap = mapboxMap;
mapboxMap.setStyle(Style.MAPBOX_STREETS, new Style.OnStyleLoaded() {
#Override
public void onStyleLoaded(#NonNull Style style) {
initSearchFab();
addUserLocations();
// Add the symbol layer icon to map for future use
style.addImage(symbolIconId, BitmapFactory.decodeResource(
Locationsearch.this.getResources(), R.drawable.ic_location_on));
// Create an empty GeoJSON source using the empty feature collection
setUpSource(style);
// Set up a new symbol layer for displaying the searched location's feature coordinates
setupLayer(style);
}
});
}
private void initSearchFab() {
findViewById(R.id.fab_location_search).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new PlaceAutocomplete.IntentBuilder()
.accessToken(Mapbox.getAccessToken() != null ? Mapbox.getAccessToken() : getString(R.string.mapbox_access_token))
.placeOptions(PlaceOptions.builder()
.backgroundColor(Color.parseColor("#EEEEEE"))
.limit(10)
.addInjectedFeature(home)
.addInjectedFeature(work)
.build(PlaceOptions.MODE_CARDS))
.build(Locationsearch.this);
startActivityForResult(intent, REQUEST_CODE_AUTOCOMPLETE);
}
});
}
private void addUserLocations() {
home = CarmenFeature.builder().text("Mapbox SF Office")
.geometry(Point.fromLngLat(-122.3964485, 37.7912561))
.placeName("50 Beale St, San Francisco, CA")
.id("mapbox-sf")
.properties(new JsonObject())
.build();
work = CarmenFeature.builder().text("Mapbox DC Office")
.placeName("740 15th Street NW, Washington DC")
.geometry(Point.fromLngLat(-77.0338348, 38.899750))
.id("mapbox-dc")
.properties(new JsonObject())
.build();
}
private void setUpSource(#NonNull Style loadedMapStyle) {
loadedMapStyle.addSource(new GeoJsonSource(geojsonSourceLayerId));
}
private void setupLayer(#NonNull Style loadedMapStyle) {
loadedMapStyle.addLayer(new SymbolLayer("SYMBOL_LAYER_ID", geojsonSourceLayerId).withProperties(
iconImage(symbolIconId),
iconOffset(new Float[] {0f, -8f})
));
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_AUTOCOMPLETE) {
// Retrieve selected location's CarmenFeature
CarmenFeature selectedCarmenFeature = PlaceAutocomplete.getPlace(data);
// Create a new FeatureCollection and add a new Feature to it using selectedCarmenFeature above.
// Then retrieve and update the source designated for showing a selected location's symbol layer icon
if (mapboxMap != null) {
Style style = mapboxMap.getStyle();
if (style != null) {
GeoJsonSource source = style.getSourceAs(geojsonSourceLayerId);
if (source != null) {
source.setGeoJson(FeatureCollection.fromFeatures(
new Feature[] {Feature.fromJson(selectedCarmenFeature.toJson())}));
}
// Move map camera to the selected location
mapboxMap.animateCamera(CameraUpdateFactory.newCameraPosition(
new CameraPosition.Builder()
.target(new LatLng(((Point) selectedCarmenFeature.geometry()).latitude(),
((Point) selectedCarmenFeature.geometry()).longitude()))
.zoom(14)
.build()), 4000);
}
}
}
}
// Add the mapView lifecycle to the activity's lifecycle methods
#Override
public void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onStart() {
super.onStart();
mapView.onStart();
}
#Override
protected void onStop() {
super.onStop();
mapView.onStop();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
}
But what I want to achieve is I want to use one EditText as a search box and show the result(suggestions) below the edittext...
How can I achieve this?

I am working on a simple pedometer app, and it has these errors, for the following code

package com.example.ritwik.letswalk;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements SensorEventListener{
TextView tv_steps;
SensorManager sensorManager;
boolean running=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_steps=(TextView) findViewById(r.id.tv_steps);
sensorManager=(SensorManager) getSystemService(Context.SENSOR_SERVICE);
}
#Override
protected void onResume()
{
super.onResume();
running=true;
Sensor countSensor=sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
if(countSensor==null){
sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI);
}
else
Toast.makeText(this, "Sensor Not Found",Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause()
{
super.onPause();
running=false;
}
#Override
protected void onSensorChangeed(SensorEvent event)
{
if(running)
{
tv_steps.setText(String.valueOf(event.values[0]));
}
}
}
the code has the following errors
Error:(21, 15) error: cannot find symbol class TextView
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
Compilation failed; see the compiler error output for details. Error:(12, 5) error: cannot find symbol class TextView Error:(43, 37)
error: cannot find symbol class SensorEvent Error:(11, 8) error:
MainActivity is not abstract and does not override abstract method
onAccuracyChanged(Sensor,int) in SensorEventListener Error:(21, 39)
error: package r does not exist Error:(42, 5) error: method does not
override or implement a method from a supertype
SensorEventListener has two abstract methods :
1) onAccuracyChanged(Sensor sensor, int accuracy)
2) onSensorChanged(SensorEvent event)
You need to override onAccuracyChanged method too.
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
This method is called when the accuracy of sensor changes. If you don't wish to do anything here then do not write any code here. But since its abstract you need to implement it.
Hope it helps.
In my pedometer app I did
public void onSensorChanged(SensorEvent event) {
Sensor sensor = event.sensor;
float[] values = event.values;
if (values.length > 0) {
value = (int) values[0];
}
if (sensor.getType() == Sensor.TYPE_STEP_COUNTER) {
textView.setText("" + value);
}
}
public void onAccuracyChanged(Sensor sensor,int a){}
If you want the whole code: Here it is:
import android.app.Activity;
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;
public class CounterActivity extends Activity implements SensorEventListener {
private TextView textView;
private SensorManager mSensorManager;
private Sensor mStepCounterSensor;
private Sensor mStepDetectorSensor;
int value = -1; //Step Counter
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.counter_activity);
textView = (TextView) findViewById(R.id.steps);
mSensorManager = (SensorManager)
getSystemService(Context.SENSOR_SERVICE);
mStepCounterSensor = mSensorManager
.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
mStepDetectorSensor = mSensorManager
.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);
}
public void onAccuracyChanged(Sensor sensor,int a){}
public void onSensorChanged(SensorEvent event) {
Sensor sensor = event.sensor;
float[] values = event.values;
if (values.length > 0) {
value = (int) values[0];
}
if (sensor.getType() == Sensor.TYPE_STEP_COUNTER) {
textView.setText("" + value);
}
}
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mStepCounterSensor,
SensorManager.SENSOR_DELAY_FASTEST);
mSensorManager.registerListener(this, mStepDetectorSensor,
SensorManager.SENSOR_DELAY_FASTEST);
}
protected void onStop() {
super.onStop();
mSensorManager.unregisterListener(this, mStepCounterSensor);
mSensorManager.unregisterListener(this, mStepDetectorSensor);
}
}

How can I track how many miles the user has walked?

I have made some java code in android studio to where it counts how many steps someone takes but I'm not sure how I can make it to where it counts how many miles the user walks. Here is the code.
If anyone can tell me how to do it that would be appreciated, Thanks.
package com.example.andyheggis.healthapp;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements SensorEventListener {
TextView tv_steps;
SensorManager sensorManager;
boolean running = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_steps = (TextView) findViewById(R.id.tv_steps);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
}
#Override
protected void onResume() {
super.onResume();
running = true;
Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
if(countSensor != null) {
sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI);
} else {
Toast.makeText(this, "Sensor not found!", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onPause() {
super.onPause();
running = false;
//if you unregister the hardware will stop detecting steps
//sensorManager.unregisterListener(this);
}
#Override
public void onSensorChanged(SensorEvent event) {
if(running) {
tv_steps.setText(String.valueOf(event.values[0]));
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}

When screen rotates users can cheat Android

I am following Big Nerd Ranch guide Android in which I am building a basic application which displays a set of questions and you say true or false. There is a button 'Cheat' where in you can cheat. If you hit the button Cheat see the answer, come back and type the correct answer then there is a toast displayed 'Cheating is wrong'. This works fine in vertical screen but lets say I rotate the screen to horizontal, I view the answer and come back to horizontal, I can cheat. I dont want that to happen.
My Effort:
using onSavedInstanceState to override the existing function to share values between screens & keeping track of the value in onCreate
#Override
public void onSaveInstanceState(Bundle savedInstanceState)
{
super.onSaveInstanceState(savedInstanceState);
Log.i(TAG, "onSaveInstanceState");
savedInstanceState.putBoolean(EXTRA_ANSWER_SHOWN, mAnswerIsTrue) ;
}
In onCreate method,
if(savedInstanceState !=null)
{
mAnswerIsTrue = savedInstanceState.getBoolean(EXTRA_ANSWER_SHOWN);
setAnswerShownResult(mAnswerIsTrue);
}
Here is my code:
package com.android.geoquiz;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class CheatActivity extends Activity
{
//Extras
public static final String EXTRA_ANSWER_IS_TRUE = "com.android.geoquiz.answer_is_true";
public static final String EXTRA_ANSWER_SHOWN = "com.android.geoquiz.answer_shown";
private static final String TAG="CheatActivity";
private static final String KEY_INDEX = "cheat";
private boolean mAnswerIsTrue;
private TextView mAnswerTextView;
private Button mShowAnswer;
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.showAnswerButton);
setAnswerShownResult(false);
mShowAnswer = (Button)findViewById(R.id.showAnswerButton);
mShowAnswer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mAnswerIsTrue)
{
mAnswerTextView.setText(R.string.true_button);
}
else
{
mAnswerTextView.setText(R.string.false_button);
}
setAnswerShownResult(true);
}
});
if(savedInstanceState !=null)
{
mAnswerIsTrue = savedInstanceState.getBoolean(KEY_INDEX, false);
}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState)
{
super.onSaveInstanceState(savedInstanceState);
Log.i(TAG, "onSaveInstanceState");
savedInstanceState.putBoolean(KEY_INDEX, mAnswerIsTrue) ;
}
#Override
public void onStart()
{
super.onStart();
Log.d(TAG, "onStart() called");
}
#Override
public void onPause()
{
super.onPause();
Log.d(TAG, "onPause() called");
}
#Override
public void onResume()
{
super.onResume();
Log.d(TAG, "onResume() called");
}
#Override
public void onStop()
{
super.onStop();
Log.d(TAG, "onStop() called");
}
#Override
public void onDestroy()
{
super.onDestroy();
Log.d(TAG, "onDestroy() called");
}
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
}
}
This is happening because your onCreate is being called once the user rotates the screen there is simple solution to stop onCreate from being called onOrientationChanged
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden" />
now when you do this you have to overide a method in your activity class like you have onCreate , onPause you will need to add another method named onConfigChanged();
now whenever your screen is rotated this method is gonna be fired instead of activity being created again and again.
add this to your activity class
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
}
Hope this helps. if you need any help feel free to ask.
for more info read these posts.
Activity restart on rotation Android
How do I disable orientation change on Android?
http://developer.android.com/guide/topics/manifest/activity-element.html#config
In your manifest add this to your activity
android:configChanges="orientation|screenSize"
And in your Activity listen for config changes
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
System.out.println(newConfig.toString());
if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
Toast.makeTest(this,"portrait",Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeTest(this,"landscape",Toast.LENGTH_SHORT).show();
}
}

CursorLoader does not refresh data

I'm creating application to add movie data via external web service to internal database and display list of movies as the main activity in ListFragment, another activity is responsible for search function.
ListFragment mentioned above fetches data from database using LoaderManager. Also this fragment is retained using setRetainInstance(true).
Problem that I encounter is that when I navigate to search, add something to database, and go back to ListFragment by pressing Back Button its not refreshed i.e. added movie is not displayed.
A few important things:
I'm not using ContentProvider so I manually retrieve Cursor from my data base in onCreateLoaderMethod.
I'm using support library - I hope that all imports are proper (if someone could check).
ListFragment uses custom CursorAdapter as its view.
Here is the code:
package com.mp.movieplanner;
import android.app.Activity;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import com.mp.movieplanner.data.DataManager;
public class MovieListFragment extends ListFragment
implements LoaderManager.LoaderCallbacks<Cursor> {
public static String TAG = MovieListFragment.class.getSimpleName();
private OnMovieSelectedListener mCallback;
private DataManager mDataManager;
private MovieCursorAdapter mAdapter;
public interface OnMovieSelectedListener {
public void onMovieSelected(int position);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Log.i(TAG, "onAttach(Activity)");
mDataManager = ((MoviePlannerApp)activity.getApplication()).getDataManager();
try {
mCallback = (OnMovieSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnMovieSelectedListener");
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate(Bundle)");
final int layout = Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB ? android.R.layout.simple_list_item_activated_1
: android.R.layout.simple_list_item_1;
setRetainInstance(true);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
Log.i(TAG, "onActivityCreated(Bundle)");
super.onActivityCreated(savedInstanceState);
mAdapter = new MovieCursorAdapter(getActivity(), null, 0);
setListAdapter(mAdapter);
getLoaderManager().initLoader(0, null, this);
}
#Override
public void onStart() {
super.onStart();
Log.i(TAG, "onStart()");
if (getFragmentManager().findFragmentById(R.id.movie_details_fragment) != null) {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
}
#Override
public void onResume() {
super.onResume();
Log.i(TAG, "onResume()");
}
#Override
public void onDetach() {
super.onDetach();
Log.i(TAG, "onDetach()");
mCallback = null;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Notify the parent activity of selected item
if (mCallback != null) {
mCallback.onMovieSelected(position);
// Set the item as checked to be highlighted when in two-pane layout
getListView().setItemChecked(position, true);
}
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(getActivity()) {
#Override
public Cursor loadInBackground() {
return mDataManager.getMovieCursor();
}
};
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> arg0) {
mAdapter.swapCursor(null);
}
#Override
public void onPause() {
Log.i(TAG, "onPause()");
super.onPause();
}
#Override
public void onStop() {
Log.i(TAG, "onStop()");
super.onStop();
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy()");
}
}
I would advise:
#Override
public void onResume() {
super.onResume();
Log.i(TAG, "onResume()");
getLoaderManager().restartLoader(0, null, this);
}
#Override
public void onResume() {
super.onResume();
Log.i(TAG, "onResume()");
getLoaderManager().initLoader(0, null, this);
}
try that

Categories