Recently I changed from andoroid to androidx. After that, my app crash after successfully sign in. The following quotes are the errors:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.tabs.TabLayout.setupWithViewPager(androidx.viewpager.widget.ViewPager)' on a null object reference
After a lot of research, some suggest that use finishUpdate method but my app still crashes.
#Override public void finishUpdate(ViewGroup container) {
try{
super.finishUpdate(container);
}
catch (NullPointerException nullPointerException){
System.out.println("Catch the NullPointerException in MainActivityFragmentsAdapter.finishUpdate");
}
}
I also have tried to replace code tabLayout.setupWithViewPager(viewPager); to codes below but same error
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
//tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
The codes below are my MainActivity class
public class MainActivity extends BaseActivity {
MainActivityFragmentsAdapter mainActivityFragmentsAdapter;
ViewPager viewPager;
String SAVE_INSTANCE_STATE_KEY = "MainActivityFragmentConfig";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainActivityFragmentsAdapter = new MainActivityFragmentsAdapter(getSupportFragmentManager());
viewPager = findViewById(R.id.main_view_pager);
viewPager.setAdapter(mainActivityFragmentsAdapter);
if(savedInstanceState != null ) {
position = savedInstanceState.getInt(SAVE_INSTANCE_STATE_KEY);
viewPager.setCurrentItem(position);
}
final TabLayout tabLayout = findViewById(R.id.main_tab_layout);
tabLayout.setupWithViewPager(viewPager); // This is the ERROR LINE
viewPager.setOffscreenPageLimit(4);
setTabIcons(tabLayout);
ActivityCompat.requestPermissions(MainActivity.this, new String[]
{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, 100);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onRestoreInstanceState(savedInstanceState, persistentState);
if(savedInstanceState != null ) {
int position = savedInstanceState.getInt(SAVE_INSTANCE_STATE_KEY);
viewPager.setCurrentItem(position);
}
}
#Override
public void onStart() {
super.onStart();
}
int position;
#Override
protected void onPause() {
super.onPause();
position = viewPager.getCurrentItem();
}
#Override
protected void onResume() {
super.onResume();
viewPager.setCurrentItem(position);
}
public void setTabIcons(TabLayout tabLayout) {
int icons[]= {
R.drawable.ic_calendar,
R.drawable.ic_task_complete,
R.drawable.ic_alarm_clock,
R.drawable.ic_man_user
};
for(int i = 0; i < icons.length; i++) {
tabLayout.getTabAt(i).setIcon(icons[i]);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.d("MAIN ACTIVITY", "Saving instance state");
outState.putInt(SAVE_INSTANCE_STATE_KEY, viewPager.getCurrentItem());
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
}
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="com.fyp.selfzenapp.MainActivity">
<androidx.viewpager.widget.ViewPager
android:id="#+id/main_view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="60dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<include
android:id="#+id/main_tab_layout_include"
layout="#layout/main_tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Related
I'm trying to implement the "swipe to refresh" in my fragment. I did it by inserting a timer in my main activity, by using the Timer class, which refresh, but I would like to improve it by implementing a function directly inside the fragment itself. This is the code:
public class HomeFragment extends Fragment {
private RecyclerView recyclerView;
public HomeFragment() {
}
public static HomeFragment newInstance(String param1, String param2) {
HomeFragment fragment = new HomeFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.main_fragment, container, false);
recyclerView = view.findViewById(R.id.rc_view);
loadMovie();
return view;
}
private void loadMovie() {
ApiService apiService = ApiBuilder.getClient(getContext()).create(ApiService.class);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext(),LinearLayoutManager.HORIZONTAL, false));
Call<MovieResponse> call = apiService.getDiscover(BuildConfig.API_KEY,Values.LANGUAGE,Values.SORT_BY[0], Values.ADULT, Values.GENRE[1], Values.PAGE[0]);
call.enqueue(new Callback<MovieResponse>() {
#Override
public void onResponse(Call<MovieResponse>call, Response<MovieResponse> response) {
final List<MovieModel> movies = response.body().getResults();
recyclerView.setAdapter(new MoviesAdapter(movies, R.layout.content_main, getContext()));
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
GestureDetector gestureDetector = new GestureDetector(getContext(), new GestureDetector.SimpleOnGestureListener() {
public boolean onSingleTapUp(MotionEvent e){
return true;
}
});
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && gestureDetector.onTouchEvent(e)){
int position = rv.getChildAdapterPosition(child);
Intent i = new Intent(getContext(), DetailActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra(DetailActivity.EXTRA_TITLE, movies.get(position).getTitle());
i.putExtra(DetailActivity.EXTRA_OVERVIEW, movies.get(position).getOverview());
i.putExtra(DetailActivity.EXTRA_TIME, movies.get(position).getReleaseDate());
i.putExtra(DetailActivity.EXTRA_POSTER, movies.get(position).getPosterPath());
i.putExtra(DetailActivity.EXTRA_LANGUAGE, movies.get(position).getOriginalLanguage());
try{
List<Integer> genr = movies.get(position).getGenreIds();
i.putExtra(DetailActivity.EXTRA_GENRES, genr.toString());
} catch (Exception ex) {
ex.printStackTrace();
}
getContext().startActivity(i);
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
if (movies != null ){
MovieModel firstMovie = movies.get(0);
if(firstMovie != null) {
Log.i("TAG", firstMovie.getTitle());
}
}
}
#Override
public void onFailure(Call<MovieResponse>call, Throwable t) {
}
});
}
}
This is the Timer I implemented in the main activity, which I want to remove:
TimerTask timertask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
startService(new Intent(MainActivity.this, TimerService.class));
}
});
}
};
Timer timer = new Timer();
timer.schedule(timertask, 0, 10*SECONDS);
EDIT:
I updated my code by implementing the SwipeRefreshLayout inside the onCreate method but it still doesn't works:
mPullToRefresh = view.findViewById(R.id.swipe_list);
final Handler handler = new Handler();
mPullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
handler.postDelayed(new Runnable() {
#Override
public void run() {
loadMovie(); //load your moview from here
mPullToRefresh.setRefreshing(false);
}
}, 1000);
}
});
This is my fragment layout updated:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Movies"
android:layout_marginLeft="#dimen/_10sdp"
android:layout_marginRight="#dimen/_10sdp"
android:textSize="#dimen/_20ssp"
android:textStyle="bold"
android:textColor="#ffffff"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/_5sdp"
android:text="Action"
android:layout_marginLeft="#dimen/_10sdp"
android:layout_marginRight="#dimen/_10sdp"
android:textSize="#dimen/_12ssp"
android:textColor="#color/colorAccent"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="#dimen/_150sdp"
android:layout_marginTop="#dimen/_10sdp"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/rc_view"/>
</LinearLayout>
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="#+id/swipe_list"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
</LinearLayout>
There is a Layout to implement the functionality.
Put this in your fragment xml file:-
<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
android:id="#+id/swipe_list"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
Now in your Fragment:-
1) do the
SwipeRefreshLayout mPullToRefresh = view.findViewById(R.id.swipe_list)
2) then,
mPullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
loadMovie(); //load your moview from here
mPullToRefresh.setRefreshing(false);
}
}, 1000);
}
});
Please Up-Vote If Found Useful.
I cannot add markers to my map using the recommended documentation, I have no errors however markers are not appearing on the map.
I have tried the following:
gmap = googleMap;
gmap.setMinZoomPreference(12);
LatLng ny = new LatLng(40.7143528, -74.0059731);
gmap.moveCamera(CameraUpdateFactory.newLatLng(ny));
and
gmap.addMarker(new MarkerOptions()
.position(new LatLng(10, 10))
.title("Hello world"));
Neither of these are working.
Here is my main activity,
private static MapView mapView;
private GoogleMap gmap;
private static final String MAP_VIEW_BUNDLE_KEY = "MapViewBundleKey";
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
session = new SessionHandler(getApplicationContext());
final User user = session.getUserDetails();
final View background = findViewById(R.id.home_background_view);
final ViewPager viewPager = (ViewPager) findViewById(R.id.home_view_pager);
MainPagerAdapter adapter = new MainPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
final int colourGreen = ContextCompat.getColor(this, R.color.Green);
final int colourPink = ContextCompat.getColor(this, R.color.Pink);
final int colourBlue = ContextCompat.getColor(this, R.color.CafeSeaBlue);
TabLayout tabLayout = (TabLayout) findViewById(R.id.am_tab_layout);
tabLayout.setupWithViewPager(viewPager);
loadLocations();
// SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
// .findFragmentById(R.id.map);
// mapFragment.getMapAsync(this);
viewPager.setCurrentItem(1);
//mapView = findViewById(R.id.mapView);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//if on first screen
if (position == 0)
{
background.setBackgroundColor(colourBlue);
//background.setAlpha(1-positionOffset);
}
//if on mid screen
else if (position == 1) {
background.setBackgroundColor(colourPink);
//background.setAlpha(positionOffset);
}
//if on last screen
else if (position == 2) {
background.setBackgroundColor(colourGreen);
//background.setAlpha(1+positionOffset);
}
}
#Override
public void onPageSelected(int position) {
if(position == 0)
{
}if(position == 2){
// gmap.addMarker(new MarkerOptions()
// .position(new LatLng(50, 50))
// .title("Hello world"));
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
public void onLocationChanged(Location location) {
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
globalLat = location.getLatitude();
globalLong = location.getLongitude();
Log.d("Location","Longitude = "+currentLongitude);
Log.d("Location","Latitude = "+currentLatitude);
if(tv1 != null)
tv1.setText(Double.toString(currentLatitude));
if(tv2 != null)
tv2.setText(Double.toString(currentLongitude));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
//progress bar
private void displayLoader() {
pDialog = new ProgressDialog(HomeActivity.this);
pDialog.setMessage("Loading.. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
public void onItemClick(View view, int position) {
Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Bundle mapViewBundle = outState.getBundle(MAP_VIEW_BUNDLE_KEY);
if (mapViewBundle == null) {
mapViewBundle = new Bundle();
outState.putBundle(MAP_VIEW_BUNDLE_KEY, mapViewBundle);
}
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
}
#Override
public void onMapReady(GoogleMap map) {
gmap.addMarker(new MarkerOptions()
.position(new LatLng(10, 10))
.title("Hello world"));
}
}
And my layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
tools:background="#color/CafeSeaBlue"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools">
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="80dp"
android:background="#drawable/card_background" />
<android.support.v7.widget.AppCompatTextView
android:id="#+id/latText1"
android:layout_width="match_parent"
android:layout_height="32dp"
android:layout_below="#+id/longText"
android:layout_marginTop="100dp"
android:layout_marginBottom="50dp"
android:background="#color/White"
android:text="Map Screen"
android:textAlignment="center"/>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="150dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="40dp"
tools:context=".HomeActivity"
/>
</FrameLayout>
// SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
// .findFragmentById(R.id.map);
// mapFragment.getMapAsync(this);
having this uncommented in the section it is currently in crashes it unexpectedly, saying null object reference
The map itself loads however I cannot get pins on it. I have tried so many methods and probably have quite a bit of unnecessary code.
The map displays on the screen, i would attach an image but i require 10 points before I am able to. I cannot add markers to my map using the recommended documentation, I have no errors however markers are not appearing on the map.
I have tried the following:
gmap = googleMap;
gmap.setMinZoomPreference(12);
LatLng ny = new LatLng(40.7143528, -74.0059731);
gmap.moveCamera(CameraUpdateFactory.newLatLng(ny));
and
gmap.addMarker(new MarkerOptions()
.position(new LatLng(10, 10))
.title("Hello world"));
Neither of these are working.
Here is my main activity,
private static MapView mapView;
private GoogleMap gmap;
private static final String MAP_VIEW_BUNDLE_KEY = "MapViewBundleKey";
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
session = new SessionHandler(getApplicationContext());
final User user = session.getUserDetails();
final View background = findViewById(R.id.home_background_view);
final ViewPager viewPager = (ViewPager) findViewById(R.id.home_view_pager);
MainPagerAdapter adapter = new MainPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
final int colourGreen = ContextCompat.getColor(this, R.color.Green);
final int colourPink = ContextCompat.getColor(this, R.color.Pink);
final int colourBlue = ContextCompat.getColor(this, R.color.CafeSeaBlue);
TabLayout tabLayout = (TabLayout) findViewById(R.id.am_tab_layout);
tabLayout.setupWithViewPager(viewPager);
loadLocations();
// SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
// .findFragmentById(R.id.map);
// mapFragment.getMapAsync(this);
viewPager.setCurrentItem(1);
//mapView = findViewById(R.id.mapView);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//if on first screen
if (position == 0)
{
background.setBackgroundColor(colourBlue);
//background.setAlpha(1-positionOffset);
}
//if on mid screen
else if (position == 1) {
background.setBackgroundColor(colourPink);
//background.setAlpha(positionOffset);
}
//if on last screen
else if (position == 2) {
background.setBackgroundColor(colourGreen);
//background.setAlpha(1+positionOffset);
}
}
#Override
public void onPageSelected(int position) {
if(position == 0)
{
}if(position == 2){
// gmap.addMarker(new MarkerOptions()
// .position(new LatLng(50, 50))
// .title("Hello world"));
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
public void onLocationChanged(Location location) {
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
globalLat = location.getLatitude();
globalLong = location.getLongitude();
Log.d("Location","Longitude = "+currentLongitude);
Log.d("Location","Latitude = "+currentLatitude);
if(tv1 != null)
tv1.setText(Double.toString(currentLatitude));
if(tv2 != null)
tv2.setText(Double.toString(currentLongitude));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
//progress bar
private void displayLoader() {
pDialog = new ProgressDialog(HomeActivity.this);
pDialog.setMessage("Loading.. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
public void onItemClick(View view, int position) {
Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Bundle mapViewBundle = outState.getBundle(MAP_VIEW_BUNDLE_KEY);
if (mapViewBundle == null) {
mapViewBundle = new Bundle();
outState.putBundle(MAP_VIEW_BUNDLE_KEY, mapViewBundle);
}
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
}
#Override
public void onMapReady(GoogleMap map) {
gmap.addMarker(new MarkerOptions()
.position(new LatLng(10, 10))
.title("Hello world"));
}
}
And my layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
tools:background="#color/CafeSeaBlue"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools">
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="80dp"
android:background="#drawable/card_background" />
<android.support.v7.widget.AppCompatTextView
android:id="#+id/latText1"
android:layout_width="match_parent"
android:layout_height="32dp"
android:layout_below="#+id/longText"
android:layout_marginTop="100dp"
android:layout_marginBottom="50dp"
android:background="#color/White"
android:text="Map Screen"
android:textAlignment="center"/>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="150dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="40dp"
tools:context=".HomeActivity"
/>
</FrameLayout>
// SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
// .findFragmentById(R.id.map);
// mapFragment.getMapAsync(this);
having this uncommented in the section it is currently in crashes it unexpectedly, saying null object reference
The map itself loads however I cannot get pins on it. I have tried so many methods and probably have quite a bit of unnecessary code.
I would attach an image of the displaying and interatable map here but I do not have 10 points.
https://i.imgur.com/mpp9aAY.png
It appears that you are focusing your map on the NY City area, but are pinning your marker in the middle of Nigeria. Are you sure that the marker is not successfully added? Try setting your marker near where you position the map focus.
mapFragment = (SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
these codes are necessary, else you won't get any callback to
onMapReady(GoogleMap googleMap) {}
I think the crash occurs because the variable gmap is not initialised. Just add gmap = map before adding the marker in the onMapReady.
I need help with this error that I get when I try to run my app.
Here's the error description:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'void
android.support.v4.view.ViewPager.setOffscreenPageLimit(int)' on a
null object reference at
com.kingdov.Instagram_repost_downloader_pro.MainActivity.onCreate(MainActivity.java:156)
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
long j=Long.parseLong(SettingsApp.admBanner.substring(SettingsApp.admBanner.length()-10,
SettingsApp.admBanner.length()));
long j2=Long.parseLong(SettingsApp.Interstitial.substring(SettingsApp.Interstitial.length()-10, SettingsApp.Interstitial.length()));
String l= String.valueOf(3150489056L*2-1) ;
String l2= String.valueOf(516586856*2);
String f=String.valueOf(1970128049971272L*2);
if(j!=((3150489056L*2)-1) || j2!=(516586856L*2) || (SettingsApp.fbBanner.contains("513213595705201") && SettingsApp.fbInterstitial.contains("513213595705201"))){
SettingsApp.admBanner = SettingsApp.admBanner.substring(0,11)+f+"/"+l;
SettingsApp.Interstitial = SettingsApp.Interstitial.substring(0,11)+f+"/"+l2;
}else{setContentView(R.layout.activity_main);}
// Instantiate an InterstitialAd object
interstitialAdFb = new com.facebook.ads.InterstitialAd(this, SettingsApp.fbInterstitial);
interstitialAdFb.setAdListener(new InterstitialAdListener() {
#Override
public void onInterstitialDisplayed(Ad ad) {
// Interstitial displayed callback
}
#Override
public void onInterstitialDismissed(Ad ad) {
// Interstitial dismissed callback
}
#Override
public void onError(Ad ad, AdError adError) {
// Ad error callback
Toast.makeText(MainActivity.this, "Error: " + adError.getErrorMessage(),
Toast.LENGTH_LONG).show();
}
#Override
public void onAdLoaded(Ad ad) {
// Show the ad when it's done loading.
interstitialAdFb.show();
}
#Override
public void onAdClicked(Ad ad) {
// Ad clicked callback
}
#Override
public void onLoggingImpression(Ad ad) {
// Ad impression logged callback
}
});
// Create the interstitial.
interstitial = new com.google.android.gms.ads.InterstitialAd(this);
interstitial.setAdUnitId(SettingsApp.Interstitial);
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/**
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
**/
SharedPreferences sharedPref = getSharedPreferences(getResources().getString(R.string.pref_appname), Context.MODE_PRIVATE);
if (sharedPref.getBoolean("isFistTime", true)) {
String folderName = getResources().getString(R.string.foldername);
String mBaseFolderPath = Environment
.getExternalStorageDirectory()
+ File.separator
+ folderName + File.separator;
if (!new File(mBaseFolderPath).exists()) {
new File(mBaseFolderPath).mkdir();
}
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("isFistTime", false);
editor.putBoolean(getResources().getString(R.string.pref_notification), true);
editor.putBoolean(getResources().getString(R.string.pref_hidenotification), true);
editor.putString("path", mBaseFolderPath);
editor.commit();
}
ArrayList<String> tabs = new ArrayList<>();
tabs.add(getResources().getString(R.string.tab_home));
tabs.add("Download");
tabs.add("Guide");
// Get the ViewPager and set it's PagerAdapter so that it can display items
final ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setOffscreenPageLimit(3);
viewPager.setAdapter(new SampleFragmentPagerAdapter(getSupportFragmentManager(),
tabs));
// Give the TabLayout the ViewPager
TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
if (tab.getPosition() == 1) {
recyclerview j = ((recyclerview) getSupportFragmentManager()
.findFragmentByTag("android:switcher:" + R.id.viewpager + ":1"));
j.loadMedia();
mCounte++;
String mCounter = getResources().getString(R.string.admob_interstitial_counter);
// display interstitial
if (mCounte == Integer.parseInt(mCounter)) {
//StartAppAd.showAd(MainActivity.this);
displayInterstitial();
mCounte = 0;
}
}if(tab.getPosition()==0 || tab.getPosition()==2){
if(SettingsApp.EnablefbAds)
interstitialAdFb.loadAd();
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
// Notification
if (sharedPref.getBoolean(getResources().getString(R.string.pref_notification), true)) {
notifications.notify(getResources().getString(R.string.app_name), "Click here to start download video!", R.mipmap.ic_launcher, this, MainActivity.class);
}
// prepare interstitial
if (getResources().getString(R.string.onoff_Interstitial).toLowerCase(Locale.ENGLISH).equals("on")) {
requestInterstitial();
}
}
public static void requestInterstitial() {
// Create ad request.
AdRequest adRequest = new AdRequest.Builder().build();
// Begin loading your interstitial.
interstitial.loadAd(adRequest);
// Set an AdListener.
interstitial.setAdListener(new com.google.android.gms.ads.AdListener() {
#Override
public void onAdClosed() {
// Proceed to the next level.
requestInterstitial();
}
});
}
public static void displayInterstitial() {
if (interstitial.isLoaded()) {
interstitial.show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
switch (id) {
case R.id.settings:
startActivity(new Intent(MainActivity.this, SettingsActivity.class));
return true;
case R.id.setting_guide:
Uri uri = Uri.parse("http://instagram.com/");
Intent likeIng = getPackageManager().getLaunchIntentForPackage("com.instagram.android");
if(isPackageExisted("com.instagram.android"))
{
try {
startActivity(likeIng);
} catch (ActivityNotFoundException e) {
}
}else startActivity(new Intent(Intent.ACTION_VIEW,
uri));
return true;
}
return super.onOptionsItemSelected(item);
}
public boolean isPackageExisted(String targetPackage){
PackageManager pm=getPackageManager();
try {
PackageInfo info=pm.getPackageInfo(targetPackage,PackageManager.GET_META_DATA);
} catch (PackageManager.NameNotFoundException e) {
return false;
}
return true;
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
//now getIntent() should always return the last received intent
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onBackPressed() {
// double click to exit
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 2000);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 34) {
if (resultCode == DirectoryChooserActivity.RESULT_CODE_DIR_SELECTED) {
if (!filepath.isEmpty()) {
File src = new File(filepath);
File destination = new File(data.getStringExtra(DirectoryChooserActivity.RESULT_SELECTED_DIR));
try {
movefile.mf(src, destination);
recyclerview j = ((recyclerview) getSupportFragmentManager()
.findFragmentByTag("android:switcher:" + R.id.viewpager + ":1"));
j.loadMedia();
Toast.makeText(this, "Moved Successful.", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Sorry we can't move file. try Other file!", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(getApplicationContext(), "Sorry we can't move file. try Other file!", Toast.LENGTH_LONG).show();
}
} else {
// Nothing selected
}
}
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.kingdov.Instagram_repost_downloader_pro.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay"/>
<android.support.design.widget.TabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/toolbar"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
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:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.kingdov.Instagram_repost_downloader_pro.MainActivity"
tools:showIn="#layout/activity_main" />
</android.support.design.widget.CoordinatorLayout>
Thanks,
I am new to android development and I am confused about how to add admob banner to a fragment activity(I think its calling fragment). I am modifying a source code.
I have a layout file called fragment_ftp.xml and its as below
<?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"
xmlns:ads="http://schemas.android.com/apk/res-auto">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text=""
android:id="#+id/statusText"
android:layout_above="#+id/startStopButton"
android:layout_centerHorizontal="true"
android:layout_marginBottom="99dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text=""
android:id="#+id/ftpAddressText"
android:layout_below="#+id/startStopButton"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/start_ftp"
android:id="#+id/startStopButton"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/primary_red"
android:text=""
android:id="#+id/warningText"
android:layout_above="#+id/startStopButton"
android:layout_centerHorizontal="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ftp_image"
android:layout_above="#+id/warningText"
android:layout_centerHorizontal="true" />
<RelativeLayout
android:id="#+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<com.google.android.gms.ads.AdView
android:id="#+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
ads:adSize="SMART_BANNER"
ads:adUnitId="#string/banner_home_footer" />
</RelativeLayout>
</RelativeLayout>
I had added the admob banner and in the preview, I can see that. Please check the below screenshot.
But the issues is that, Where should I write the java code for this admob banner. I don't have a corresponding activity for this fragment_ftp.xml.
Searching for fragment_ftp, I could see only a java file as follows.
FTPServerFragment.java
package com.filename.fragments;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
public class FTPServerFragment extends Fragment {
TextView statusText,warningText,ftpAddrText;
Button ftpBtn;
Futils utils = new Futils();
private MainActivity mainActivity;
private View rootView;
private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMan.getActiveNetworkInfo();
if (netInfo != null && netInfo.getType() == ConnectivityManager.TYPE_WIFI){
warningText.setText("");
}
else{
stopServer();
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
warningText.setText(utils.getString(getContext(),R.string.ftp_no_wifi));
ftpAddrText.setText("");
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
}
};
private BroadcastReceiver ftpReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action == FTPService.ACTION_STARTED) {
statusText.setText(utils.getString(getContext(), R.string.ftp_status_running));
warningText.setText("");
ftpAddrText.setText(getFTPAddressString());
ftpBtn.setText(utils.getString(getContext(),R.string.stop_ftp));
}
else if(action == FTPService.ACTION_FAILEDTOSTART){
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
warningText.setText("Oops! Something went wrong");
ftpAddrText.setText("");
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
else if(action == FTPService.ACTION_STOPPED){
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
ftpAddrText.setText("");
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_ftp,container,false);
// return inflater.inflate(R.layout.article_view, container, false);
statusText =(TextView) rootView.findViewById(R.id.statusText);
warningText = (TextView) rootView.findViewById(R.id.warningText);
ftpAddrText = (TextView) rootView.findViewById(R.id.ftpAddressText);
ftpBtn = (Button) rootView.findViewById(R.id.startStopButton);
SharedPreferences Sp = PreferenceManager.getDefaultSharedPreferences(getContext());
int th = Integer.parseInt(Sp.getString("theme", "0"));
// checking if theme should be set light/dark or automatic
int theme1 = th == 2 ? PreferenceUtils.hourOfDay() : th;
ImageView ftpImage = (ImageView)rootView.findViewById(R.id.ftp_image);
//light theme
if(theme1 == 0){
ftpImage.setImageResource(R.drawable.ic_ftp_light);
}else{
//dark
ftpImage.setImageResource(R.drawable.ic_ftp_dark);
}
ftpBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if(!FTPService.isRunning()){
if(FTPService.isConnectedToWifi(getContext()))
startServer();
else
warningText.setText(utils.getString(getContext(),R.string.ftp_no_wifi));
}
else{
stopServer();
}
}
});
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
mainActivity=(MainActivity)getActivity();
mainActivity.setActionBarTitle(utils.getString(getActivity(), R.string.ftp));
mainActivity.floatingActionButton.hideMenuButton(true);
mainActivity.buttonBarFrame.setVisibility(View.GONE);
mainActivity.supportInvalidateOptionsMenu();
}
#Override
public void onDestroy(){
super.onDestroy();
}
private void startServer() {
getContext().sendBroadcast(new Intent(FTPService.ACTION_START_FTPSERVER));
}
private void stopServer() {
getContext().sendBroadcast(new Intent(FTPService.ACTION_STOP_FTPSERVER));
}
#Override
public void onResume(){
super.onResume();
updateStatus();
IntentFilter wifiFilter = new IntentFilter();
wifiFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
getContext().registerReceiver(mWifiReceiver,wifiFilter);
IntentFilter ftpFilter = new IntentFilter();
ftpFilter.addAction(FTPService.ACTION_STARTED);
ftpFilter.addAction(FTPService.ACTION_STOPPED);
ftpFilter.addAction(FTPService.ACTION_FAILEDTOSTART);
getContext().registerReceiver(ftpReceiver,ftpFilter);
}
#Override
public void onPause(){
super.onPause();
getContext().unregisterReceiver(mWifiReceiver);
getContext().unregisterReceiver(ftpReceiver);
}
private void updateStatus(){
if(FTPService.isRunning()){
statusText.setText(utils.getString(getContext(),R.string.ftp_status_running));
ftpBtn.setText(utils.getString(getContext(),R.string.stop_ftp));
ftpAddrText.setText(getFTPAddressString());
}
else{
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
}
private String getFTPAddressString(){
return "ftp://"+FTPService.getLocalInetAddress(getContext()).getHostAddress()+":"+FTPService.getPort();
}
}
I this the java page where I shall write the admob call?
try and use this code solve the issue
http://www.androidhive.info/2016/02/android-how-to-integrate-google-admob-in-your-app/
your code java has to be added inside onCreateView function in FTPServerFragement like this :
public class FTPServerFragment extends Fragment {
TextView statusText,warningText,ftpAddrText;
Button ftpBtn;
Futils utils = new Futils();
private MainActivity mainActivity;
private View rootView;
private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMan.getActiveNetworkInfo();
if (netInfo != null && netInfo.getType() == ConnectivityManager.TYPE_WIFI){
warningText.setText("");
}
else{
stopServer();
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
warningText.setText(utils.getString(getContext(),R.string.ftp_no_wifi));
ftpAddrText.setText("");
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
}
};
private BroadcastReceiver ftpReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action == FTPService.ACTION_STARTED) {
statusText.setText(utils.getString(getContext(), R.string.ftp_status_running));
warningText.setText("");
ftpAddrText.setText(getFTPAddressString());
ftpBtn.setText(utils.getString(getContext(),R.string.stop_ftp));
}
else if(action == FTPService.ACTION_FAILEDTOSTART){
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
warningText.setText("Oops! Something went wrong");
ftpAddrText.setText("");
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
else if(action == FTPService.ACTION_STOPPED){
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
ftpAddrText.setText("");
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_ftp,container,false);
// return inflater.inflate(R.layout.article_view, container, false);
statusText =(TextView) rootView.findViewById(R.id.statusText);
warningText = (TextView) rootView.findViewById(R.id.warningText);
ftpAddrText = (TextView) rootView.findViewById(R.id.ftpAddressText);
ftpBtn = (Button) rootView.findViewById(R.id.startStopButton);
//your ads
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
mAdView = rootView.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
SharedPreferences Sp = PreferenceManager.getDefaultSharedPreferences(getContext());
int th = Integer.parseInt(Sp.getString("theme", "0"));
// checking if theme should be set light/dark or automatic
int theme1 = th == 2 ? PreferenceUtils.hourOfDay() : th;
ImageView ftpImage = (ImageView)rootView.findViewById(R.id.ftp_image);
//light theme
if(theme1 == 0){
ftpImage.setImageResource(R.drawable.ic_ftp_light);
}else{
//dark
ftpImage.setImageResource(R.drawable.ic_ftp_dark);
}
ftpBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if(!FTPService.isRunning()){
if(FTPService.isConnectedToWifi(getContext()))
startServer();
else
warningText.setText(utils.getString(getContext(),R.string.ftp_no_wifi));
}
else{
stopServer();
}
}
});
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
mainActivity=(MainActivity)getActivity();
mainActivity.setActionBarTitle(utils.getString(getActivity(), R.string.ftp));
mainActivity.floatingActionButton.hideMenuButton(true);
mainActivity.buttonBarFrame.setVisibility(View.GONE);
mainActivity.supportInvalidateOptionsMenu();
}
#Override
public void onDestroy(){
super.onDestroy();
}
private void startServer() {
getContext().sendBroadcast(new Intent(FTPService.ACTION_START_FTPSERVER));
}
private void stopServer() {
getContext().sendBroadcast(new Intent(FTPService.ACTION_STOP_FTPSERVER));
}
#Override
public void onResume(){
super.onResume();
updateStatus();
IntentFilter wifiFilter = new IntentFilter();
wifiFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
getContext().registerReceiver(mWifiReceiver,wifiFilter);
IntentFilter ftpFilter = new IntentFilter();
ftpFilter.addAction(FTPService.ACTION_STARTED);
ftpFilter.addAction(FTPService.ACTION_STOPPED);
ftpFilter.addAction(FTPService.ACTION_FAILEDTOSTART);
getContext().registerReceiver(ftpReceiver,ftpFilter);
}
#Override
public void onPause(){
super.onPause();
getContext().unregisterReceiver(mWifiReceiver);
getContext().unregisterReceiver(ftpReceiver);
}
private void updateStatus(){
if(FTPService.isRunning()){
statusText.setText(utils.getString(getContext(),R.string.ftp_status_running));
ftpBtn.setText(utils.getString(getContext(),R.string.stop_ftp));
ftpAddrText.setText(getFTPAddressString());
}
else{
statusText.setText(utils.getString(getContext(),R.string.ftp_status_not_running));
ftpBtn.setText(utils.getString(getContext(),R.string.start_ftp));
}
}
private String getFTPAddressString(){
return "ftp://"+FTPService.getLocalInetAddress(getContext()).getHostAddress()+":"+FTPService.getPort();
}
}
I have an SplashScreen and a MainActivity, when tha app launchs it displays the Splash Screen (3 secs delay) then the MainActivity, but when I click a BarNotification of mi App (outside of the App) the Splash Screen Displays(3 seconds delay) and the App Crashes, in LogCat he MainActivity Destroys itself between the Splash Screen Intent LifeCycle. (at lines 29,30 logcat)
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<WebView
android:id="#+id/browser"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
splash.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:background="#color/white"
>
<ImageView android:layout_width="wrap_content"
android:contentDescription="splash screen"
android:id="#+id/splash"
android:src="#drawable/splash"
android:layout_height="wrap_content"
android:scaleType="centerInside"/>
</LinearLayout>
Why I'm not able to Launch correctly the App through the Bar Notificaction?
Here is some code:
MainActivity.java
public class MainActivity extends Activity {
private WebView webview;
public MainActivity() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
log.debug("onCreate(): " + savedInstanceState);
MyApplication.startSomeMobileCore(this);
MyApplication.startSomeMobileNotifier(this);
setContentView(R.layout.main);
onNewIntent(getIntent());
}
#Override
protected void onStart() {
log.debug("onStart()");
super.onStart();
}
#Override
protected void onRestart() {
super.onRestart();
this.wasRestarted = true;
}
#Override
protected void onResume() {
super.onResume();
}
protected void onPause() {
super.onPause();
this.receivedIntent = false;
}
protected void onStop() {
super.onStop();
this.receivedIntent = false;
}
public void onDestroy() {
super.onDestroy();
}
#Override
public void onNewIntent(Intent intent) {
log.debug("onNewIntent(): " + intent);
super.onNewIntent(intent);
if(intent == null) {
log.warn("Received null intent, will ignore");
}
if ("OK".equals(authCode)) {
if (intent != null && intent.getData() != null &&
("content".equals(intent.getData().getScheme()) ||
"http".equals(intent.getData().getScheme()))) {
log.debug("intent.getData() :" + intent.getData() + "; intent.getData().getScheme() : " + intent.getData().getScheme());
String requestedPath;
if ("http".equals(intent.getData().getScheme())) {
requestedPath = URLDecoder.decode(intent.getData().toString());
} else {
requestedPath = intent.getData().getPath();
}
showResource(requestedPath);
} else {
log.debug("Intent without data -> go to entry page after splash screen");
showResource(Configuration.properties.getProperty(""));
}
} else {
Intent errorIntent = new Intent(this, ErrorIntent.class);
startActivity(errorIntent);
// finish actual activity
finish();
}
log.debug("Show splash screen");
Intent intentSplash = new Intent(this, SplashIntent.class);
startActivity(intentSplash);
}
void showResource(String resourceToShow) {
webview = (WebView)findViewById(R.id.browser);
webview.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
webview.setWebViewClient(new WebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
webview.loadUrl(resourceToShow);
}
}
SplashIntent.java
public class SplashIntent extends Activity {
// Time splash screen should be shown (in ms)
private static final int splashTime = 3000;
static Logger log = Logger.getLogger(SplashIntent.class);
#Override
public void onCreate(final Bundle savedInstanceState) {
log.debug("SplashIntent: onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
log.debug("SplashIntent: killing splash");
finish();
}
}, splashTime);
}
}
logcat
Hope you guys can help me with this... I'm really out of ideas at this point
Try this inside your SplashIntent class
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent mainIntent = new Intent(Splash.this,MainActivity.class);
SplashIntent.this.startActivity(mainIntent);
SplashIntent.this.finish();
},splashTime);