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!
Related
ListView in FragmentA refresh perfectly when move from Activity to Fragment. This is my very very successful code in fragmentA but before, this is the OUTPUT that i will show the code after this:
OUTPUT:
from first Query
EAT
DRINK
POOP
from second Query
DONALD TRUMP
BARRACK OBAMA
GEORGE BUSH
the success above output happen when i move from,
FragmentA --> Activity --> back to FragmentA
bu when i move like this,
FragmentA --> FragmentB --> back to FragmentA
ListView show unwanted ASCENDING result
// wrong
POOP
DRINK
EAT
// true
EAT
DRINK
EAT
and there is no second query at all.
I am very thankful for your response. Before i show the code after this,
this is what happen why go to Activity then having successful refresh
because i put Fragments in MainActivity, so:
MainActiviy --> Activity --> call again onCreate in MainActivity
FragmentA --> FragmentB --> not call onCreate in MainActivity
All codes below inside FragmentA.
Ok, First Query code:
// when scroll reach bottom
recyclerSeen.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(#NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
// vertical scroll
Boolean reachBottom = !recyclerView.canScrollVertically(-1);
if (reachBottom) {
secondQuery();
}
}
});
Query firstQuery = firebaseFirestore
.collection("Posts")
.orderBy("timestamp", Query.Direction.DESCENDING)
.limit(3);
firstQuery.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
if (isFirstPageFirstLoad) {
lastVisible = documentSnapshots.getDocuments().get(documentSnapshots.size() - 1);
}
for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {
if (doc.getType() == DocumentChange.Type.ADDED) {
//String postId = doc.getDocument().getId();
ContentProfile contentSeen = doc.getDocument().toObject(ContentProfile.class);
/* how to store multi ArrayList */
if (isFirstPageFirstLoad) {
contentList.add(contentSeen);
} else {
contentList.add(0, contentSeen);
}
adapterSeen.notifyDataSetChanged();
}
}
isFirstPageFirstLoad = false;
}
});
second Query code:
public void loadMorePost() {
Query nextQuery = firebaseFirestore
.orderBy("timestamp", Query.Direction.DESCENDING)
.collection("Posts")
.startAfter(lastVisible)
.limit(3);
nextQuery.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
if (!documentSnapshots.isEmpty()) {
lastVisible = documentSnapshots.getDocuments().get(documentSnapshots.size() - 1);
for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {
if (doc.getType() == DocumentChange.Type.ADDED) {
//String postId = doc.getDocument().getId();
ContentProfile contentSeen = doc.getDocument().toObject(ContentProfile.class);
contentList.add(contentSeen);
adapterSeen.notifyDataSetChanged();
}
}
}
}
});
}
MainActivity.class
public class MainActivity extends AppCompatActivity {
private HomeFragment homeFragment;
private Search search;
private CenterFragment centerFragment;
private Notification notification;
private ProfileFragment profileFragment;
private BottomNavigationView bottomNavigation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
homeFragment = new HomeFragment();
search = new Search();
centerFragment = new CenterFragment();
notification = new Notification();
profileFragment = new ProfileFragment();
bottomNavigation = findViewById(R.id.bottom_navigation);
BottomNavigationViewHelper.removeShiftAnimation(bottomNavigation);
//initializeFragment
replaceFragment(homeFragment);
}
#Override
public void onStart() {
super.onStart();
bottomNavigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener(){
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item){
switch(item.getItemId()){
case R.id.action_home :
replaceFragment(homeFragment);
return true;
case R.id.action_search :
replaceFragment(search);
return true;
case R.id.action_center :
replaceFragment(centerFragment);
return true;
case R.id.action_notif :
replaceFragment(notification);
return true;
case R.id.action_profile :
replaceFragment(profileFragment);
return true;
default:
return false;
}
}
});
}
private void replaceFragment(Fragment fragment){
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container, fragment);
fragmentTransaction.commit();
}
}
i have a solution for handling my above problem, forawhile i don't know how to to refresh it, or call MainActivity onCreate() manually , or remove() fragment or whatever clean code, what i do is, change replace become hide. And this code below work like a charm, i don't have to refresh my list.
public class MainActivity extends AppCompatActivity {
private HomeFragment homeFragment;
private Search search;
private CenterFragment centerFragment;
private Notification notification;
private ProfileFragment profileFragment;
private BottomNavigationView bottomNavigation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
homeFragment = new HomeFragment();
search = new Search();
centerFragment = new CenterFragment();
notification = new Notification();
profileFragment = new ProfileFragment();
bottomNavigation = findViewById(R.id.bottom_navigation);
BottomNavigationViewHelper.removeShiftAnimation(bottomNavigation);
initializeFragment();
//replaceFragment(homeFragment);
Toast.makeText(MainActivity.this, "MainActivity : onCreate() ", Toast.LENGTH_SHORT).show();
}
#Override
public void onStart() {
super.onStart();
bottomNavigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener(){
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item){
Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.main_container);
switch(item.getItemId()){
case R.id.action_home :
replaceFragment(homeFragment, currentFragment);
return true;
case R.id.action_search :
replaceFragment(search, currentFragment);
return true;
case R.id.action_center :
replaceFragment(centerFragment, currentFragment);
return true;
case R.id.action_notif :
replaceFragment(notification, currentFragment);
return true;
case R.id.action_profile :
replaceFragment(profileFragment, currentFragment);
return true;
default:
return false;
}
}
});
}
private void initializeFragment(){
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.main_container, homeFragment);
fragmentTransaction.add(R.id.main_container, search);
fragmentTransaction.add(R.id.main_container, centerFragment);
fragmentTransaction.add(R.id.main_container, notification);
fragmentTransaction.add(R.id.main_container, profileFragment);
fragmentTransaction.hide(search);
fragmentTransaction.hide(centerFragment);
fragmentTransaction.hide(notification);
fragmentTransaction.hide(profileFragment);
fragmentTransaction.commit();
}
// private void replaceFragment(Fragment fragment){
// FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
//
// fragmentTransaction.replace(R.id.main_container, fragment);
// fragmentTransaction.commit();
// }
private void replaceFragment(Fragment fragment, Fragment currentFragment){
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
if(fragment == homeFragment){
fragmentTransaction.hide(search);
fragmentTransaction.hide(centerFragment);
fragmentTransaction.hide(notification);
fragmentTransaction.hide(profileFragment);
}
if(fragment == search){
fragmentTransaction.hide(homeFragment);
fragmentTransaction.hide(centerFragment);
fragmentTransaction.hide(notification);
fragmentTransaction.hide(profileFragment);
}
if(fragment == centerFragment){
fragmentTransaction.hide(search);
fragmentTransaction.hide(homeFragment);
fragmentTransaction.hide(notification);
fragmentTransaction.hide(profileFragment);
}
if(fragment == notification){
fragmentTransaction.hide(search);
fragmentTransaction.hide(centerFragment);
fragmentTransaction.hide(homeFragment);
fragmentTransaction.hide(profileFragment);
}
if(fragment == profileFragment){
fragmentTransaction.hide(search);
fragmentTransaction.hide(centerFragment);
fragmentTransaction.hide(notification);
fragmentTransaction.hide(homeFragment);
}
fragmentTransaction.show(fragment);
//fragmentTransaction.replace(R.id.main_container, fragment);
fragmentTransaction.commit();
}
I want to make a POS app. In this app, I need to print a receipt, but I have a problem with the bluetooth connection.
In this code, I want to set the printer device that I use in my fragment. I want the bluetooth to stay connected even though I move to another fragment. I put the code in my MainActivity, but the problem is every time I move to another fragment, mService is always null. So I couldn't connect to the device.
Please help me. Thanks in advance.
MainActivity.Java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener{
private static final String TAG = "MainActivity";
Fragment fragment = null;
Class fragmentClass = null;
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
public static final int MESSAGE_CONNECTION_LOST = 6;
public static final int MESSAGE_UNABLE_CONNECT = 7;
private String mConnectedDeviceName = null;
// Key names received from the BluetoothService Handler
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
public static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
private BluetoothAdapter mBluetoothAdapter = null;
public BluetoothService mService = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
fragmentClass = RegisterFragment.class;
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_main2, fragment).commit();
Log.v(TAG, "Starting DoDaily service...");
startService(new Intent(this, DoDaily.class));
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
FragmentManager fm = getSupportFragmentManager();
//if you added fragment via layout xml
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the session
} else {
if (mService == null) {
setMService();
}
}
}
#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 boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.main2, menu);
return true;
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
String TAG_FRAGMENT="";
if (id == R.id.nav_regist) {
fragmentClass = RegisterFragment.class;
TAG_FRAGMENT ="register";
// Handle the camera action
} else if (id == R.id.nav_activity) {
fragmentClass = ActivityFragment.class;
TAG_FRAGMENT ="activity";
}
else if(id == R.id.nav_inventory)
{
fragmentClass = InventoryFragment.class;
TAG_FRAGMENT ="inventory";
}
else if (id == R.id.nav_manage) {
fragmentClass = SettingFragment.class;
TAG_FRAGMENT ="setting";
}
try {
fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_main2, fragment,TAG_FRAGMENT).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#SuppressLint("HandlerLeak")
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
if (DEBUG)
Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case BluetoothService.STATE_CONNECTED:
//btnScan.setText(getText(R.string.Connecting));
fragment1.btnScanEnable(false);
break;
case BluetoothService.STATE_CONNECTING:
Toast.makeText(MainActivity.this,R.string.title_connecting,Toast.LENGTH_SHORT).show();
break;
case BluetoothService.STATE_LISTEN:
case BluetoothService.STATE_NONE:
Toast.makeText(MainActivity.this,R.string.title_not_connected,Toast.LENGTH_SHORT).show();
break;
}
break;
case MESSAGE_WRITE:
break;
case MESSAGE_READ:
break;
case MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
Toast.makeText(MainActivity.this,"Connected to " + mConnectedDeviceName,
Toast.LENGTH_SHORT).show();
String text ="Connected to "+mConnectedDeviceName;
fragment1.setTvText(text);
break;
case MESSAGE_TOAST:
Toast.makeText(MainActivity.this, msg.getData().getString(TOAST), Toast.LENGTH_SHORT).show();
break;
case MESSAGE_CONNECTION_LOST:
Toast.makeText(MainActivity.this, "Device connection was lost",Toast.LENGTH_SHORT).show();
String text1 ="Not Connect to Any Device";
fragment1.setTvText(text1);
// editText.setEnabled(false);
// sendButton.setEnabled(false);
break;
case MESSAGE_UNABLE_CONNECT:
Toast.makeText(MainActivity.this, "Unable to connect device",
Toast.LENGTH_SHORT).show();
break;
}
}
};
#Override
public void onStart() {
super.onStart();
// If Bluetooth is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the session
} else {
if (mService == null){
setMService();
}
}
}
#Override
public synchronized void onResume() {
super.onResume();
if (mService != null) {
if (mService.getState() == BluetoothService.STATE_NONE) {
// Start the Bluetooth services
mService.start();
}
}
}
#Override
public synchronized void onPause() {
super.onPause();
if (DEBUG)
Log.e(TAG, "- ON PAUSE -");
}
#Override
public void onStop() {
super.onStop();
if (DEBUG)
Log.e(TAG, "-- ON STOP --");
}
#Override
public void onDestroy() {
super.onDestroy();
// Stop the Bluetooth services
if (mService != null)
mService.stop();
if (DEBUG)
Log.e(TAG, "--- ON DESTROY ---");
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (DEBUG)
Log.d(TAG, "onActivityResult " + resultCode);
switch (requestCode) {
case REQUEST_CONNECT_DEVICE:{
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
// Get the device MAC address
String address = data.getExtras().getString(
DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Get the BLuetoothDevice object
if (BluetoothAdapter.checkBluetoothAddress(address)) {
BluetoothDevice device = mBluetoothAdapter
.getRemoteDevice(address);
// Attempt to connect to the device
mService.connect(device);
}
}
break;
}
case REQUEST_ENABLE_BT:{
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a session
// FragmentManager fm1 = getSupportFragmentManager();
// SettingFragment fragment1 = (SettingFragment) fm1.findFragmentByTag("setting");
// fragment1.KeyListenerInit();
setMService();
} else {
// User did not enable Bluetooth or an error occured
Log.d(TAG, "BT not enabled");
Toast.makeText(MainActivity.this, R.string.bt_not_enabled_leaving,Toast.LENGTH_SHORT).show();
onBackPressed();
}
break;
}
}
}
public void setMService()
{
mService = new BluetoothService(MainActivity.this, mHandler);
}
}
SettingFragment.Java
public class SettingFragment extends Fragment {
public static final int REQUEST_CONNECT_DEVICE = 1;
private static final String CHINESE = "GBK";
SessionManagement sessionManagement;
DatabaseHandler db;
TextView tvConnected;
Button btnScan;
Button btnTest;
public SettingFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootview = inflater.inflate(R.layout.fragment_setting, container, false);
getActivity().setTitle("Setting");
btnScan = (Button)rootview.findViewById(R.id.btnScan);
btnTest = (Button) rootview.findViewById(R.id.btnTest);
tvConnected = (TextView) rootview.findViewById(R.id.tvPrinterConnect);
KeyListenerInit();
return rootview;
}
public void setTvText(String text)
{
tvConnected = (TextView) getActivity().findViewById(R.id.tvPrinterConnect);
tvConnected.setText(text);
}
public void btnScanEnable(Boolean set)
{
btnScan = (Button)getActivity().findViewById(R.id.btnScan);
btnScan.setEnabled(set);
}
public void KeyListenerInit() {
btnScan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent serverIntent = new Intent(getActivity(), DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
}
});
((MainActivity)getActivity()).setMService();
}
}
remove this line from fragment KeyListenerInit method because you already initialize object in Activity then why you again intialize this.
((MainActivity)getActivity()).setMService();
and remove this code from onCreate method because you already add this code in onStart method so no need in onCreate method:
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the session
} else {
if (mService == null) {
setMService();
}
}
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.
I have a MainActivity where the Swipeable Tabs are created and from there two fragments are called. I have 2 webservice for Fragment A and Fragment B where I have to parse data coming from server. I am using volley. When I am in the first fragment; both the webservice are being called and the data are not loaded for the first time.
But in the Second time it is showing correctly but it should be like this that when I am in Fragment A the service of the Fragment A should be called and when I am in Fragment B the service of the Fragment B should be called. I am attaching the code snippets.
MainActivity.java
public class MainActivity extends AppCompatActivity {
DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
int status = 0 ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**
*Setup the DrawerLayout and NavigationView
*/
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mNavigationView = (NavigationView) findViewById(R.id.shitstuff);
android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
// Show menu icon
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
/**
* Lets inflate the very first fragment
* Here , we are inflating the NewsFragment as the first Fragment
*/
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new NewsFragment()).commit();
// mNavigationView.setBackgroundColor(Color.parseColor("#CFCFCF"));
/**
* Setup click events on the Navigation View Items.
*/
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
mDrawerLayout.closeDrawers();
if (menuItem.getItemId() == R.id.nav_item_sent) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.containerView, new SportsFragment()).commit();
status = 1;
if (status == 1){
}
}
if (menuItem.getItemId() == R.id.nav_item_inbox) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new NewsFragment()).commit();
}
if (menuItem.getItemId() == R.id.nav_item_sent){
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new VideosFragment()).commit();
}
if (menuItem.getItemId() == R.id.nav_item_draft) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new OpinionFragment()).commit();
}
if (menuItem.getItemId() == R.id.nav_item_sports) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new SportsFragment()).commit();
}
if (menuItem.getItemId() == R.id.nav_item_weather) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new NewsFragment()).commit();
}
return false;
}
});
/**
* Setup Drawer Toggle of the Toolbar
*/
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.app_name,
R.string.app_name);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
#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) {
switch (item.getItemId()) {
case R.id.action_about_us:
Intent intent = new Intent(MainActivity.this, AboutUs.class);
startActivity(intent);
return true;
case R.id.action_terms_of_use:
Intent intent_two = new Intent(MainActivity.this, TermsUse.class);
startActivity(intent_two);
return true;
case R.id.action_privacy_policy:
Intent intent_three = new Intent(MainActivity.this, PrivacyPolicy.class);
startActivity(intent_three);
return true;
case R.id.action_contact_us:
Intent intent_four = new Intent(MainActivity.this, ContactUs.class);
startActivity(intent_four);
case R.id.search:
// hidetext();
Toast.makeText(MainActivity.this, "In the development Phase... Thank You...", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// private void hidetext() {
//
// Intent i = new Intent(MainActivity.this, SearchResultActivity.class);
// startActivity(i);
// }
}
TopNewsFragment
public class TopNewsFragment extends Fragment {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
private static final String url = "http://sikkimexpress.itstunner.com/api/homenewslist/topnews";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
Movie movie;
private ListView listView;
private CustomListAdapter adapter;
String imageURL = "", title = "", description = "";
public static final String KEY_ID = "news_id";
public static final String KEY_HEADURL = "news_url";
public static final String KEY_DETAILS = "news_details";
public static final String KEY_TITLE = "news_title";
RequestQueue requestQueue;
public TopNewsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_news, container, false);
listView = (ListView) rootView.findViewById(R.id.list);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int Position,
long offset) {
// TODO Auto-generated method stub
Movie item = (Movie) adapter.getItem(Position);
Intent intent = new Intent(rootView.getContext(), DetailsPage.class);
intent.putExtra(KEY_ID, item.getNewsId());
intent.putExtra(KEY_HEADURL, item.getThumbnailUrl());
intent.putExtra(KEY_TITLE, item.getTitle());
intent.putExtra(KEY_DETAILS, item.getDescription());
startActivity(intent);
}
});
// requestQueue = Volley.newRequestQueue(getActivity());
adapter = new CustomListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Loading...Please Wait...");
pDialog.setCancelable(false);
pDialog.show();
Volley.newRequestQueue(getActivity()).add(new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
hidePDialog();
try {
JSONArray jsonArray = response.getJSONArray("HomeNews");
// if (jsonArray.length() == 0) {
// new AlertDialog.Builder(getActivity())
// .setTitle("Alert")
// .setMessage("No Items found...")
// .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// // continue with delete
// }
// })
// .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// // do nothing
// }
// })
// .setIcon(android.R.drawable.ic_dialog_alert)
// .show();
// }
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject homenews = jsonArray.getJSONObject(i);
Movie movie = new Movie();
movie.setNewsId(homenews.getString("NewsId"));
movie.setDateTime(homenews.getString("DateTime"));
movie.setNewsType(homenews.getString("NewsType"));
movie.setTitle(homenews.getString("Title"));
title = movie.setTitle(homenews.getString("Title"));
description = movie.setDescription(homenews.getString("Description"));
movie.setDescription(homenews.getString("Description"));
imageURL = movie.setThumbnailUrl(homenews.getString("MainImageThumbnail"));
movie.setThumbnailUrl(homenews.getString("MainImageThumbnail"));
movieList.add(movie);
System.out.println("Setting up in ListView");
// System.out.println("Result:- " + newsId + " " + dateTime + " " + newsType + " " + title + " " + description + " " + mainImageURL);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// new AlertDialog.Builder(getActivity())
// .setTitle("No Connectivity ")
// .setMessage("Please check your internet connectivity!")
// .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// // continue with delete
// }
// })
// //.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
// //public void onClick(DialogInterface dialog, int which) {
// // do nothing
// //}
// //})
// .setIcon(android.R.drawable.ic_dialog_alert)
// .show();
hidePDialog();
}
}));
// AppController.getInstance().addToRequestQueue(jsonObjectRequest);
// requestQueue.add(jsonObjectRequest);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
LatestNewsFragment.java
public class LatestNewsFragment extends Fragment {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
private static final String url = "http://sikkimexpress.itstunner.com/api/homenewslist/latest";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;
// contacts JSONArray
private JSONArray users = null;
RequestQueue requestQueue;
public static final String KEY_HEADURL="news_url";
public static final String KEY_DETAILS="news_details";
public static final String KEY_TITLE = "news_title";
public LatestNewsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_news, container, false);
listView = (ListView) rootView.findViewById(R.id.list);
// requestQueue = Volley.newRequestQueue(getActivity());
adapter = new CustomListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int Position,
long offset) {
// TODO Auto-generated method stub
Movie item = (Movie) adapter.getItem(Position);
Intent intent = new Intent(rootView.getContext(), DetailsPage.class);
// intent.putExtra("URL", movie.getThumbnailUrl());
// intent.putExtra("title", movie.getTitle());
// intent.putExtra("description", movie.getDescription());
intent.putExtra(KEY_HEADURL, item.getThumbnailUrl());
intent.putExtra(KEY_TITLE, item.getTitle());
intent.putExtra(KEY_DETAILS, item.getDescription());
startActivity(intent);
}
});
pDialog = new ProgressDialog(getActivity());
// Showing progress dialog before making http request
pDialog.setMessage("Loading...Please Wait...");
pDialog.setCancelable(false);
pDialog.show();
Volley.newRequestQueue(getActivity()).add(new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() {
// JsonObjectRequest jsonObjectRequest =
#Override
public void onResponse(JSONObject response) {
try {
hidePDialog();
JSONArray jsonArray = response.getJSONArray("HomeNews");
// if (jsonArray.length() == 0){
// new AlertDialog.Builder(getActivity())
// .setTitle("Alert")
// .setMessage("No Items found...")
// .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// // continue with delete
// }
// })
// .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// // do nothing
// }
// })
// .setIcon(android.R.drawable.ic_dialog_alert)
// .show();
// }
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject homenews = jsonArray.getJSONObject(i);
Movie movie = new Movie();
movie.setNewsId(homenews.getString("NewsId"));
movie.setDateTime(homenews.getString("DateTime"));
movie.setNewsType(homenews.getString("NewsType"));
movie.setTitle(homenews.getString("Title"));
movie.setDescription(homenews.getString("Description"));
movie.setThumbnailUrl(homenews.getString("MainImageThumbnail"));
movieList.add(movie);
System.out.println("Setting up in ListView");
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// new AlertDialog.Builder(getActivity())
// .setTitle("No Connectivity ")
// .setMessage("Please check your internet connectivity!")
// .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int which) {
// // continue with delete
// }
// })
// //.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
// //public void onClick(DialogInterface dialog, int which) {
// // do nothing
// //}
// //})
// .setIcon(android.R.drawable.ic_dialog_alert)
// .show();
hidePDialog();
}
}));
// AppController.getInstance().addToRequestQueue(jsonObjectRequest);
// requestQueue.add(jsonObjectRequest);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
}
What probably happens is that the two fragments are both loaded even though you are only looking at one fragment at a time. Instead of creating a new RequestQueue on every request you should only have one. For example create an Application class like so:
public class MyApp extends Application {
private RequestQueue mRequestQueue;
private static MyApp mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized MyApp getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
}
Don't forget to add your application class to your manifest inside the <activity> tag:
<application
android:name=".MyApp"
Now you can put requests on that queue from your fragments:
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET,
URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Do something with response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Do something with error
}
});
//Put the actual request on the queue
MyApp.getInstance().addToRequestQueue(req);
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()