Main Activity is not executing a class inside on create - java

I'm trying to execute CheckInternetConnection class inside my main activity on create but when the oncreate is called the class is not getting launced however when i press back navigation button Main Activity successfully executes CheckInternetConnection :
Here's my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawer=findViewById(R.id.drawerlayout);
mDrawer.setTouchMode(ElasticDrawer.TOUCH_MODE_BEZEL);
Context context=this.getApplicationContext();
setupToolbar();
setupMenu();
search();
new CheckInternetConnection(this).checkConnection();
FragmentManager pr = getSupportFragmentManager();
ProjectListFragment prjlist = (ProjectListFragment)
pr.findFragmentById(R.id.frame);
if (prjlist == null) {
prjlist = new ProjectListFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in,
android.R.anim.fade_out);
fragmentTransaction.commitAllowingStateLoss();
pr.beginTransaction().replace(R.id.id_main_frame, prjlist).commit();
}
public void onBackPressed() {
int count = getFragmentManager().getBackStackEntryCount();
if (count == 0) {
Intent intent=new Intent(MainActivity.this,MainActivity.class);//This intent will refresh mainactivity on back press
startActivity(intent);
finish();
//additional code
} else {
getFragmentManager().popBackStack();
finish();
}
}
This class will basically check for internet connection and display dialog if connection is not present.
public class CheckInternetConnection {
Context ctx;
public CheckInternetConnection(Context context){
ctx=context;
}
public void checkConnection(){
if(!isInternetConnected()) {
final FancyAlertDialog.Builder alert = new FancyAlertDialog.Builder(ctx)
.setBackgroundColor(R.color.colorAccent)
.setimageResource(R.drawable.internetconnection)
.setTextTitle("No Internet")
.setTextSubTitle("Cannot connect to server")
.setBody(R.string.noconnection)
.setPositiveButtonText("Connect Now")
.setNegativeButtonText("Go Offline")
.setOnNegativeClicked(new FancyAlertDialog.OnNegativeClicked() {
#Override
public void OnClick(View view, Dialog dialog) {
Intent in=new Intent(ctx,MainActivity.class);
in.putExtra("offline","offline");
ctx.startActivity(in);
dialog.dismiss();
}
})
.setPositiveColor(R.color.colorPrimaryDark)
.setOnPositiveClicked(new FancyAlertDialog.OnPositiveClicked() {
#Override
public void OnClick(View view, Dialog dialog) {
if(isInternetConnected()){
Intent in=new Intent(ctx,MainActivity.class);
ctx.startActivity(in);
dialog.dismiss();
}else {
Intent dialogIntent = new Intent(Settings.ACTION_SETTINGS);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(dialogIntent);
}
}
})
.setBodyGravity(FancyAlertDialog.TextGravity.CENTER)
.setTitleGravity(FancyAlertDialog.TextGravity.CENTER)
.setSubtitleGravity(FancyAlertDialog.TextGravity.CENTER)
.setCancelable(false)
.build();
alert.show();
}
}
public boolean isInternetConnected() {
ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isConnectedOrConnecting();
}
}

Related

ClassCastException when casting Activity to MainActivity

I'm having a weird problem in my Android app when casting a Activity to my MainActivity. I'm using GeoFences to broadcasts events to a base activity called NotificationActivity. The NotificationActivity is used in all the other activities I use so when a GeoFence triggers an AlertDialog pops up. Now when a GeoFence triggers and I'm in an activity other than MainActivity, I need to finish the current activity and do a certain action on the MainActivity (switch to a certain tab). In my Application class I'm implementing the Application.ActivityLifeCycleCallbacks, in the onActivityResumed callback I set my currentActivity to the resumed activity (I know a static reference causes memory leaks but I need to fix this).
Here's my application class:
private static Activity currentActivity;
#Override
public void onCreate() {
super.onCreate();
// Setup Fabric
if (AppConfig.getEnvironment() != AppConfig.Environment.Development) {
Fabric.with(this, new Crashlytics(), new Answers());
}
// Init realm
Realm.init(this);
// Init Firebase
FirebaseApp.initializeApp(this);
if (AppConfig.getEnvironment() == AppConfig.Environment.Development) {
// Init Stetho with realm plugin
Stetho.initialize (
Stetho.newInitializerBuilder(this)
.enableDumpapp(Stetho.defaultDumperPluginsProvider(this))
.enableWebKitInspector(RealmInspectorModulesProvider.builder(this).build())
.build());
}
registerActivityLifecycleCallbacks(this);
}
#Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
Log.d(Constants.DEBUG, "Activity created: " + activity.toString());
}
#Override
public void onActivityStarted(Activity activity) {
Log.d(Constants.DEBUG, "Activity started: " + activity.toString());
}
#Override
public void onActivityResumed(Activity activity) {
Log.d(Constants.DEBUG, "Activity resumed: " + activity.toString());
currentActivity = activity;
}
#Override
public void onActivityPaused(Activity activity) {
Log.d(Constants.DEBUG, "Activity paused: " + activity.toString());
}
#Override
public void onActivityStopped(Activity activity) {
Log.d(Constants.DEBUG, "Activity stopped: " + activity.toString());
}
#Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
Log.d(Constants.DEBUG, "Activity SaveInstanceState: " + activity.toString());
}
#Override
public void onActivityDestroyed(Activity activity) {
Log.d(Constants.DEBUG, "Activity Destroyed: " + activity.toString());
}
public static Activity getCurrentActivity() {
return currentActivity;
}
And here's my NotificationActivity (base) activity:
public abstract class NotificationActivity extends AppCompatActivity {
private BroadcastReceiver onNoticeWithinPoi = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
abortBroadcast();
Bundle bundle = intent.getExtras();
if (bundle != null) {
Realm realm = Realm.getDefaultInstance();
Poi poi = realm.where(Poi.class).equalTo("ref", bundle.getString(Constants.POI_KEY_REF)).findFirst();
showAlertWithinPoi(context, poi);
}
}
};
private BroadcastReceiver onNoLocationProviderSet = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
warnUserNoLocationProviderSet();
}
};
private BroadcastReceiver onNoticeOutOfRange = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
abortBroadcast();
alertNoticeOutOfRange();
}
};
public Fragment getActiveFragment() {
if (getFragmentManager().getBackStackEntryCount() == 0) {
return null;
}
String tag = getFragmentManager().getBackStackEntryAt(getFragmentManager().getBackStackEntryCount() - 1).getName();
return getFragmentManager().findFragmentByTag(tag);
}
private void showAlertWithinPoi(final Context context, final Poi poi) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.poi_popup_title));
builder.setMessage(getString(R.string.poi_popup_subtitle));
builder.setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Game currentGame = Helper.getCurrentGame(context);
Game poiGame = null;
Realm realm = Realm.getDefaultInstance();
for (Game game : realm.where(Game.class).findAll()) {
for (Tag tag : game.tags) {
if (tag.poi.ref.equals(poi.ref)) {
poiGame = game;
break;
}
}
if (poiGame != null) {
break;
}
}
if (poiGame != null && poiGame.ref.equals(currentGame.ref)) {
realm.beginTransaction();
currentGame.lastSeenPoi = poi.ref;
realm.commitTransaction();
checkCurrentActivity();
} else if (poiGame != null && !poiGame.ref.equals(currentGame.ref)) {
showAlertDifferentGame(context, poiGame, poi);
}
}
});
builder.setNegativeButton(getString(R.string.later), null);
builder.setIcon(R.drawable.poi_unvisited);
builder.create().show();
}
private void showAlertDifferentGame(final Context context, final Game game, final Poi poi) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(getString(R.string.game_switch_title));
builder.setMessage(getString(R.string.game_switch_message) + " " + LanguageHelper.getGameTitle(game) + " ?");
builder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Realm realm = Realm.getDefaultInstance();
realm.beginTransaction();
game.lastSeenPoi = poi.ref;
realm.commitTransaction();
SharedPreferencesHelper.saveString(context, Constants.PREF_SELECTED, game.ref);
GeofenceService.updateGeoFences(game, context);
checkCurrentActivity();
}
});
builder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
checkCurrentActivity();
}
});
builder.create().show();
}
private void checkCurrentActivity() {
final Activity currentActivity = GeoFortApplication.getCurrentActivity();
if (currentActivity instanceof MainActivity) {
((MainActivity) currentActivity).switchTab();
} else {
currentActivity.finish();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
try {
Log.d(Constants.DEBUG, "CurrentActivity: " + currentActivity.toString());
((MainActivity) currentActivity).switchTab();
} catch (ClassCastException e) {
Log.e(Constants.EXCEPTION, e.getLocalizedMessage());
}
}
}, 5000);
}
}
private void alertNoticeOutOfRange() {
new AlertDialog.Builder(this)
.setTitle(R.string.error_location_not_close_enough_title)
.setMessage(R.string.error_location_not_close_enough_alert)
.setPositiveButton(R.string.ok, null)
.setIcon(R.drawable.ic_launcher)
.show();
}
private void warnUserNoLocationProviderSet() {
new AlertDialog.Builder(this)
.setTitle(R.string.error_location_not_available_title)
.setMessage(R.string.error_location_services_not_available_text)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO no user location set?
}
})
.setIcon(null)
.show();
}
#Override
protected void onResume() {
super.onResume();
IntentFilter filterWithinPoi = new IntentFilter(Constants.NOTIFICATION_WITHIN_POI);
filterWithinPoi.setPriority(2);
registerReceiver(onNoticeWithinPoi, filterWithinPoi);
IntentFilter filterOutOfRange = new IntentFilter(Constants.NOTIFICATION_LOCATION_OUT_OF_RANGE);
filterOutOfRange.setPriority(2);
registerReceiver(onNoticeOutOfRange, filterOutOfRange);
IntentFilter filterLocationProviderOff = new IntentFilter(Constants.NOTIFICATION_LOCATION_PROVIDER_OFF);
registerReceiver(onNoLocationProviderSet, filterLocationProviderOff);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(onNoticeWithinPoi);
unregisterReceiver(onNoticeOutOfRange);
unregisterReceiver(onNoLocationProviderSet);
}
}
you are doing something wrong on else
private void checkCurrentActivity() {
final Activity currentActivity = GeoFortApplication.getCurrentActivity();
if (currentActivity instanceof MainActivity) {
((MainActivity) currentActivity).switchTab();
} else {
currentActivity.finish();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
try {
Log.d(Constants.DEBUG, "CurrentActivity: " + currentActivity.toString());
((MainActivity) currentActivity).switchTab();
} catch (ClassCastException e) {
Log.e(Constants.EXCEPTION, e.getLocalizedMessage());
}
}
}, 5000);
}
}
Within run method the activity is not a MainActivity, as you do check it before.
Fist check
if (activity instanceOf MainActivity){
// do typecast here
}else{
// you should which which instance you have
}
This way you will get rid of classCastException

Zxing Bar code scanner issue in Android

I am working on a barcode scanner App where on button click in the first Activity, I am moving to the BarcodeScanner Activity where I am importing Zxing library functionalities. Once the scanning is completed, I am moving to a 3rd Activity where I am showing the scanned Results. On clicking a button in the 3rd activity, i am coming back to the 1st activity. For devices having Marshmallow, the code is running fine. But the issue is happening with devices having versions below marshmallow where after going back to the 1st activity from the 3rd Activity, when i am pressing again the button, the scanner activity is appearing but the camera is not starting. It just showing a blank page. Please help. Below I am posting my codes for all 3 Activities.
First Activity:
public class FirstActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(Color.parseColor("#FDB50A"));
}
ImageView Scan= (ImageView) findViewById(R.id.scanButton);
Scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirstActivity.this.finish();
Intent nextPage= new Intent(FirstActivity.this,MainActivity.class);
startActivity(nextPage);
}
});
ScannerActivity:
public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler{
Integer response = 0 ;
int currentIndex=0;
Boolean flash=false;
DataBaseHelper dataBaseHelper;
private ZXingScannerView mScannerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("onCreate", "onCreate");
checkPermissions();
mScannerView = new ZXingScannerView(this);
mScannerView.setResultHandler(this);
boolean cam= isCameraUsebyApp();
Log.d("cameraBar",cam+"");
if(cam)
{
mScannerView.stopCamera();
}
cam= isCameraUsebyApp();
Log.d("cameraBar",cam+"");
mScannerView.startCamera();
// FrameLayout frameLayout= new FrameLayout(this);
// FrameLayout.LayoutParams mainParam= new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
// frameLayout.setLayoutParams(mainParam);
// Button scanButton= new Button(this);
dataBaseHelper= new DataBaseHelper(this);
if(dataBaseHelper.checkDataBase()==false)
{
try {
dataBaseHelper.createDataBase();
} catch (IOException e)
{
e.printStackTrace();
}
}
else{
}
Log.d("AnimeshSQL","copy");
dataBaseHelper.openDataBase();
// List<String> data=dataBaseHelper.getQuotes("n",1);
// Log.d("AnimeshSQL",data.get(0).toString());
LayoutParams params =
new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
// scanButton.setBackground(getResources().getDrawable(R.drawable.round_button));
// scanButton.setText("Flash");
// scanButton.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// if(flash==false)
// {
// flash=true;
//
//
// }
// else
// {
// flash=false;
// }
// mScannerView.setFlash(flash);
// }
// });
// scanButton.setLayoutParams(params);
// frameLayout.addView(mScannerView);
// frameLayout.addView(scanButton);
// setContentView(mScannerView);
checkPermissions();
if(response == 1) {
mScannerView = null;
mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
response = 0;
}
}
public boolean isCameraUsebyApp() {
Camera camera = null;
try {
camera = Camera.open();
} catch (RuntimeException e) {
return true;
} finally {
if (camera != null) camera.release();
}
return false;
}
private void checkPermissions() {
try {
for (int i = currentIndex; i < permissions.length; i++) {
currentIndex = currentIndex + 1;
int result = ContextCompat.checkSelfPermission(context, permissions[i]);
if (result == PackageManager.PERMISSION_GRANTED) {
} else {
requestPermission(permissions[i]);
return;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Activity activity = this;
Context context = this;
String[] permissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
private void requestPermission(String permission) {
//
ActivityCompat.requestPermissions(activity, new String[]{permission}, 101);
//
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 101:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//
checkPermissions();
} else {
try {
// FuncUtils.showToast(context, permissions[0] + " Denied!!!");
} catch (Exception e) {
e.printStackTrace();
}
//
///
}
break;
}
}
#Override
public void onResume() {
super.onResume();
if(response == 1) {
mScannerView = null;
mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
response = 0;
}
mScannerView.setResultHandler(this);
mScannerView.startCamera();
}
#Override
public void onDestroy() {
super.onDestroy();
mScannerView.stopCamera();
}
#Override
protected void onRestart() {
super.onRestart();
Log.d("ani","onrestart");
}
#Override
public void handleResult(Result rawResult)
{
//Some codes to handle the result
Intent intent= new Intent(this,ScanResultActivity.class);
startActivity(intent);
//vbn
mScannerView.stopCamera();
MainActivity.this.finish();
}
}
Final Activity:
public class ScanResultActivity extends AppCompatActivity {
SharedPreferences prefs;
Button ok;
ImageView Hubbell,CI;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_result);
prefs = getSharedPreferences("ScanPref", MODE_PRIVATE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(Color.parseColor("#FDB50A"));
}
//Codes to show the data
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ScanResultActivity.this.finish();
Intent nextPage= new Intent(ScanResultActivity.this,FirstActivity.class);
startActivity(nextPage);
}
});
You can write Intent in OnActivityResult.
// Call Back method to get the Message form other Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
String message=data.getStringExtra("MESSAGE");
textView1.setText(message);
}
}

Destroy data on pressing back button in android

I have few activity files that contains almost same code as shown below. Well i have not included onDestroy and finish() method in all of my activity files, before moving forward i want to be sure of the code posted below.
public class Three extends AppCompatActivity {
Button forwardB,backwardB,homeB;
TextView textView2,textView4,textView5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.one);
//Place advertisement here
AdView adView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.build();
adView.loadAd(adRequest);
//
//find widget by Id
forwardB = (Button) findViewById(R.id.forwardB);
backwardB = (Button) findViewById(R.id.backwardB);
homeB = (Button) findViewById(R.id.homeB);
textView2= (TextView) findViewById(R.id.textView2);
textView4 = (TextView) findViewById(R.id.textView4);
textView5 = (TextView) findViewById(R.id.textView5);
textView5.setText("3/50");
//set text inside textView3 and textView4
textView2.setText("Apfel");textView4.setText("apple");
//set on click listener for forward,backward and home button
forwardB.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), Two.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
finish();
}
});
homeB.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
finish();
}
});
backwardB.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), Four.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
finish();
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
After running the application i found a serious issue with data,it looks like android keeps data in background. How can i avoid this?
Everytime i run app and check the data it seems to be increasing.
Well this is my MainActivity.java:
public class MainActivity extends Activity {
Button btnflashcards;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
//create widget ids that are usable forw rest of the code
btnflashcards = (Button) findViewById(R.id.btnflashcards);
}
//on flash card button click
public void findFlashCards(View v){
Intent i = new Intent(this, FlashCardSelection.class);
startActivity(i);
}
#Override
public void onBackPressed() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
You will need to explicitly clear the application's user data every time you exit the aplication or at any point of time you want to during the use of your app.
Use this: ActivityManager's clearApplicationUserData() method
As per documentation this will:
Permits an application to erase its own data from disk. This is
equivalent to the user choosing to clear the app's data from within
the device settings UI. It erases all dynamic data associated with the
app -- its private data and data in its private area on external
storage -- but does not remove the installed application itself, nor
any OBB files.
Give something like this a shot
import java.io.File;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
public class HelloWorld extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle *) {
super.onCreate(*);
setContentView(R.layout.main);
}
#Override
protected void onStop(){
super.onStop();
}
//Fires after the OnStop() state
#Override
protected void onDestroy() {
super.onDestroy();
try {
trimCache(this);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void trimCache(Context context) {
try {
File dir = context.getCacheDir();
if (dir != null && dir.isDirectory()) {
deleteDir(dir);
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}
}

(Android) Starting up a fragment is blocking LocationListener

So when I comment out past the facebook code comment, the Location manager does work and onLocationChanged does update the proper Latitude and Longitude. However, when I uncomment it, the Facebook functionality works but the onLocationChanged never gets called for some reason.
MainActivity.java
public class MainActivity extends FragmentActivity implements OnClickListener {
private MainFragment mainFragment;
Button sendIPbutton; //Button for sending IP Address
EditText mEdit; //Get info from what user enters in form
//TextView mText;
TextView coordinates;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*http://www.firstdroid.com/2010/04/29/android-development-using-gps-to-get-current-location-2/*/
/* Use the LocationManager class to obtain GPS locations */
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
/**************************Facebook code********************************************/
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragment = new MainFragment();
getSupportFragmentManager()
.beginTransaction()
.add(android.R.id.content, mainFragment)
.commit();
} else {
// Or set the fragment from restored state info
mainFragment = (MainFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
/*********************************************************************************/
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location loc){
loc.getLatitude();
loc.getLongitude();
String Text = "Latitude: " + loc.getLatitude() + "\nLongitude: " + loc.getLongitude();
// Toast.makeText( getApplicationContext(),Text, Toast.LENGTH_SHORT).show();
coordinates = (TextView)findViewById(R.id.coordinates);
coordinates.setText(Text);
}
#Override
public void onProviderDisabled(String provider){
Toast.makeText( getApplicationContext(),
"Gps Disabled",
Toast.LENGTH_SHORT ).show();
}
#Override
public void onProviderEnabled(String provider){
Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras){
}
}/* End of Class MyLocationListener */
#Override
public boolean onTouchEvent(MotionEvent event) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.
INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
return true;
}
public void setObject(View view){
Intent intent = new Intent(this, SetObjectActivity.class);
startActivity(intent);
}
I think there must be something going on in the oncreate function.
Here is my MainFragment.java code. Note that it's primarily from the Facebook Login and Sharing tutorial on their website.
public class MainFragment extends Fragment {
private Button shareButton;
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
private boolean pendingPublishReauthorization = false;
private static final String TAG = MainFragment.class.getSimpleName();
private TextView coordinates;
private UiLifecycleHelper uiHelper;
private final List<String> permissions;
public MainFragment() {
permissions = Arrays.asList("user_status");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
shareButton = (Button) view.findViewById(R.id.shareButton);
coordinates = (TextView) view.findViewById(R.id.coordinates);
shareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
publishStory();
}
});
LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
authButton.setFragment(this);
authButton.setReadPermissions(permissions);
if (savedInstanceState != null) {
pendingPublishReauthorization =
savedInstanceState.getBoolean(PENDING_PUBLISH_KEY, false);
}
return view;
}
#Override
public void onResume() {
super.onResume();
// For scenarios where the main activity is launched and user
// session is not null, the session state change notification
// may not be triggered. Trigger it if it's open/closed.
Session session = Session.getActiveSession();
if (session != null &&
(session.isOpened() || session.isClosed()) ) {
onSessionStateChange(session, session.getState(), null);
}
uiHelper.onResume();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(PENDING_PUBLISH_KEY, pendingPublishReauthorization);
uiHelper.onSaveInstanceState(outState);
}
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
shareButton.setVisibility(View.VISIBLE);
if (pendingPublishReauthorization &&
state.equals(SessionState.OPENED_TOKEN_UPDATED)) {
pendingPublishReauthorization = false;
publishStory();
}
} else if (state.isClosed()) {
shareButton.setVisibility(View.INVISIBLE);
}
}
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
onSessionStateChange(session, state, exception);
}
};
private void publishStory() {
Session session = Session.getActiveSession();
if (session != null){
// Check for publish permissions
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
pendingPublishReauthorization = true;
Session.NewPermissionsRequest newPermissionsRequest = new Session
.NewPermissionsRequest(this, PERMISSIONS);
session.requestNewPublishPermissions(newPermissionsRequest);
return;
}
String text = coordinates.getText().toString();
Bundle postParams = new Bundle();
postParams.putString("name", "My Location!");
postParams.putString("caption", "Thanks to Hot and Cold");
postParams.putString("description", text);
postParams.putString("link", null);
postParams.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");
Request.Callback callback= new Request.Callback() {
public void onCompleted(Response response) {
JSONObject graphResponse = response
.getGraphObject()
.getInnerJSONObject();
String postId = null;
try {
postId = graphResponse.getString("id");
} catch (JSONException e) {
Log.i(TAG,
"JSON error "+ e.getMessage());
}
FacebookRequestError error = response.getError();
if (error != null) {
Toast.makeText(getActivity()
.getApplicationContext(),
error.getErrorMessage(),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity()
.getApplicationContext(),
postId,
Toast.LENGTH_LONG).show();
}
}
};
Request request = new Request(session, "me/feed", postParams,
HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
}
private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
for (String string : subset) {
if (!superset.contains(string)) {
return false;
}
}
return true;
}
}
So apparently I was spot on about the Fragment causing the issue. to Resolve it, I just added Context to the fragment class, i imported all of the Location logic into MainFragment, and now it works!

RuntimeException : android.view.InflateException: Binary XML file line #8: Error inflating class fragment

I want to integrate my Google map with Facebook SDK to check in location via Facebook and share it out in the same layout but when I add this code to method onCreate(), it's force close and tell an errors
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragment = new MainFragment();
getSupportFragmentManager().beginTransaction().add(android.R.id.content, mainFragment).commit();
myFragmentManager = getSupportFragmentManager();
mainFragment = (MainFragment) myFragmentManager.findFragmentById(R.id.checkIn);
} else {
// Or set the fragment from restored state info
mainFragment = (MainFragment) getSupportFragmentManager().findFragmentById(android.R.id.content);
}
and here is my onCreate() method
protected void onCreate(final Bundle savedInstanceState) {
try {
// Permission StrictMode
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.check_in);
checkInButton = (Button) findViewById(R.id.shareButton);
checkInButton.setVisibility(View.VISIBLE);
authButton = (Button)findViewById(R.id.authButton);
authButton.setVisibility(View.VISIBLE);
endLocationEditText = (EditText) findViewById(R.id.endLocationEditText);
endLocationEditText.setVisibility(View.INVISIBLE);
startLocationEdittext = (EditText) findViewById(R.id.starLocationEditText);
startLocationEdittext.setVisibility(View.INVISIBLE);
toggle = (ToggleButton) findViewById(R.id.togglebutton);
toggle.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (hasConnection(getApplicationContext()) == true) {
if (toggle.isChecked()) {
endLocationEditText = (EditText) findViewById(R.id.endLocationEditText);
endLocationEditText.setVisibility(View.VISIBLE);
startLocationEdittext = (EditText) findViewById(R.id.starLocationEditText);
startLocationEdittext.setVisibility(View.INVISIBLE);
goButton.setVisibility(View.VISIBLE);
} else {
endLocationEditText = (EditText) findViewById(R.id.endLocationEditText);
endLocationEditText.setVisibility(View.INVISIBLE);
startLocationEdittext = (EditText) findViewById(R.id.starLocationEditText);
startLocationEdittext.setVisibility(View.VISIBLE);
goButton.setVisibility(View.VISIBLE);
}
checkInButton.setVisibility(View.VISIBLE);
checkInButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
endLocationEditText
.setVisibility(View.INVISIBLE);
AlertDialog.Builder builder = new AlertDialog.Builder(
CheckIn.this);
builder.setTitle("Attach photo?");
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
}
});
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
Intent captureIntent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(
captureIntent,
CAMERA_CAPTURE);
}
});
builder.show();
}
});
} else {
System.out.println("ยังไม่ได้ต่อเน็ต");
AlertDialog.Builder builder = new AlertDialog.Builder(
CheckIn.this);
builder.setTitle("Please connect to the Internet.");
builder.show();
}
}
});
goButton = (Button) findViewById(R.id.goButton);
goButton.setVisibility(View.INVISIBLE);
goButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (toggle.isChecked() == true) {
String location = endLocationEditText.getText()
.toString();
if (location != null && !location.equals("")) {
new GeocoderTask().execute(location);
}
} else {
String location = startLocationEdittext.getText()
.toString();
if (location != null && !location.equals("")) {
new GeocoderTask().execute(location);
}
}
}
});
myLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = myLocationManager.getBestProvider(criteria, true);
Location location = myLocationManager
.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
}
myLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 20000, 0, this);
// สำหรับแสดง Google maps v2
FragmentManager myFragmentManager = getSupportFragmentManager();
SupportMapFragment mySupportMapFragment = (SupportMapFragment) myFragmentManager
.findFragmentById(R.id.checkIn);
myMap = mySupportMapFragment.getMap();
myMap.setMyLocationEnabled(true);
fromMarkerPosition = new LatLng(location.getLatitude(),
location.getLongitude());
toMarkerPosition = fromMarkerPosition;
myMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
fromMarkerPosition, 13));
myMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
myMap.addMarker(new MarkerOptions()
.position(fromMarkerPosition)
.title("Yor are here!")
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
myMap.getUiSettings().setCompassEnabled(true);
myMap.getUiSettings().setZoomControlsEnabled(true);
/* จบการแสดง maps */
// สร้าง click event สำหรับระบุพิกัดจุด
myMap.setOnMapClickListener(new OnMapClickListener() {
public void onMapClick(LatLng arg0) {
if (hasConnection(getApplicationContext()) == true) {
final LatLng coordinate = arg0;
AlertDialog.Builder builder = new AlertDialog.Builder(
CheckIn.this);
endLocationEditText.setVisibility(View.INVISIBLE);
startLocationEdittext.setVisibility(View.INVISIBLE);
goButton.setVisibility(View.INVISIBLE);
System.out
.println("#####################################################");
builder.setTitle("Select Marker").setItems(
new String[] { "From", "To" },
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int position) {
try {
if (position == 0) {
fromMarkerPosition = coordinate;
System.out
.println(fromMarkerPosition
+ " yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy");
refreshMarker();
} else if (position == 1) {
toMarkerPosition = coordinate;
System.out
.println(toMarkerPosition
+ " ttttttttttttttttttttttttttttttttttttttt");
refreshMarker();
}
} catch (Exception ex) {
ex.printStackTrace();
System.out
.println("Please connect to the internet first");
}
}
});
builder.show();
myMap.animateCamera(CameraUpdateFactory
.newLatLng(coordinate));
checkInButton.setVisibility(View.VISIBLE);
checkInButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
endLocationEditText
.setVisibility(View.INVISIBLE);
AlertDialog.Builder builder = new AlertDialog.Builder(
CheckIn.this);
builder.setTitle("Attach photo?");
builder.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
}
});
builder.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int which) {
Intent captureIntent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(
captureIntent,
CAMERA_CAPTURE);
}
});
builder.show();
}
});
} else {
System.out.println("ยังไม่ได้ต่อเน็ต");
AlertDialog.Builder builder = new AlertDialog.Builder(
CheckIn.this);
builder.setTitle("Please connect to the Internet.");
builder.show();
}
}
});
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragment = new MainFragment();
getSupportFragmentManager().beginTransaction().add(android.R.id.content, mainFragment).commit();
myFragmentManager = getSupportFragmentManager();
mainFragment = (MainFragment) myFragmentManager
.findFragmentById(R.id.checkIn);
} else {
// Or set the fragment from restored state info
mainFragment = (MainFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}// end onCreate
here is my MainFragment class........
public class MainFragment extends Fragment{
private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
private boolean pendingPublishReauthorization = false;
private Button shareButton;
private UiLifecycleHelper uiHelper;
private static final String TAG = "MainFragment";
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.check_in, container, false);
LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
authButton.setFragment(this);
authButton.setReadPermissions(Arrays.asList("user_likes", "user_status"));
shareButton = (Button) view.findViewById(R.id.shareButton);
shareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
publishStory();
}
});
if (savedInstanceState != null) {
pendingPublishReauthorization =
savedInstanceState.getBoolean(PENDING_PUBLISH_KEY, false);
}
return view;
}
private void onSessionStateChange(Session session, SessionState state, Exception exception) {
if (state.isOpened()) {
Log.i(TAG, "Logged in...");
} else if (state.isClosed()) {
Log.i(TAG, "Logged out...");
}
if (state.isOpened()) {
shareButton.setVisibility(View.VISIBLE);
if (pendingPublishReauthorization &&
state.equals(SessionState.OPENED_TOKEN_UPDATED)) {
pendingPublishReauthorization = false;
publishStory();
}
} else if (state.isClosed()) {
shareButton.setVisibility(View.INVISIBLE);
}
}
private void publishStory() {
Session session = Session.getActiveSession();
if (session != null){
// Check for publish permissions
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
pendingPublishReauthorization = true;
Session.NewPermissionsRequest newPermissionsRequest = new Session
.NewPermissionsRequest(this, PERMISSIONS);
session.requestNewPublishPermissions(newPermissionsRequest);
return;
}
Bundle postParams = new Bundle();
postParams.putString("name", "Facebook SDK for Android");
postParams.putString("caption", "Build great social apps and get more installs.");
postParams.putString("description", "The Facebook SDK for Android makes it easier and faster to develop Facebook integrated Android apps.");
postParams.putString("link", "https://developers.facebook.com/android");
postParams.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");
Request.Callback callback= new Request.Callback() {
public void onCompleted(Response response) {
JSONObject graphResponse = response
.getGraphObject()
.getInnerJSONObject();
String postId = null;
try {
postId = graphResponse.getString("id");
} catch (JSONException e) {
Log.i(TAG,
"JSON error "+ e.getMessage());
}
FacebookRequestError error = response.getError();
if (error != null) {
Toast.makeText(getActivity()
.getApplicationContext(),
error.getErrorMessage(),
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity()
.getApplicationContext(),
postId,
Toast.LENGTH_LONG).show();
}
}
};
Request request = new Request(session, "me/feed", postParams,
HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
}
private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
for (String string : subset) {
if (!superset.contains(string)) {
return false;
}
}
return true;
}
#Override
public void onResume() {
super.onResume();
Session session = Session.getActiveSession();
if (session != null &&
(session.isOpened() || session.isClosed()) ) {
onSessionStateChange(session, session.getState(), null);
}
uiHelper.onResume();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(PENDING_PUBLISH_KEY, pendingPublishReauthorization);
uiHelper.onSaveInstanceState(outState);
}
}
xml line 8 is here
<fragment
android:id="#+id/checkIn"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/authButton"
class="com.google.android.gms.maps.SupportMapFragment" />
here is an Errors
03-09 20:17:15.433: E/AndroidRuntime(12547): Caused by: android.view.InflateException: Binary XML file line #8: Error inflating class fragment
03-09 20:17:15.433: E/AndroidRuntime(12547): Caused by: java.lang.IllegalArgumentException: Binary XML file line #8: Duplicate id 0x7f04000a, tag null, or parent id 0x0 with another fragment for com.google.android.gms.maps.SupportMapFragment
Take a look at http://code.google.com/p/gmaps-api-issues/issues/detail?id=5064#c1 for how to put SupportMapFragment inside fragment correctly.

Categories

Resources