ProgressBar while loading ListView (using AsyncTask) - android-layout

I'm trying to show a progress bar when loading a custom ListView and afterwards - hide it.
I'm using ASync task, but for some reason - The content view is not set and the previous layout view is stuck until all the list view is loaded.
Here is my code:
private ListView listViewGameResults;
protected View dialogLayout;
protected ArrayList<Game> listGames;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.adresults);
GameResultsLoader gameResultsLoader = new GameResultsLoader();
gameResultsLoader.execute();
}
private class GameResultsLoader extends AsyncTask<Void, Void, Void> {
private GameResultsAdapter adapter;
public GameResultsLoader() {
}
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(Void... params) {
try {
listGames = GameResultsCache.getInstance().getGameResults();
adapter = new GameResultsAdapter(getBaseContext(), listGames);
listViewGameResults = (ListView)findViewById(R.id.listViewGameResults);
}
catch (Exception e) {
// TODO Auto-generated catch block
finish();
}
return null;
}
#Override
protected void onPostExecute(Void res) {
listViewGameResults.setAdapter(adapter);
listViewGameResults.setDivider(null);
listViewGameResults.setDividerHeight(0);
ProgressBar pb = (ProgressBar)findViewById(R.id.progressbar_loading);
pb.setVisibility(View.GONE);
}
}
ProgressBar and ListView in my layout:
<ProgressBar
style="?android:attr/progressBarStyle"
android:layout_centerInParent="true"
android:id="#+id/progressbar_loading"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/listViewGameResults"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="1dip"
android:layout_below="#+id/upperstrip"
android:layout_above="#+id/ivDownStrip" />

You need to set default visibility of progressBar gone.and onPreExecute()set Visible and onPostExecute()set gone.
<ProgressBar
style="?android:attr/progressBarStyle"
android:layout_centerInParent="true"
android:id="#+id/progressbar_loading"
android:visibility="gone"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ListView
android:id="#+id/listViewGameResults"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="1dip"
android:layout_below="#+id/upperstrip"
android:layout_above="#+id/ivDownStrip" />
your Activity should look like this
public class demo extends Activity{
private ListView listViewGameResults;
protected View dialogLayout;
protected ArrayList<Game> listGames;
progressBar progress;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.adresults);
progress=(ProgressBar)findViewByid(R.id.progressbar_loading);
GameResultsLoader gameResultsLoader = new GameResultsLoader(this);
gameResultsLoader.execute();
}
}
Use one separate class for AsyncTask
public class GameResultsLoader extends AsyncTask<Void, Void, Void> {
private GameResultsAdapter adapter;
Demo demo;
public GameResultsLoader(Demo demo) {
this.demo=demo;
}
#Override
protected void onPreExecute() {
demo.progress.setvisibility(View.Visible);
}
#Override
protected Void doInBackground(Void... params) {
try {
listGames = GameResultsCache.getInstance().getGameResults();
adapter = new GameResultsAdapter(getBaseContext(), listGames);
listViewGameResults = (ListView)findViewById(R.id.listViewGameResults);
}
catch (Exception e) {
// TODO Auto-generated catch block
finish();
}
return null;
}
#Override
protected void onPostExecute(Void res) {
listViewGameResults.setAdapter(adapter);
listViewGameResults.setDivider(null);
listViewGameResults.setDividerHeight(0);
ProgressBar pb = (ProgressBar)findViewById(R.id.progressbar_loading);
demo.progress.setVisibility(View.GONE);
}
}

if your using asnkTask that is work on main Thread so application is much more load.so better solution is using Service.class.
downlaod this example Check this link all are solution are there and download it:
you have to also get list from relaunch this application.
https://github.com/PankajSavaliyaGit/Upload-List

you have to write code to start progressDialog in preExecute method and at the postExecute dismiss it.
#Override
protected void onPreExecute() {
proDialog = new ProgressDialog(context);
proDialog.setTitle("App name");
proDialog.setMessage("Loding...");
proDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
//proDialog.setIcon(R.drawable.)
proDialog.setCancelable(true);
proDialog.show();
}
#Override
protected void onPostExecute(Void res) {
proDialog.dismiss();
}

The first thing you can do is put Progress bar code after OnCreate method. But the best thing is to create a simple method for Progress bar and only call it in OnCreate method.
The following code worked fine for me:
private void showDialog() {
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Have a nice time");
progressDialog.setMessage("Please wait while showing Titles :) ");
progressDialog.setCancelable(true);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();
}
And then call this method in OnCreate
showDialog();
You can stop Progress when the data is ready to view using:
progressDialog.dismiss();
I hope this is helpful.

Related

My App crashing due to the inMobi Banner Ads can i know where i am wrong in the code

I have written Inmobi Banner code but my app is crashing, please can anyone help what is wrong. MainActivity.java and Activity_main.xml codes are as below.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private InMobiBanner mBanner;
private static final String TAG = MainActivity.class.getName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
InMobiSdk.setLogLevel(InMobiSdk.LogLevel.DEBUG);
mBanner = findViewById(R.id.banner);
setupBannerAd();
JSONObject consentObject = new JSONObject();
try {
// Provide correct consent value to sdk which is obtained by User
consentObject.put(InMobiSdk.IM_GDPR_CONSENT_AVAILABLE, true);
// Provide 0 if GDPR is not applicable and 1 if applicable
consentObject.put("gdpr", "0");
} catch (JSONException e) {
e.printStackTrace();
}
InMobiSdk.init(this, "a4d02aad2f14407782fdd6053fa5988f", consentObject, error -> {
if (null != error) {
Log.e(TAG, "InMobi Init failed -" + error.getMessage());
} else {
Log.d(TAG, "InMobi Init Successful");
}
});
}
private void setupBannerAd() {
mBanner.setListener(new BannerAdEventListener() {
#Override
public void onAdLoadSucceeded(#NonNull InMobiBanner inMobiBanner,
#NonNull AdMetaInfo adMetaInfo) {
Log.d(TAG, "onAdLoadSucceeded with bid " + adMetaInfo.getBid());
}
#Override
public void onAdLoadFailed(#NonNull InMobiBanner inMobiBanner, #NonNull InMobiAdRequestStatus inMobiAdRequestStatus) {
Log.d(TAG, "Banner ad failed to load with error: " +
inMobiAdRequestStatus.getMessage());
}
#Override
public void onAdClicked(#NonNull InMobiBanner inMobiBanner, #NonNull Map<Object, Object> map) {
Log.d(TAG, "onAdClicked");
}
#Override
public void onAdDisplayed(#NonNull InMobiBanner inMobiBanner) {
Log.d(TAG, "onAdDisplayed");
}
#Override
public void onAdDismissed(#NonNull InMobiBanner inMobiBanner) {
Log.d(TAG, "onAdDismissed");
}
#Override
public void onUserLeftApplication(#NonNull InMobiBanner inMobiBanner) {
Log.d(TAG, "onUserLeftApplication");
}
#Override
public void onRewardsUnlocked(#NonNull InMobiBanner inMobiBanner, #NonNull Map<Object, Object> map) {
Log.d(TAG, "onRewardsUnlocked");
}
});
mBanner.load();
}
}
ActivityMain.XML Code
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:ads="http://schemas.android.com/apk/lib/com.inmobi.ads"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<com.inmobi.ads.InMobiBanner
android:id="#+id/banner"
android:layout_width="320dp"
android:layout_height="50dp"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
ads:placementId="plid-1638544811338"
ads:refreshInterval="60"/>
</RelativeLayout>
The problem is InMobi Banner expects InMobiSDK to be initialized, Now in the code if you see you have added InMobiBanner in xml and when you do setContentView the InMobiBanner will expect InMobiSDK to be initialized but the InMobiSDK code initialization is written after the setContentView. Hence it will throw an exception and your app will crash.
Solution would be to add init code before setContentView or to programmatically add Banner View to your UI

NestedScrollView inside fragment not programatically scrolling

I have a tablayout with a viewpager2 and FragmentStateAdapter. I have 3 tabs, each with a NestedScrollView that wraps a Linear Layout:
<androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="#+id/scrollView"
android:focusableInTouchMode="true"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:descendantFocusability="blocksDescendants">
/* ... */
</LinearLayout>
</androidx.core.widget.NestedScrollView>
When I switch between the tabs in the tablayout, the scrollview does not start at the top. In the onViewCreated() method of each Fragment for the viewPager, I added the following lines, however the scrollview still does not scroll to the top, it starts where it was left off.
public static class MyFragment extends Fragment {
private NestedScrollView scrollView;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
scrollView = view.findViewById(R.id.scrollView);
scrollView.smoothScrollTo(0, 0);
}
}
The solution from #star4z should work, but there is an easier option. What you could do instead, use FragmentPagerAdapter for this and set it's behavior to BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT.
Every time, you change your tab, onResume will be called and there you can call your scrollView.smoothScrollTo(0, 0);
public class MyAdapter extends FragmentPagerAdapter {
...
public MyAdapter(FragmentManager fm) {
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
}
...
}
And then in your Fragment:
public class MyFragment extends Fragment {
...
public void onResume() {
super.onResume();
scrollView.smoothScrollTo(0, 0);
}
...
}
onViewCreated is only called when the Fragments are first created. A ViewPager does not change the state of the Fragments. You can think of the hidden Fragments being stored, visible, to the sides of the currently visible Fragment.
I accomplished by setting up a callback when the TabLayout changes. The TabLayout is where the listener for this is. You can then have it call a callback method in your FragmentPagerAdapter. In each Fragment, you should implement a method that returns a callback. In the FragmentPagerAdapter, use the getItem(int position) to store the callback from the Fragment in a Map. The callback method in the adapter takes the position from the TabLayout
First, in your Fragments, give them a method that returns some kind of callback (I used a Runnable) that will be called from the adapter.
public class PlaceHolderFragment extends Fragment {
...
public Runnable getOnTabChangedListener() {
return new Runnable() {
#Override
public void run() {
scrollView.smoothScrollTo(0, 0);
}
};
}
...
}
Then, in your FragmentPagerAdapter (I called mine SectionsPagerAdapter), store the callbacks in a map in the getItem() method, and then add a custom callback.
public class SectionsPagerAdapter extends FragmentPagerAdapter {
...
HashMap<Integer, Runnable> tabChangedCallbacks = new HashMap<>();
...
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
PlaceholderFragment fragment = PlaceholderFragment.newInstance(position + 1);
tabChangedCallbacks.put(position, fragment.getOnTabChangedListener());
return fragment;
}
public void onTabChanged(int position) {
tabChangedCallbacks.get(position).run();
}
...
}
In your activity that contains the TabLayout, you will want to call addOnTabSelectedListener() on the TabLayout in the onCreate() method.
protected void onCreate(Bundle savedInstanceState) {
...
final SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
final ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
tabs.addOnTabSelectedListener(
new TabLayout.ViewPagerOnTabSelectedListener(viewPager) {
#Override
public void onTabSelected(TabLayout.Tab tab) {
super.onTabSelected(tab);
sectionsPagerAdapter.onTabChanged(tab.getPosition());
}
});
...
}
EDIT
The principle is the same, but for this to work using ViewPager2 and FragmentStateAdapter, you will need the follow changes:
The Fragment stays the same.
The adapter is the same, functionally, with some updated methods:
public class SectionsStateAdapter extends FragmentStateAdapter {
HashMap<Integer, Runnable> tabChangedCallbacks = new HashMap<>();
...
public void onTabChanged(int position) {
tabChangedCallbacks.get(position).run();
}
#NonNull
#Override
public Fragment createFragment(int position) {
PlaceholderFragment fragment = PlaceholderFragment.newInstance(position + 1);
tabChangedCallbacks.put(position, fragment.getOnTabChangedListener());
return fragment;
}
#Override
public int getItemCount() {
return 2;
}
...
}
The activity changes the most:
public class MainActivity extends AppCompatActivity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
...
final SectionsStateAdapter sectionsStateAdapter = new SectionsStateAdapter(this);
final ViewPager2 viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsStateAdapter);
TabLayout tabs = findViewById(R.id.tabs);
// connect the TabLayout to the ViewPager2
new TabLayoutMediator(tabs, viewPager, new TabLayoutMediator.TabConfigurationStrategy() {
#Override
public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
// set tab text, etc
}
}).attach();
// set the change listener on the ViewPager2
viewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
sectionsStateAdapter.onTabChanged(position);
}
});
...
}
}
Note that the only real change is that the ViewPager2 doesn't need the TabLayout to handle the page change. You could still use TabLayout.addOnTabSelectedListener() if you wanted, but you would have to implement your own TabLayout.OnTabSelecterListener since TabLayout.ViewPagerOnTabSelectedListener doesn't work with ViewPager2.
For example:
tabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
sectionsStateAdapter.onTabChanged(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});

Change the floatingButton Background (ButterKnife) programmatically

I am new to Android Butterknife and want to change the background color of floating Button. I am unable to do this.How can i achieve this.Thanks in advance.Application crashes when i use .
floatingActionButton.setBackgroundTintList(ColorStateList.valueOf(Color
.parseColor("#33691E")));
This works fine if i donot integrate Butterknife.
This is my floating Button
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:id="#+id/fab1"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right"
app:rippleColor="#android:color/white"
android:layout_margin="16dp"
android:src="#drawable/circle"
android:onClick="newForm"
app:layout_anchorGravity="bottom|right|end" />
And in MainActivity
public class MainActivity extends AppCompatActivity implements
SearchView.OnQueryTextListener {
#BindView(R.id.fab1)
FloatingActionButton floatingActionButton;
#BindColor(R.color.colorFolatingButton)
int Floating_Button_Color;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
setSupportActionBar(toolbar);
floatingActionButton.setBackgroundColor(Floating_Button_Color);
}
#OnClick(R.id.fab1)
public void newForm (View view){
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Confirm");
builder.setMessage("Are you sure?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getApplicationContext(),BuilderPage.class);
startActivity(intent);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
Use app:backgroundTint="#color/your_color"
I have found this answer from #tdamian-kozlakejjd. Follow this link this might help you
How to change FAB background color
app:backgroundTint="#color/YOURCOLOR"
xmlns:app="http://schemas.android.com/apk/res-auto"

Android Studio, Capture FrameLayout View, While Camera is StopPreview()

This is my CameraView.java (I got it from http://blog.rhesoft.com/)
public class CameraView extends SurfaceView implements SurfaceHolder.Callback{
private SurfaceHolder mHolder;
private Camera mCamera;
public CameraView(Context context, Camera camera){
super(context);
mCamera = camera;
mCamera.setDisplayOrientation(90);
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_NORMAL);
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try{
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (IOException e) {
Log.d("ERROR", "Camera error on surfaceCreated " + e.getMessage());
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i2, int i3) {
if(mHolder.getSurface() == null)
return;
try{
mCamera.stopPreview();
} catch (Exception e){
}
try{
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (IOException e) {
Log.d("ERROR", "Camera error on surfaceChanged " + e.getMessage());
}
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
mCamera.stopPreview();
mCamera.release();
}}
and this is my MainActivity.java.
public class MainActivity extends AppCompatActivity {
private Camera mCamera = null;
private CameraView mCameraView = null;
private FrameLayout camera_view;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
mCamera = Camera.open();
//you can use open(int) to use different cameras
} catch (Exception e){
Log.d("ERROR", "Failed to get camera: " + e.getMessage());
}
if(mCamera != null) {
mCameraView = new CameraView(this, mCamera);//create a SurfaceView to show camera data
camera_view = (FrameLayout)findViewById(R.id.camera_view);
camera_view.addView(mCameraView);//add the SurfaceView to the layout
}
//btn to close the application
final ImageButton imgClose = (ImageButton)findViewById(R.id.imgClose);
final ImageButton capImg = (ImageButton) findViewById(R.id.imgCapture);
imgClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
imgClose.setVisibility(View.INVISIBLE);
capImg.setVisibility(View.VISIBLE);
mCamera.startPreview();
}
});
capImg.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
mCamera.stopPreview();
imgClose.setVisibility(View.VISIBLE);
capImg.setVisibility(View.INVISIBLE);
}
});
}
#Override
public void onBackPressed(){
System.exit(0);
}}
and this my activity_main.xml.
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<FrameLayout
android:id="#+id/camera_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
</FrameLayout>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imgClose"
android:layout_gravity="right|top"
android:background="#android:drawable/ic_menu_close_clear_cancel"
android:padding="20dp"
android:visibility="invisible" />
<ImageButton
android:layout_width="98dp"
android:layout_height="98dp"
android:id="#+id/imgCapture"
android:layout_gravity="center_horizontal|bottom"
android:background="#android:drawable/ic_menu_camera"
android:padding="20dp"/>
Can I capture this FrameLayout preview as image or do some programing with that preview like delete red color? Can you give me some clue?
So if I understand correctly, you wish to get the image data that is shown when you stop the preview? If you so you can mCamera.takePicture() method. It takes 3 parameters, all of which are useful callbacks. Here is something I recently did to show you.
btn_Capture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mCamera == null)
return;
mCamera.takePicture(null, null, mPicture);
}
});
This is my button click listener which is a floating image button (any button will work just fine). The third parameter is a callback that returns an array of pixels that you can convert into a bitmap.
private Camera.PictureCallback mPicture = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
mCamera.stopPreview();
Bitmap bMap = BitmapFactory.decodeByteArray(data, 0, data.length);
preview.removeView(mPreview);
img_Captured.setImageBitmap(bMap);
}
};
This is the callback which I passed in the takePicture() method. byte[] data is the image that you are trying to get. As you can see I converted it into a bitmap and displayed it to an ImageView after removing the surfaceview (which holds the camera preview). Just a note, the takePicture() method stops the preview automatically so don't stop the preview before taking the photo. You can do it how I did it in the callback. Also, if you want to take another photo, you can start the preview again.
I hope this helps!! Let me know if I left anything out! By the way, it is all documented on the Android Developer site.
http://developer.android.com/training/camera/cameradirect.html#TaskTakePicture

mapview and cameraupdate in api v2

Why the CameraUpdateFactory class is not working in my project?
The app crashes if it executes the following command:
CameraUpdate pino= CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
If i remove that line (and of course the next one), the code successfully starts and shows the map.
I need the mapView and i need to use the new api v2.
I declare the mapView in layout in this way:
<com.google.android.gms.maps.MapView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="#+id/mappa"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_below="#+id/buttonBar"
map:uiZoomControls="false"
/>
then in mainActivity.java i wrote this:
public class MainActivity extends FragmentActivity implements LocationListener, LocationSource {
public static boolean locatingMe=true;
public GoogleMap mappa;
public MapView mapView;
private OnLocationChangedListener onLocationChangedListener;
private LocationManager locationManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapView = (MapView) findViewById(R.id.mappa);
mapView.onCreate(savedInstanceState);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
//You may want to pass a different provider in as the first arg here
//depending on the location accuracy that you desire
//see LocationManager.getBestProvider()
Criteria locationCriteria = new Criteria();
locationCriteria.setAccuracy(Criteria.NO_REQUIREMENT);
locationManager.requestLocationUpdates(locationManager.getBestProvider(locationCriteria, true), 1L, 2F, this);
if (mappa == null) {
mappa=mapView.getMap();
//This is how you register the LocationSource
mappa.setLocationSource(this);
mappa.getUiSettings().setMyLocationButtonEnabled(false);
mappa.setMyLocationEnabled(true);
}
}
#Override
public void onPause()
{
if(locationManager != null)
{
locationManager.removeUpdates(this);
}
mapView.onPause();
super.onPause();
}
#Override
public void onResume()
{
checkGooglePlayServicesAvailability();
checkGps();
mapView.onResume();
super.onResume();
}
#Override
protected void onDestroy() {
mapView.onDestroy();
super.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
public void activate(OnLocationChangedListener listener)
{
onLocationChangedListener = listener;
}
#Override
public void deactivate()
{
onLocationChangedListener = null;
}
#Override
public void onLocationChanged(Location location)
{
if( onLocationChangedListener != null )
{
onLocationChangedListener.onLocationChanged( location );
//Move the camera to the user's location once it's available!
//only if locatingMe is true
if (locatingMe) {
if (mappa!=null){
CameraUpdate pino= CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
mappa.animateCamera(pino);
}
}
}
}
#Override
public void onProviderDisabled(String provider)
{
// TODO Auto-generated method stub
Toast.makeText(this, "provider disabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider)
{
// TODO Auto-generated method stub
Toast.makeText(this, "provider enabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
// TODO Auto-generated method stub
Toast.makeText(this, "status changed", Toast.LENGTH_SHORT).show();
}
The error in the LogCat is the following:
Caused by: java.lang.NullPointerException: CameraUpdateFactory is not initialized.
I solved the problem by adding on the "onCreate" the following lines:
try {
MapsInitializer.initialize(this);
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
the reason is that the CameraUpdateFactory needs to be initilized (even if from documentation it seems that using mapview it shoud be automatically initialized)
I even replaced "public class MainActivity extends FragmentActivity" with "public class MainActivity extends Activity". But i think that this last thing it was not needed..
if i use:
try {
MapsInitializer.initialize(this);
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
The exception give me this error:
Unreachable catch block for GooglePlayServicesNotAvailableException.
This exception is never thrown from the try statement body".
I have use only:
MapsInitializer.initialize(this);
:)

Resources