reopen Google map stops my Application - google-maps

i have tow fragment. by click in first fragment button second fragment that is Google map will open.
first time all thing is correct but if i back and click again program will stop.
map fragment code is as blow:
public class map extends Fragment implements OnMapReadyCallback {
private GoogleMap mMap;
private double lat;
private double att;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.map,container,false);
// GoogleMap map = ((MapFragment) getFragmentManager(.findFragmentById(R.id.map)).getMap();
return view;
}
#Override
public void onStart() {
super.onStart();
if (getArguments() != null) {
lat= getArguments().getDouble("LAT");
att=getArguments().getDouble("ATT");
Toast.makeText(getActivity(),String.valueOf(att),Toast.LENGTH_LONG).show();
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onMapReady(GoogleMap googleMap) {
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(lat, att);
CameraPosition googlePlex = CameraPosition.builder()
.target(new LatLng(lat,att))
.zoom(16).build();
googleMap.addMarker(new MarkerOptions().position(sydney));
googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(googlePlex));
}
}
and main activity is:
public class MainActivity extends AppCompatActivity implements onclicklistener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(findViewById(R.id.firstpage)!=null)
{
if(savedInstanceState!=null)
return;
firstpage startpage=new firstpage();
FragmentManager fm=getFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
ft.add(R.id.firstpage,startpage);
ft.commit();
}
}
#Override
public void onclickbutton(String index) {
try{ map newmap=new map();
Bundle args = new Bundle();
args.putDouble("LAT",32.657892);
args.putDouble("ATT",51.668643);
FragmentManager fm=getFragmentManager();
FragmentTransaction ft=fm.beginTransaction();
newmap.setArguments(args);
ft.addToBackStack(null);
ft.replace(R.id.firstpage,newmap);
ft.commit();}
catch (Exception e){Toast toast = Toast.makeText(this, "error", Toast.LENGTH_SHORT);}
}
#Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0 ){
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
}
first Run is completely OK but if i click again program will stop. please guide me.

it solved.
i added this code:
#Override
public void onDetach() {
Fragment fragment = (getFragmentManager().findFragmentById(R.id.map));
FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
ft.remove(fragment);
ft.commit();
super.onDetach();
}

Related

how to add ( admob ) Interstitial ads to libgdx game and what activity to use?

I followed google guide:
updated build.gradle dependencies
updated AndroidManifest.xml
updated the AndroidLauncher and tried banner ads first
from libgdx wiki https://libgdx.com/wiki/third-party/admob-in-libgdx
#Override public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create the layout
RelativeLayout layout = new RelativeLayout(this);
// Do the stuff that initialize() would do for you
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// Create the libGDX View
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
View gameView = initializeForView(new mygame(), config);
// Create and setup the AdMob view
AdView adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111"); // Put in your secret key here
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
// Add the libGDX view
layout.addView(gameView);
// Add the AdMob view
RelativeLayout.LayoutParams adParams =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
adParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
adParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
layout.addView(adView, adParams);
// Hook it all up
setContentView(layout);
}}
but I cant figure out how to do the same for Interstitial ads
i tried adding adscontroller interface
public interface AdsController {
public void loadInterstitialAd();
public void showInterstitialAd();
}
and updating AndroidLauncher
public class AndroidLauncher extends AndroidApplication implements AdsController {
InterstitialAd mInterstitialAd;
private static final String TAG = "Androidlauncher";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// // Create the layout
RelativeLayout layout = new RelativeLayout(this);
// Do the stuff that initialize() would do for you
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
// Create the libGDX View
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
View gameView = initializeForView(new mygame(this), config);
layout.addView(gameView);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {}
});
AdRequest adRequest = null;
InterstitialAd.load(this,"ca-app-pub-3940256099942544/1033173712", adRequest,
new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
mInterstitialAd = interstitialAd;
Log.i(TAG, "onAdLoaded");
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
Log.d(TAG, loadAdError.toString());
mInterstitialAd = null;
}
});
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback(){
#Override
public void onAdClicked() {
// Called when a click is recorded for an ad.
Log.d(TAG, "Ad was clicked.");
}
#Override
public void onAdDismissedFullScreenContent() {
// Called when ad is dismissed.
// Set the ad reference to null so you don't show the ad a second time.
Log.d(TAG, "Ad dismissed fullscreen content.");
mInterstitialAd = null;
}
#Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when ad fails to show.
Log.e(TAG, "Ad failed to show fullscreen content.");
mInterstitialAd = null;
}
#Override
public void onAdImpression() {
// Called when an impression is recorded for an ad.
Log.d(TAG, "Ad recorded an impression.");
}
#Override
public void onAdShowedFullScreenContent() {
// Called when ad is shown.
Log.d(TAG, "Ad showed fullscreen content.");
}
});
loadInterstitialAd();
}
#Override
public void loadInterstitialAd() {
AdRequest adRequest = new AdRequest.Builder().build();
}
#Override
public void showInterstitialAd() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if(mInterstitialAd!=null) {
mInterstitialAd.show();
}
else loadInterstitialAd();
}
});
}
}
InterstitialAd.show(MyActivity.this); require activity but libgdx doesn't work like that(I think?)
every code I found is no longer useful because google updated Admob
AndroidApplication extends Activity, so for interstitials you can just pass in a reference to the application, eg InterstitialAd.show(this);
I did something very similar to get interstitials working in my project. I use Ironsource but the process should be very similar. First, I defined an AdManager interface:
public interface AdManager {
/**
* Show a rewarded video ad
*/
void showRewardedVideo();
/**
* Called on app pause
*/
void onPause();
/**
* Called on app resume
*/
void onResume();
/**
* Attempts to show an interstitial ad
*
* #param onSuccess
* #param onFailed
*/
void showInterstitial(Listener onSuccess, Listener onFailed);
/**
* Called every frame, for any extra work that might need to be done
*
* #param deltaTime
*/
void update(float deltaTime);
}
Following that, you can implement your platform's ad provider:
public class AndroidAdManager implements AdManager, RewardedVideoListener, InterstitialListener, OfferwallListener {
private OnlineRPG game;
private boolean videoAvailable;
private Listener onInterstitialSuccess;
private Listener onInterstitialFailed;
private float timeSinceAd;
public AndroidAdManager(Activity activity, Gamegame) {
this.game = game;
this.activity = activity;
IronSource.setRewardedVideoListener(this);
IronSource.setInterstitialListener(this);
IronSource.setOfferwallListener(this);
IronSource.init(activity, "whatever");
IronSource.shouldTrackNetworkState(activity, true);
IronSource.loadInterstitial();
IntegrationHelper.validateIntegration(activity);
}
#Override
public void showRewardedVideo() {
if (IronSource.isRewardedVideoPlacementCapped(REWARDED_VIDEO_PLACEMENT_NAME)) {
Log.i(TAG, "Rewarded video placement is capped");
return;
}
IronSource.showRewardedVideo(REWARDED_VIDEO_PLACEMENT_NAME);
}
#Override
public void onPause() {
IronSource.onPause(activity);
}
#Override
public void onResume() {
IronSource.onResume(activity);
}
#Override
public void showInterstitial(Listener onSuccess, Listener onFailed) {
if (timeSinceAd < INTERSTITIAL_MIN_PERIOD || true) {
onFailed.invoke();
return;
}
this.onInterstitialSuccess = onSuccess;
this.onInterstitialFailed = onFailed;
IronSource.showInterstitial(INTERSTITIAL_PLACEMENT_NAME);
}
#Override
public void update(float deltaTime) {
timeSinceAd += deltaTime;
}
#Override
public void onRewardedVideoAdOpened() {
}
#Override
public void onRewardedVideoAdClosed() {
}
#Override
public void onRewardedVideoAvailabilityChanged(boolean b) {
Log.i(TAG, "onRewardedVideoAvailabilityChanged: " + b);
videoAvailable = b;
}
#Override
public void onRewardedVideoAdStarted() {
}
#Override
public void onRewardedVideoAdEnded() {
}
#Override
public void onRewardedVideoAdRewarded(Placement placement) {
}
#Override
public void onRewardedVideoAdShowFailed(IronSourceError ironSourceError) {
}
#Override
public void onRewardedVideoAdClicked(Placement placement) {
}
#Override
public void onInterstitialAdReady() {
}
#Override
public void onInterstitialAdLoadFailed(IronSourceError ironSourceError) {
if (onInterstitialFailed != null) {
Gdx.app.postRunnable(new Runnable() {
#Override
public void run() {
onInterstitialFailed.invoke();
onInterstitialFailed = null;
}
});
}
}
#Override
public void onInterstitialAdOpened() {
Log.i(TAG, "Interstitial Ad Opened");
}
#Override
public void onInterstitialAdClosed() {
Log.i(TAG, "Interstitial Ad Closed");
if (onInterstitialSuccess != null) {
Gdx.app.postRunnable(new Runnable() {
#Override
public void run() {
timeSinceAd = 0;
onInterstitialSuccess.invoke();
onInterstitialSuccess = null;
}
});
}
IronSource.loadInterstitial();
}
#Override
public void onInterstitialAdShowSucceeded() {
}
#Override
public void onInterstitialAdShowFailed(IronSourceError ironSourceError) {
Log.e(TAG, ironSourceError.getErrorMessage());
if (onInterstitialFailed != null) {
Gdx.app.postRunnable(new Runnable() {
#Override
public void run() {
onInterstitialFailed.invoke();
onInterstitialFailed = null;
}
});
}
}
#Override
public void onInterstitialAdClicked() {
}
#Override
public void onOfferwallAvailable(boolean b) {
}
#Override
public void onOfferwallOpened() {
}
#Override
public void onOfferwallShowFailed(IronSourceError ironSourceError) {
}
#Override
public boolean onOfferwallAdCredited(int i, int i1, boolean b) {
return false;
}
#Override
public void onGetOfferwallCreditsFailed(IronSourceError ironSourceError) {
}
#Override
public void onOfferwallClosed() {
}
}
Lastly, in your AndroidLauncher you can create your AndroidAdManager, giving it a reference to your game/activity.
public class AndroidLauncher extends AndroidApplication {
private Game game;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
game = new Game();
game.setAdManager(new AndroidAdManager(this, game));
game.setPermissionManager(new AndroidPermissionManager(this, game));
initialize(game, config);
}
#Override
protected void onPause() {
super.onPause();
game.getAds().onPause();
}
#Override
protected void onResume() {
super.onResume();
game.getAds().onResume();
}
}
I hope this helps in your project!

Getting data in recyclerView

i am getting messages from the database into a recycler view but i want to refresh the recycler view every second for to adding different for to getting new messages in recycler view
But i haver an error of getting data please see it https://www.filemail.com/d/izhittgyibvcjxx
my code is
boolean refresh;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message_user);
refresh = true;
content();
}
public void content()
{
getdata();
if (refresh)
{
refresh(100);
}
}
private void refresh(int milliseconds)
{
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
#Override
public void run() {
content();
}
};
handler.postDelayed(runnable,milliseconds);
}
private void getdata()
{
String Choice = "Get Messages";
Call<List<responsemodel>> call = SplashScreen.apiInterface.getfullprofiledata(Choice,Message_To,Message_From);
call.enqueue(new Callback<List<responsemodel>>() {
#Override
public void onResponse(Call<List<responsemodel>> call, Response<List<responsemodel>> response) {
List<responsemodel> data = response.body();
Message_user_Adapter adapter = new Message_user_Adapter(data,Message_To);
messages_Message_user_RecyclerView.setAdapter(adapter);
messages_Message_user_RecyclerView.smoothScrollToPosition(messages_Message_user_RecyclerView.getAdapter().getItemCount());
}
#Override
public void onFailure(Call<List<responsemodel>> call, Throwable t) {
}
});
}

notifyDataSetChanged on RecyclerView

I have a recyclerView and customAdaprer. I pass an list of an object (earthquakeList)to recycleradapter and then i do setAdapter:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
earthquakeList = new ArrayList<>();
adapter = new RecyclerViewAdapter(earthquakeList);
recyclerView.setAdapter(adapter);
}
I create AsyncTask on onResume method:
#Override
protected void onResume() {
super.onResume();
// Kick off an {#link AsyncTask} to perform the network request
new EarthQuakeAsyncTask().execute();
}
in AsyncTask my class i get a new List from my object that i get from internet and when I replaced this new list with older list and call notifyDataSetChanged, recyclerView still nothing show??
I debug my app and I get object from net.
I do in this way on list view but recylerview seems efferent.
I replace old list with the new list one like blow:
private class EarthQuakeAsyncTask extends AsyncTask<Void, Void, List<Earthquake>> {
#Override
protected List<Earthquake> doInBackground(Void... urls) {
// Create URL object
URL url = HttpRequest.createUrl(USGS_REQUEST_URL);
// perform HTTP request to the URL and receive a JSON response back
String jsonResponse = "";
try {
jsonResponse = HttpRequest.makeHttpRequest(url);
} catch (IOException e) {
e.printStackTrace();
}
List<Earthquake> earthquakes = HttpRequest.extractFeaturesFromJson(jsonResponse);
return earthquakes;
}
#Override
protected void onPostExecute(List<Earthquake> earthquakeList) {
super.onPostExecute(earthquakeList);
MainActivity.this.earthquakeList.clear();
MainActivity.this.earthquakeList.addAll(earthquakeList);
adapter.notifyDataSetChanged();
}
what is exactly my wrong?
************************ EDIT ********************
this is Adapter :
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyHolder> {
List<Earthquake> earthquakes;
public RecyclerViewAdapter(List<Earthquake> earthquakes) {
this.earthquakes = earthquakes;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(
R.layout.earthquak_list_item, parent, false);
MyHolder myHolder = new MyHolder(view);
return myHolder;
}
#Override
public void onBindViewHolder(MyHolder holder, int position) {
Earthquake earthquake = earthquakes.get(position);
holder.magnitude.setText(earthquake.getmMagnitude());
holder.location.setText(earthquake.getmLocation());
holder.time.setText(earthquake.getmDate());
}
#Override
public int getItemCount() {
return (null != earthquakes ? earthquakes.size() : 0);
}
public void setItems(List<Earthquake> earthquakeList) {
this.earthquakes = earthquakeList;
}
public class MyHolder extends RecyclerView.ViewHolder {
#BindView(R.id.magnitude)
TextView magnitude;
#BindView(R.id.location)
TextView location;
#BindView(R.id.date)
TextView time;
public MyHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
Ops ,I forgot put LayoutManager for recyclerView .
this is right code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
earthquakeList = new ArrayList<>();
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
adapter = new RecyclerViewAdapter(earthquakeList);
recyclerView.setAdapter(adapter);
}

Web pages in a webview how to obtain position

public class MainActivity extends Activity {
private WebView webView;`
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView=(WebView) findViewById(R.id.web_view);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDatabaseEnabled(true);
webSettings.setAppCacheEnabled(true);
String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
webSettings.setAppCachePath(appCachePath);
webSettings.setGeolocationEnabled(true);
webSettings.setDomStorageEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
#Override
public void onReceivedIcon(WebView view, Bitmap icon) {
super.onReceivedIcon(view, icon);
}
#Override
public void onGeolocationPermissionsHidePrompt() {
super.onGeolocationPermissionsHidePrompt();
}
});
/*
* setWebViewClient()
* shouldOverrideUrlLoading
* */
webView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
});
webView.loadUrl("http://uri.amap.com/line");
}
I write a map page in webview. This is a HTML page.
But can't locate.Unable to display. I want the webview positioning can be obtained.In the system browser can show the location.This is I write my own code, I don't know how to do

Android Preferences Screen inside Action Bar Tab

I am developing some app with have ActionBar with three tabs, one of with is a settings tab.
PreferencesFragment loads my preferences xml file, so how can i add PreferenceFragment to ActionBar Tab ??
As at this picteur:
This is a main Activity that adds three tabs, I has added two simple fragments tab successfuly but a problem began with a RreferenceFragment
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ActionBar actionBar = this.getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab settings = actionBar.newTab();
settings.setText("Settings");
settings.setTabListener(new SettingsFragment());
actionBar.addTab(settings);
Tab control = actionBar.newTab();
control.setText("Controller");
control.setTabListener(new ControlFragment());
actionBar.addTab(control);
Tab information = actionBar.newTab();
information.setText("information");
information.setTabListener(new InformationFragment());
actionBar.addTab(information);
}
For example, this is a ControlFragment class ( second tab )
public class ControlFragment extends Fragment implements ActionBar.TabListener {
private Fragment fragment;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActivity().setContentView(R.layout.control_fragment);
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction frgTransaction) {
//TODO
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction frgTransaction) {
fragment = new ControlFragment();
frgTransaction.add(android.R.id.content, fragment);
frgTransaction.attach(fragment);
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction frgTransaction) {
frgTransaction.remove(fragment);
}
}
And this is a SettingsFragment class with do the main problem
public class SettingsFragment extends PreferenceFragment implements ActionBar.TabListener {
private Activity act;
private Context context;
private Fragment fragment;
public SettingsFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preference_settings);
}
#Override
public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
fragment = new SettingsFragment();
arg1.add(android.R.id.content, fragment);
arg1.attach(fragment);
}
#Override
public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
}
}
Application crashes because its a problem to transact PreferenceFragment.
How I can inplement it ??? I know about TabHost but I use Action Bar.
You'd have to use the v13 support library to achieve this. Hope I helped.