Error with creating databse - java

public class MainActivity extends FragmentActivity implements CustomEmpDialogFragment.EmpDialogFragmentListener {
private Fragment contentFragment;
private EmpListFragment employeeListFragment;
private EmpAddFragment employeeAddFragment;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fragmentManager = getSupportFragmentManager();
if (savedInstanceState != null)
{
if (savedInstanceState.containsKey("content"))
{
String content = savedInstanceState.getString("content");
if (content.equals(EmpAddFragment.ARG_ITEM_ID))
{
if (fragmentManager.findFragmentByTag(EmpAddFragment.ARG_ITEM_ID) != null)
{
setFragmentTitle(R.string.add_emp);
contentFragment = fragmentManager.findFragmentByTag(EmpAddFragment.ARG_ITEM_ID);
}
}
}
if (fragmentManager.findFragmentByTag(EmpListFragment.ARG_ITEM_ID) != null)
{
employeeListFragment = (EmpListFragment) fragmentManager.findFragmentByTag(EmpListFragment.ARG_ITEM_ID);
contentFragment = employeeListFragment;
}
}
else
{
employeeListFragment = new EmpListFragment();
setFragmentTitle(R.string.app_name);
switchContent(employeeListFragment, EmpListFragment.ARG_ITEM_ID);
}
}
#Override
protected void onSaveInstanceState(Bundle outState)
{
if (contentFragment instanceof EmpAddFragment)
{
outState.putString("content", EmpAddFragment.ARG_ITEM_ID);
}
else
{
outState.putString("content", EmpListFragment.ARG_ITEM_ID);
}
super.onSaveInstanceState(outState);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.action_add:
setFragmentTitle(R.string.add_emp);
employeeAddFragment = new EmpAddFragment();
switchContent(employeeAddFragment, EmpAddFragment.ARG_ITEM_ID);
return true;
}
return super.onOptionsItemSelected(item);
}
public void switchContent(Fragment fragment, String tag)
{
FragmentManager fragmentManager = getSupportFragmentManager();
while (fragmentManager.popBackStackImmediate());
if (fragment != null)
{
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.content_frame, fragment, tag);
if (!(fragment instanceof EmpListFragment))
{
transaction.addToBackStack(tag);
}
transaction.commit();
contentFragment = fragment;
}
}
protected void setFragmentTitle(int resourseId)
{
setTitle(resourseId);
getActionBar().setTitle(resourseId);
}
#Override
public void onBackPressed()
{
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() > 0)
{
super.onBackPressed();
}
else if (contentFragment instanceof EmpListFragment|| fm.getBackStackEntryCount() == 0)
{
onShowQuitDialog();
}
}
public void onShowQuitDialog()
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(false);
builder.setMessage("Do You Want To Quit?");
builder.setPositiveButton(android.R.string.yes,new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int id)
{
finish();
}
});
builder.setNegativeButton(android.R.string.no,new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
}
});
builder.create().show();
}
#Override
public void onFinishDialog()
{
if (employeeListFragment != null)
{
employeeListFragment.updateView();
}
}}
here i am creating a database with CRUD operation,
while compile these code found some error that give below
Error:(35, 76) error: incompatible types: android.support.v4.app.Fragment cannot be converted to android.app.Fragment
Error:(41, 91) error: incompatible types: Fragment cannot be converted to EmpListFragment
Error:(91, 53) error: incompatible types: android.app.Fragment cannot be converted to android.support.v4.app.Fragment
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
Compilation failed; see the compiler error output for details.

You are mixing up the class Fragment from the support library and the class Fragment from the standard sdk.
If you want to use the first one, then the support fragment manager with getSupportFragmentManager(). Otherwise, use the fragment manager with getFragmentManager()

Related

Change BottomNavigationView Icons on Back Button clicked

At the bottom of my layout I have a BottomNavigationView with three fragments. If I click the back button the fragment is switching but not the bottom icons. How can I fix it?
addToBackStack() works. Maybe you have some advise to pretty the code. Is it good practise to have the fragment tags in the activity or fragment?
public class MainActivity extends AppCompatActivity {
private FragmentManager mFragmentManager;
private BottomNavigationView mBottomNavigationView;
private static final String HOME_FRAGMENT = "homeFragment";
private static final String SEARCH_FRAGMENT = "searchFragment";
private static final String SHARE_FRAGMENT = "shareFragment";
private boolean isFirstFragment;
private long mBackPressedTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
setBottomNavigationView();
}
private void init() {
mBottomNavigationView = findViewById(R.id.bottomNavigationView);
mFragmentManager = getSupportFragmentManager();
mBackPressedTime = 0;
}
private void setBottomNavigationView() {
setFragment(HomeFragment.newInstance(), HOME_FRAGMENT);
isFirstFragment = true;
mBottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.ic_home:
setFragment(HomeFragment.newInstance(), HOME_FRAGMENT);
return true;
case R.id.ic_search:
setFragment(SearchFragment.newInstance(), SEARCH_FRAGMENT);
return true;
case R.id.ic_circle:
setFragment(ShareFragment.newInstance(), SHARE_FRAGMENT);
return true;
default:
return false;
}
}
});
}
private void setFragment(Fragment fragment, String tag) {
FragmentTransaction transaction = mFragmentManager.beginTransaction();
transaction.replace(R.id.container, fragment, tag);
if (isFirstFragment) {
transaction.addToBackStack(tag);
}
transaction.commit();
}
#Override
public void onBackPressed() {
final long currentTimeMillis = System.currentTimeMillis();
if (mFragmentManager.getBackStackEntryCount() > 0) {
mFragmentManager.popBackStack();
} else if (currentTimeMillis - mBackPressedTime > 2000) {
mBackPressedTime = currentTimeMillis;
Toast.makeText(this, getString(R.string.reach_homescreen), Toast.LENGTH_SHORT).show();
} else {
super.onBackPressed();
}
}
}
#Hans Baum instead of adding your first fragment to back stack try this code,
#Override
public void onBackPressed() {
if(mBottomNavigationView.getSelectedItemId () != R.id.ic_home)
{
mBottomNavigationView.setSelectedItemId(R.id.ic_home);
}
else
{
super.onBackPressed();
}
}
This code will exit your activity if you are in Home Fragment else if you are in any other Fragment it will go to Home Fragment.
So no addToBackStack() needed. So your serFragment() method should be,
private void setFragment(Fragment fragment, String tag) {
FragmentTransaction transaction = mFragmentManager.beginTransaction();
transaction.replace(R.id.container, fragment, tag);
transaction.commit();
}
hope it helps.
Note that in your code you never assigned false to isFirstFragment so i assume all fragments are added to backstack which is very memory consuming.
UPDATE:
Since your requirement is different.As you want Instagram like tabs, i hope this implementation helps you .
Deque<Integer> mStack = new ArrayDeque<>();
boolean isBackPressed = false;
private void setBottomNavigationView() {
mBottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.ic_home:
if(!isBackPressed) {
pushFragmentIntoStack(R.id.ic_home);
}
isBackPressed = false
setFragment(HomeFragment.newInstance(), HOME_FRAGMENT);
return true;
case R.id.ic_search:
if(!isBackPressed) {
pushFragmentIntoStack(R.id.ic_search);
}
isBackPressed = false
setFragment(SearchFragment.newInstance(), SEARCH_FRAGMENT);
return true;
case R.id.ic_circle:
if(!isBackPressed) {
pushFragmentIntoStack(R.id.ic_circle);
}
isBackPressed = false
setFragment(ShareFragment.newInstance(), SHARE_FRAGMENT);
return true;
default:
return false;
}
}
});
mBottomNavigationView.setOnNavigationItemReselectedListener(new
BottomNavigationView.OnNavigationItemReselectedListener() {
#Override
public void onNavigationItemReselected(#NonNull MenuItem item) {
}
});
mBottomNavigationView.setSelectedItemId(R.id.ic_home);
pushFragmentIntoStack(R.id.ic_home);
}
private void pushFragmentIntoStack(int id)
{
if(mStack.size() < 3)
{
mStack.push(id);
}
else
{
mStack.removeLast();
mStack.push(id);
}
}
private void setFragment(Fragment fragment, String tag) {
FragmentTransaction transaction = mFragmentManager.beginTransaction();
transaction.replace(R.id.container, fragment, tag);
transaction.commit();
}
#Override
public void onBackPressed() {
if(mStack.size() > 1)
{
isBackPressed = true;
mStack.pop();
mBottomNavigationView.setSelectedItemId(mStack.peek());
}
else
{
super.onBackPressed();
}
}
I have used deque to store the order in which the tabs are clicked Since there are 3 tabs deque size is 3 .On back press it will pop the stack and go to that tab. If no item in stack it will quit the activity.
IMPORTANT NOTE:
Do not add fragments to backstack in this scenario because as i switch the tabs the backstack count will keep increasing and may even lead to MemoryOutOfBound exception.
To Question 2:
Coming to your Fragment tag question , It is good to save tag in fragment . As the fragment is reusable in any activity instead adding tag in every activity it is used , it is good if we add it in fragment itself.
Try this:
#Override
public void onBackPressed() {
if(navigation_bottom.getSelectedItemId () != R.id.action_home)
{
FragmentTransaction transaction =
((HomeActivity)this).getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.frameLayout_home, new HomeFragment());
transaction.commit();
navigation_bottom.setSelectedItemId(R.id.action_home);
}
else
{
HomeActivity.this.finishAffinity();
}
}
You can add the fragment name in the backstack with the fragment transaction
getFragmentManager()
.beginTransaction()
.replace(R.id.frame, YourCurrentFragment.newInstance())
.addToBackStack(YourFragment.class.getName())
.commit();
Then you can add onBackstackChangedListener to get the currently selected fragment
fragmentManager.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
FragmentManager.BackStackEntry bse = fragmentManager.
getBackStackEntryAt(fragmentManager.getBackStackEntryCount() -1);
//bse will be the backstack entry for current fragment
if (bse.getName().equals(YourFragment.class.getName())) {
navigationView.getMenu().getItem(0).setChecked(true);
} else if (bse.getName().equals(YourSecondFragment.class.getName())) {
navigationView.getMenu().getItem(1).setChecked(true);
}
}
});

Android BaseFragment class with multiple different fragment types

I created a base fragment class that handles setting the toolbar title, registering for when the fragment is attached, setting the menu icons and a few other things. My issue is that I've decided to use the PreferencesFragmentCompat for my settings fragment and I cant extend both my BaseFragment and androids PreferencesFragmentCompat. Using an interface here wouldn't help because my BaseFragment has a lot of functionality, and I don't want to duplicate it into each of my fragment classes. Normally to extend two classes, you just do it in two seperate files but because both already extend off Androids Fragment class, I dont see how this is possible. Is there a better way of doing this?
BaseFragment:
public abstract class BaseFragment extends Fragment {
protected View rootView;
protected AppSettings settings;
protected LayoutInflater inflater;
public static void startFragment(Activity activity, BaseFragment newFragment) {
FragmentManager fragManager = ((AppCompatActivity) activity).getSupportFragmentManager();
BaseFragment currentFragment = (BaseFragment) fragManager.findFragmentById(R.id.fragment_container);
// Start the transactions
FragmentTransaction transaction = fragManager.beginTransaction();
transaction.replace(R.id.fragment_container, newFragment);
// If there is already a fragment then we want it on the backstack
if (currentFragment != null) {
transaction.addToBackStack(null);
}
// Show it
transaction.commit();
}
#TargetApi(21)
private void lockMode(boolean start) {
if (android.os.Build.VERSION.SDK_INT >= 16) {
if (start) {
getActivity().startLockTask();
} else {
getActivity().stopLockTask();
}
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get a reference to the app settings
settings = AppSettings.getInstance(getActivity());
// Don't want keyboard to stay open between fragments
hideKeyboard();
ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
if (actionBar != null) {
if (toolbarElevation()) {
actionBar.setElevation(4 * getActivity().getResources().getDisplayMetrics().density);
} else {
actionBar.setElevation(0);
}
}
setHasOptionsMenu(true);
}
#Override
public void onResume() {
super.onResume();
// Set the title up
Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
toolbar.setTitle(getTitle());
// Enable the home button in the action bar
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);
// Change the home button icon for menu or back
if (showUpNavigation()) {
toolbar.setNavigationIcon(R.drawable.ic_navigation_back_white);
} else {
toolbar.setNavigationIcon(R.drawable.ic_menu_white);
}
if (isAppInLockTaskMode() == true && pinnedMode() == false) {
lockMode(false);
}
setDrawerMenu();
}
public boolean getAuthRequired() {
return true;
}
public boolean isBackAllowed() {
return true;
}
public boolean toolbarElevation() {
return true;
}
public String getTitle() {
return "ISOPED";
}
public boolean pinnedMode() {
return false;
}
public boolean showUpNavigation() {
return false;
}
public void hideKeyboard() {
InputMethodManager inputManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
// check if no view has focus:
View v = getActivity().getCurrentFocus();
if (v == null) {
return;
}
inputManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
public void setDrawerMenu() {
NavigationView navigationView = (NavigationView) getActivity().findViewById(R.id.drawer_navigation);
Integer menuID = null;
Integer currentMenuId = null;
if (settings.isType(AppSettings.TYPES.PERSONAL)) {
menuID = R.menu.drawer_personal;
} else if (settings.isType(AppSettings.TYPES.PROFESSIONAL)) {
if (getAuthRequired() == true) {
menuID = R.menu.drawer_professional_locked;
} else {
menuID = R.menu.drawer_professional_unlocked;
}
}
if (menuID != null) {
if (navigationView.getTag() != null) {
currentMenuId = (Integer) navigationView.getTag();
}
if (currentMenuId == null || navigationView.getMenu().size() == 0 || currentMenuId != menuID) {
navigationView.getMenu().clear();
navigationView.inflateMenu(menuID);
navigationView.setTag(Integer.valueOf(menuID));
}
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
if (settings.isType(AppSettings.TYPES.PROFESSIONAL) && pinnedMode() && false == isAppInLockTaskMode()) {
inflater.inflate(R.menu.pin_menu, menu);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
DrawerLayout drawer = (DrawerLayout) getActivity().findViewById(R.id.drawer_layout);
switch (item.getItemId()) {
case android.R.id.home:
if (showUpNavigation()) {
getActivity().onBackPressed();
} else {
drawer.openDrawer(GravityCompat.START);
}
return true;
case R.id.menu_pin:
if (isAppInLockTaskMode()) {
PinDialog dialog = new PinDialog((AppCompatActivity) getActivity(), new NavigationCallback((AppCompatActivity) getActivity()) {
#Override
public void run() {
lockMode(false);
}
});
dialog.show();
} else {
lockMode(true);
}
return true;
}
return super.onOptionsItemSelected(item);
}
private boolean isAppInLockTaskMode() {
ActivityManager activityManager;
activityManager = (ActivityManager)
getActivity().getSystemService(Context.ACTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// For SDK version 23 and above.
return activityManager.getLockTaskModeState()
!= ActivityManager.LOCK_TASK_MODE_NONE;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// When SDK version >= 21. This API is deprecated in 23.
return activityManager.isInLockTaskMode();
}
return false;
}
}
This is a nice example, where you should apply Joshua Bloch's "Favor composition over inheritance" idiom.
You can delegate all the logic that you have applied to BaseFragment to some class FragmentHelper:
public class FragmentHelper {
private final Fragment fragment;
public FragmentHelper(Fragment fragment) {
this.fragment = fragment;
}
public void create(Bundle bundle) {
// `BaseFragment`'s code goes here
}
public void resume() {
// `BaseFragment`'s code goes here
}
...
}
Now in your BaseFragment:
public class BaseFragment {
private FragmentHelper fragmentHelper;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
fragmentHelper = new FragmentHelper(this);
fragmentHelper.create(savedInstanceState);
}
#Override
public void onResume() {
fragmentHelper.resume();
}
}
And the same this should be applied to the class that is extending PreferenceFragment.
Thus, you'd evade from code duplication.
Reference:
Joshua Bloch - Effective Java 2nd edition, Item 16.

Non-functioning of the application when adding Facebook Like Button

I am working on adding Facebook Like button to the application everything is normal but the problem when running the application and do not know what exactly is the problem
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
public static final String PROPERTY_REG_ID = "notifyId";
private static final String PROPERTY_APP_VERSION = "appVersion";
GoogleCloudMessaging gcm;
SharedPreferences preferences;
String reg_cgm_id;
static final String TAG = "MainActivity";
private AdView mAdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Settings.sdkInitialize(this);
LikeView likeView = (LikeView) findViewById(R.id.like_view);
likeView.setObjectId("https://m.facebook.com/DZ.4.EverR");
likeView.setLikeViewStyle(LikeView.Style.STANDARD);
likeView.setAuxiliaryViewPosition(LikeView.AuxiliaryViewPosition.INLINE);
likeView.setHorizontalAlignment(LikeView.HorizontalAlignment.CENTER);
preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
}
//show admob banner ad
mAdView = (AdView) findViewById(R.id.adView);
mAdView.loadAd(new AdRequest.Builder().build());
mAdView.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
}
#Override
public void onAdFailedToLoad(int error) {
mAdView.setVisibility(View.GONE);
}
#Override
public void onAdLeftApplication() {
}
#Override
public void onAdOpened() {
}
#Override
public void onAdLoaded() {
mAdView.setVisibility(View.VISIBLE);
}
});
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mNavigationView = (NavigationView) findViewById(R.id.main_drawer) ;
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.frame_container, new FragmentRecent()).commit();
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
//setTitle(menuItem.getTitle());
if (menuItem.getItemId() == R.id.drawer_recent) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, new FragmentRecent()).commit();
}
if (menuItem.getItemId() == R.id.drawer_category) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, new FragmentCategory()).commit();
}
if (menuItem.getItemId() == R.id.drawer_favorite) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frame_container, new FragmentFavorite()).commit();
}
if (menuItem.getItemId() == R.id.drawer_rate) {
final String appName = getPackageName();
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appName)));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + appName)));
}
}
if (menuItem.getItemId() == R.id.drawer_more) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.play_more_apps))));
}
if (menuItem.getItemId() == R.id.drawer_setting) {
Intent i = new Intent(getBaseContext(), SettingsActivity.class);
startActivity(i);
}
return false;
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
// init analytics tracker
((Analytics) getApplication()).getTracker();
// GCM
if (checkPlayServices()) {
gcm = GoogleCloudMessaging.getInstance(getApplicationContext());
String reg_cgm_id = getRegistrationId(getApplicationContext());
Log.i(TAG, "Play Services Ok.");
if (reg_cgm_id.isEmpty()) {
Log.i(TAG, "Find Register ID.");
registerInBackground();
}
} else {
Log.i(TAG, "No valid Google Play Services APK found.");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(menuItem);
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
else {
super.onBackPressed();
}
}
#Override
public void onStart() {
super.onStart();
// analytics
GoogleAnalytics.getInstance(this).reportActivityStart(this);
}
#Override
public void onStop() {
super.onStop();
// analytics
GoogleAnalytics.getInstance(this).reportActivityStop(this);
}
#Override
protected void onPause() {
mAdView.pause();
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
mAdView.resume();
}
#Override
protected void onDestroy() {
mAdView.destroy();
super.onDestroy();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
LikeView.handleOnActivityResult(this, requestCode, resultCode, data);
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(MainActivity.this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this, 9000).show();
} else {
Log.i(TAG, "This device is not supported.");
}
return false;
}
return true;
}
private void storeRegistrationId(Context context, String regId) {
int appVersion = getAppVersion(context);
Log.i(TAG, "Saving regId on app version " + appVersion);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
}
private String getRegistrationId(Context context) {
String registrationId = preferences.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
Log.i(TAG, "Registration not found.");
return "";
}
// Check if app was updated; if so, it must clear the registration ID
// since the existing regID is not guaranteed to work with the new
// app version.
int registeredVersion = preferences.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
Log.i(TAG, "Analytics version changed.");
return "";
}
return registrationId;
}
private void registerInBackground() {
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(MainActivity.this);
}
reg_cgm_id = gcm.register(getString(R.string.google_api_sender_id));
msg = "Device registered, registration ID=" + reg_cgm_id;
Log.d(TAG, "ID GCM: " + reg_cgm_id);
sendRegistrationIdToBackend();
storeRegistrationId(MainActivity.this, reg_cgm_id);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
#Override
protected void onPostExecute(String msg) {
}
}.execute(null, null, null);
}
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (PackageManager.NameNotFoundException e) {
throw new RuntimeException("Could not get package name: " + e);
}
}
private void sendRegistrationIdToBackend() {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("token", reg_cgm_id));
new HttpTask(null, MainActivity.this, Config.SERVER_URL + "/register.php", nameValuePairs, false).execute();
}
}
This is the important part of your log:
java.lang.NullPointerException: Attempt to invoke virtual method
'void com.facebook.widget.LikeView.setObjectId(java.lang.String)'
on a null object reference at android.app.ActivityThread.performLaunchActivity
It's saying that you're trying to call the method setObjectId on a LikeView that is null. So, step through that part of the code and figure out why the LikeView is null.

How implements Android in-app-billing

I have integrate Android In-App Billing in my principal activity (MainActivity). The test works !
But, the product to be purchased is the removal of the ads. The ad is implements in a fragment. So, I can't disable ad.
This is my code :
MainActivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = "com.mypackage.inappbilling";
public static final String ITEM_SKU = "test2";
NavigationView navigationView = null;
Toolbar toolbar = null;
IabHelper mHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//InAppBilling
String base64EncodedPublicKey = "#string/base64";
// compute your public key and store it in base64EncodedPublicKey
mHelper = new IabHelper(this, base64EncodedPublicKey);
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
#SuppressLint("LongLogTag")
public void onIabSetupFinished(IabResult result) {
if (!result.isSuccess()) {
// Oh no, there was a problem.
Log.d(TAG, "Problem setting up In-app Billing: " + result);
}
// Hooray, IAB is fully set up!
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data)
{
if (!mHelper.handleActivityResult(requestCode,
resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener
= new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result,
Purchase purchase)
{
if (result.isFailure()) {
// Handle error
return;
}
else if (purchase.getSku().equals(ITEM_SKU)) {
consumeItem();
}
}
};
public void consumeItem() {
mHelper.queryInventoryAsync(mReceivedInventoryListener);
}
IabHelper.QueryInventoryFinishedListener mReceivedInventoryListener
= new IabHelper.QueryInventoryFinishedListener() {
public void onQueryInventoryFinished(IabResult result,
Inventory inventory) {
if (result.isFailure()) {
// Handle failure
} else {
mHelper.consumeAsync(inventory.getPurchase(ITEM_SKU),
mConsumeFinishedListener);
}
}
};
IabHelper.OnConsumeFinishedListener mConsumeFinishedListener =
new IabHelper.OnConsumeFinishedListener() {
public void onConsumeFinished(Purchase purchase,
IabResult result) {
}
};
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_agenda) {
//Set the fragment initially
MainFragment fragment = new MainFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
// Handle the camera action
} else if (id == R.id.nav_cadena) {
mHelper.launchPurchaseFlow(this, ITEM_SKU, 10001,
mPurchaseFinishedListener, "mypurchasetoken");
} else if (id == R.id.nav_apropos) {
//Set the fragment initially
AproposFragment fragment = new AproposFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
#Override
public void onDestroy() {
super.onDestroy();
if (mHelper != null) mHelper.dispose();
mHelper = null;
}
MainFragment.java
public class MainFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
SwipeRefreshLayout swipeLayout;
public static AdView adView;
private RecyclerView recyclerView;
private View rootView;
public MainFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_main, container, false);
StartProgress();
updateInterface();
if (Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
swipeLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(this);
swipeLayout.setColorSchemeColors(getResources().getColor(R.color.colorPrimary),
getResources().getColor(R.color.colorPrimaryDark), getResources().getColor(R.color.colorAccent));
}
private void updateInterface() {
if (purchase.getSku().equals(MainActivity.ITEM_SKU)) {
displayAd(false);
} else {
displayAd(true);
}
}
public void displayAd(boolean state) {
if (state) {
if (adView == null) {
// Google has dropped Google Play Services support for Froyo
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.FROYO) {
adView = (AdView) rootView.findViewById(R.id.adViewCardItem);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
}
}
} else {
if (adView != null) {
adView.destroy();
adView = null;
}
}
}
#Override
public void onRefresh() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
swipeLayout.setRefreshing(false);
}
}, 2000);
}
public void StartProgress() {
new AsyncProgressBar().execute();
}
private class AsyncProgressBar extends AsyncTask<Void, Void, Void> {
protected ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(getActivity());
dialog.setMessage("...");
dialog.setCancelable(false);
dialog.show();
}
#Override
protected Void doInBackground(Void... params) {
//duration of progressbar
SystemClock.sleep(1000);
return null;
}
#Override
protected void onPostExecute(Void useless) {
.....
}
}
}
I'm stuck on this part of code :
private void updateInterface() {
if (purchase.getSku().equals(MainActivity.ITEM_SKU)) {
displayAd(false);
} else {
displayAd(true);
}
}
How can I appeal to the variable " purchase" my MainActivity.java ? Or maybe this is not the right method ? Can you please enlighten me on this?
Thanks in advance !
As far as I understand you use TrivialDrive example, check how premium purchase is implemented (find usages mIsPremium).
// Do we have the premium upgrade
Purchase premiumPurchase = inventory.getPurchase(SKU_PREMIUM);
mIsPremium = (premiumPurchase != null && verifyDeveloperPayload(premiumPurchase));
Disable ads by this variable.
Finally, I chose an intermediate solution : I created two fragments , one with the pub , and without advertising.
When the user makes the purchase , it is then the ad-free fragment starts.
Here the change of my code :
MainActivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = "com.mypackage.inappbilling";
public static final String ITEM_SKU = "test2";
NavigationView navigationView = null;
Toolbar toolbar = null;
IabHelper mHelper;
boolean mIsPremium = false;
boolean mIsUserPremium = false;
boolean searchAllowed = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences prefs = getSharedPreferences(
"com.xxxxxx", 0);
mIsPremium = prefs.getBoolean("premium", false);
if (mIsPremium) {
MainFragmentDisAd fragment = new MainFragmentDisAd();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
} else {
MainFragment fragment = new MainFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
//InAppBilling
String base64EncodedPublicKey = "#string/base64";
// compute your public key and store it in base64EncodedPublicKey
mHelper = new IabHelper(this, base64EncodedPublicKey);
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
#SuppressLint("LongLogTag")
public void onIabSetupFinished(IabResult result) {
if (!result.isSuccess()) {
// Oh no, there was a problem.
Log.d(TAG, "Problem setting up In-app Billing: " + result);
}
// Hooray, IAB is fully set up. Now, let's get an inventory of
Log.d(TAG, "Setup successful. Querying inventory.");
mHelper.queryInventoryAsync(mGotInventoryListener);
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data)
{
if (!mHelper.handleActivityResult(requestCode,
resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener
= new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result,
Purchase purchase)
{
if (result.isFailure()) {
// Handle error
return;
}
if (!verifyDeveloperPayload(purchase)) {
complain("Erreur lors de l'achat. Authentification non reconnue.");
return;
}
Log.d(TAG, "Purchase successful.");
if (purchase.getSku().equals(ITEM_SKU)) {
// bought the premium upgrade!
Log.d(TAG, "It's ok.");
alert("You are premiul");
mIsPremium = true;
SharedPreferences prefs = getBaseContext().getSharedPreferences(
"com.xxxxx", 0);
prefs.edit().putBoolean("premium", true).apply();
}
};
public void consumeItem() {
mHelper.queryInventoryAsync(mReceivedInventoryListener);
}
IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
#SuppressLint("LongLogTag")
#Override
public void onQueryInventoryFinished(IabResult result,
Inventory inventory) {
Log.d(TAG, "Inventory is finish.");
if (result.isFailure()) {
complain("Echec" + result);
return;
}
/*if (inventory.hasPurchase(PREM_SKU)) {
mHelper.consumeAsync(inventory.getPurchase(PREM_SKU), null);
}*/
Log.d(TAG, "Inventory is ok.");
Purchase premiumPurchase = inventory.getPurchase(ITEM_SKU);
mIsPremium = (premiumPurchase != null && verifyDeveloperPayload(premiumPurchase));
Log.d(TAG, "User is " + (mIsPremium ? "PREMIUM" : "NOT PREMIUM"));
if (mIsPremium) {
searchAllowed = true;
mIsUserPremium = true;
Log.d(TAG, "you must be premium...");
SharedPreferences prefs = getBaseContext().getSharedPreferences(
"com.xxxx", 0);
prefs.edit().putBoolean("premium", true).apply();
}
Log.d(TAG, "Initial inventory query finished; enabling main UI.");
}
};
IabHelper.OnConsumeFinishedListener mConsumeFinishedListener =
new IabHelper.OnConsumeFinishedListener() {
public void onConsumeFinished(Purchase purchase,
IabResult result) {
}
};
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_agenda) {
if (mIsPremium) {
MainFragmentDisAd fragment = new MainFragmentDisAd();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
} else {
MainFragment fragment = new MainFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
}
} else if (id == R.id.nav_cadena) {
mHelper.launchPurchaseFlow(this, ITEM_SKU, 10001,
mPurchaseFinishedListener, "mypurchasetoken");
} else if (id == R.id.nav_apropos) {
//Set the fragment initially
AproposFragment fragment = new AproposFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
#Override
public void onDestroy() {
super.onDestroy();
if (mHelper != null) mHelper.dispose();
mHelper = null;
}
It's good for me, it works!

Issue with setting and opening fragments in Android App

I am having a issue, as my app is crashing instead of opening the fragments. I have a ListActivity, that takes you to another activity; and in that other activity, there are two fragments. The ListActivity is expecting a result from one of the fragments.
My code was working prior to adding the fragments! However the fragments are no longer showing up and the app closes...does anyone possibly know what my issue could be? And any advice on how to take this issue? I sincerely appreciate all and any help, thank you! My code is below.
The ListActivity.java:
public class LyricList extends ListActivity {
private static final int ACTIVITY_CREATE=0;
private static final int ACTIVITY_EDIT=1;
private static final int INSERT_ID = Menu.FIRST;
private static final int DELETE_ID = Menu.FIRST + 1;
private LyricsDbAdapter mDbHelper;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lyriclist);
mDbHelper = new LyricsDbAdapter(this);
mDbHelper.open();
fillData();
registerForContextMenu(getListView());
}
private void fillData() {
Cursor lyricsCursor = mDbHelper.fetchAllLyrics();
startManagingCursor(lyricsCursor);
String[] from = new String[]{LyricsDbAdapter.KEY_TITLE};
int[] to = new int[]{R.id.text1};
SimpleCursorAdapter lyrics =
new SimpleCursorAdapter(this, R.layout.lyrics_row, lyricsCursor, from, to);
setListAdapter(lyrics);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, INSERT_ID, 0, R.string.menu_insert);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch(item.getItemId()) {
case INSERT_ID:
createLyric();
return true;
}
return super.onMenuItemSelected(featureId, item);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, DELETE_ID, 0, R.string.menu_delete);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()) {
case DELETE_ID:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
mDbHelper.deleteLyric(info.id);
fillData();
return true;
}
return super.onContextItemSelected(item);
}
private void createLyric() {
Intent i = new Intent(this, NextActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent i = new Intent(this, NextActivity.class);
i.putExtra(LyricsDbAdapter.KEY_ROWID, id);
startActivityForResult(i, ACTIVITY_EDIT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
fillData();
}
}
The other activity class that should be opening via the listActivity:
public class NextActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab one = actionBar.newTab().setText("Lyric Editor");
Tab two = actionBar.newTab().setText("Loops");
one.setTabListener(new MyTabListener(new LyricEditorFragment()));
two.setTabListener(new MyTabListener(new LoopsFragment()));
actionBar.addTab(one);
actionBar.addTab(two);
}
public class MyTabListener implements TabListener{
Fragment fragment;
public MyTabListener(Fragment f){
fragment = f;
}
#Override
public void onTabReselected(Tab arg0, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab arg0, FragmentTransaction ft) {
// TODO Auto-generated method stub
ft.replace(R.id.frame1, fragment);
}
#Override
public void onTabUnselected(Tab arg0, FragmentTransaction ft) {
// TODO Auto-generated method stub
ft.remove(fragment);
}
}
}
Not sure if you want to see the fragment class, but here is this just incase:
public class LyricEditorFragment extends Fragment {
private EditText mTitleText;
private EditText mBodyText;
private Long mRowId;
private LyricsDbAdapter mDbHelper;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDbHelper = new LyricsDbAdapter(getActivity());
mDbHelper.open();
mTitleText = (EditText) getView().findViewById(R.id.title);
mBodyText = (EditText) getView().findViewById(R.id.body);
Button confirmButton = (Button) getView().findViewById(R.id.confirm);
mRowId = (savedInstanceState == null) ? null :
(Long) savedInstanceState.getSerializable(LyricsDbAdapter.KEY_ROWID);
if (mRowId == null) {
Bundle extras = getActivity().getIntent().getExtras();
mRowId = extras != null ? extras.getLong(LyricsDbAdapter.KEY_ROWID)
: null;
}
populateFields();
confirmButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
getActivity().setResult(Activity.RESULT_OK);
getActivity().finish();
}
});
}
private void populateFields() {
if (mRowId != null) {
Cursor lyric = mDbHelper.fetchLyric(mRowId);
getActivity().startManagingCursor(lyric);
mTitleText.setText(lyric.getString(
lyric.getColumnIndexOrThrow(LyricsDbAdapter.KEY_TITLE)));
mBodyText.setText(lyric.getString(
lyric.getColumnIndexOrThrow(LyricsDbAdapter.KEY_BODY)));
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveState();
outState.putSerializable(LyricsDbAdapter.KEY_ROWID, mRowId);
}
#Override
public void onPause() {
super.onPause();
saveState();
}
#Override
public void onResume() {
super.onResume();
populateFields();
}
private void saveState() {
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
if (mRowId == null) {
long id = mDbHelper.createLyric(title, body);
if (id > 0) {
mRowId = id;
}
} else {
mDbHelper.updateLyric(mRowId, title, body);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
//return super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.activity_lyriceditor, container, false);
return view;
}
}
The problem is that you are getting a View from the activity which will return null.. you need to create/inflate the view from the onCreateView..
click here and follow the steps on how to create and use a view from fragment..
Click Here

Categories

Resources