button click not responding - java

This is the demo code and when I add onClickListener in fill function it is not working and if i set any other property like background color it works fine.
private void fillHolder(FriendsHolder holder, final Friend friend) {
if (friend == null)
return;
Iterator<Button> iViews = holder.interests.iterator();
Iterator<String> iInterests = friend.getInterests().iterator();
while (iViews.hasNext() && iInterests.hasNext()) {
iViews.next().setText(iInterests.next());
}
Iterator<Button> iViewss = holder.interests.iterator();
while (iViewss.hasNext()) {
iViewss.next().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), friend.getNickname(), Toast.LENGTH_SHORT).show();
}
});
}
holder.infoPage.setBackgroundColor(getResources().getColor(friend.getBackground()));
holder.nickName.setText(friend.getNickname());
}
}

You're iterating through iViewss (with double S in the end) and you're setting the listener to iViews(with single S in the end).
It's not the same object.
iViews.next().setOnClickListener() will throw a NoSuchElementException because there is not a next element.
Change your code like that:
private void fillHolder(FriendsHolder holder, final Friend friend) {
if (friend == null)
return;
Iterator<Button> iViews = holder.interests.iterator();
Iterator<String> iInterests = friend.getInterests().iterator();
while (iViews.hasNext() && iInterests.hasNext()) {
iViews.next().setText(iInterests.next());
}
while (iViews.hasNext()) {
iViews.next().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), friend.getNickname(), Toast.LENGTH_SHORT).show();
}
});
}
holder.infoPage.setBackgroundColor(getResources().getColor(friend.getBackground()));
holder.nickName.setText(friend.getNickname());
}
EDIT:
You can also combine the two while-loops (as cricket_007 suggestion):
private void fillHolder(FriendsHolder holder, final Friend friend) {
if (friend == null)
return;
Iterator<Button> iViews = holder.interests.iterator();
Iterator<String> iInterests = friend.getInterests().iterator();
while (iViews.hasNext()) {
Button button = iViews.next();
if (iInterests.hasNext()) {
button.setText(iInterests.next());
}
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), friend.getNickname(), Toast.LENGTH_SHORT).show();
}
});
}
holder.infoPage.setBackgroundColor(getResources().getColor(friend.getBackground()));
holder.nickName.setText(friend.getNickname());
}

Along with the comments from the other answer, I think this code is more appropriate - it looks like you can combine the while-loops.
private void fillHolder(FriendsHolder holder, final Friend friend) {
if (friend == null)
return;
Iterator<Button> iViews = holder.interests.iterator();
Iterator<String> iInterests = friend.getInterests().iterator();
while (iViews.hasNext()) {
Button nextButton = iViews.next();
if (iInterests.hasNext()) {
nextButton.setText(iInterests.next());
}
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(), friend.getNickname(), Toast.LENGTH_SHORT).show();
}
});
}
holder.infoPage.setBackgroundColor(getResources().getColor(friend.getBackground()));
holder.nickName.setText(friend.getNickname());
}

Related

Google billing API automatically refunding in-app purchases even after being aknowledged

I tried looking at previous questions and answers but with no luck finding a real solution. I'm acknowledging purchases once they are processed although my users are still automatically refunded. Below is my whole purchase activity. It's a simple activity with a big button to purchase the app's full version. Anoter button to restore previous purchases. A third button to show some advice if users were not able to restore their purchase.
Any help would be appreciated!
public class BuyActivity extends AppCompatActivity {
Button unlock_button;
Button restore_purchase;
static final String PRODUCT_ID = "full_version";
private BillingClient billingClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_buy);
unlock_button = findViewById(R.id.unlock_button);
restore_purchase = findViewById(R.id.restore_purchase);
billingClient = BillingClient.newBuilder(getApplicationContext())
.setListener((billingResult, list) -> {
// responds to all purchases that were already made
if (billingResult.getResponseCode()==BillingClient.BillingResponseCode.OK && list!= null) {
for (Purchase purchase:list){
if (purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED) {
acknowledge_purchase(purchase);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
features_unlocked();
}
},500);
} else {
Toast.makeText(getApplicationContext(), "ERROR OCCURRED", Toast.LENGTH_SHORT).show();
}
}
} else if (billingResult.getResponseCode()==BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED && list!=null) {
features_unlocked();
} else {
Toast.makeText(getApplicationContext(), "ERROR OCCURRED", Toast.LENGTH_SHORT).show();
}
})
.enablePendingPurchases()
.build();
connect_to_google();
restore_purchase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
restore_purchase();
}
});
unlock_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//launch_purchase_flow(productDetailsList.get(0));
Toast.makeText(getApplicationContext(), "CAN'T START THE PURCHASE PROCESS", Toast.LENGTH_SHORT).show();
}
});
}
void features_unlocked(){
App.get().MyTheme = 1;
Intent i = new Intent(BuyActivity.this, Unlocked_celebration.class);
startActivity(i);
finish();
}
void connect_to_google(){
billingClient.startConnection(new BillingClientStateListener() {
#Override
public void onBillingSetupFinished(BillingResult billingResult) {
if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
// The BillingClient is ready. You can query purchases here.
get_product_details(); // download all details to different variables as you want
Log.i( "appName", String.format( "billing setup response code %s", billingResult.toString() ) );
}
}
#Override
public void onBillingServiceDisconnected() {
connect_to_google();
// Try to restart the connection on the next request to
// Google Play by calling the startConnection() method.
}
});
}
//show products available to buy
void get_product_details(){
List<String> productIds = new ArrayList<>();
productIds.add("full_version");
SkuDetailsParams params = SkuDetailsParams
.newBuilder()
.setSkusList(productIds)
.setType(BillingClient.SkuType.INAPP)
.build();
billingClient.querySkuDetailsAsync(
params,
new SkuDetailsResponseListener() {
#Override
public void onSkuDetailsResponse(#NonNull BillingResult billingResult, #Nullable List<SkuDetails> list) {
if (billingResult.getResponseCode()==BillingClient.BillingResponseCode.OK && list!=null){
if (list.size()>0) {
Log.println(Log.DEBUG,"TAG", "onSkuDetailsResponse: " + list.get(0).getPrice());
unlock_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
billingClient.launchBillingFlow(
BuyActivity.this,
BillingFlowParams.newBuilder().setSkuDetails(list.get(0)).build()
);
}
});
}
}
}
}
);
}
void acknowledge_purchase(Purchase purchase){
AcknowledgePurchaseParams acknowledgePurchaseParams = AcknowledgePurchaseParams
.newBuilder()
.setPurchaseToken(purchase.getPurchaseToken())
.build();
billingClient.acknowledgePurchase(acknowledgePurchaseParams, new AcknowledgePurchaseResponseListener() {
#Override
public void onAcknowledgePurchaseResponse(#NonNull BillingResult billingResult) {
if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
}
}
});
}
void restore_purchase(){
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
connect_to_google();
new Handler().post(new Runnable() {
#Override
public void run() {
billingClient.queryPurchasesAsync(
BillingClient.SkuType.INAPP,
new PurchasesResponseListener() {
#Override
public void onQueryPurchasesResponse(#NonNull BillingResult billingResult, #NonNull List<Purchase> list) {
if (billingResult.getResponseCode()==BillingClient.BillingResponseCode.OK) {
for (Purchase purchase: list){
if (purchase.getPurchaseState()==Purchase.PurchaseState.PURCHASED
&& !purchase.isAcknowledged()) {
acknowledge_purchase(purchase);
features_unlocked();
} else if (purchase.getPurchaseState()==Purchase.PurchaseState.PURCHASED) {
features_unlocked();
}
}
} else if (billingResult.getResponseCode()==BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED) {
features_unlocked();
}
}
}
);
}
});
}
},300);
}
protected void onResume() {
super.onResume();
restore_purchase();
}
#Override
protected void onStop() {
super.onStop();
if (billingClient != null) billingClient.endConnection();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
public void onDestroy() {
if (billingClient != null) billingClient.endConnection();
billingClient=null;
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
if (billingClient != null) billingClient.endConnection();
}
public void cantRestore(View v){
Intent i = new Intent(BuyActivity.this, RestorePurchase.class);
startActivity(i);
}
}

How do i add another In-App Item with a different Coin Value?

billingClient = BillingClient.newBuilder(this)
.enablePendingPurchases()
.setListener(new PurchasesUpdatedListener() {
#Override
public void onPurchasesUpdated(#NonNull BillingResult billingResult, #Nullable List<Purchase> list) {
if(billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK && list != null){
for(Purchase purchase: list) {
if (purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED &&
!purchase.isAcknowledged()) {
//test
try {
coinsHandler.addCoins(150, coinsTextView);
} catch (IOException e) {
System.err.println("Could not add coins from bonus !!!!");
}
verifyPurchase(purchase);
}
}
}
}
}).build();
connectToGooglePlayBilling();
I´m not sure where to put the added Coins, this place works fine, but i dont know how to implement more Items with different values.
private void connectToGooglePlayBilling(){
billingClient.startConnection(
new BillingClientStateListener() {
#Override
public void onBillingServiceDisconnected() {
connectToGooglePlayBilling();
}
#Override
public void onBillingSetupFinished(#NonNull BillingResult billingResult) {
if(billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK){
getProductDetails();
}
}
}
);
}
private void verifyPurchase(Purchase purchase) {
String requestUrl = "https://xxxxxxx?" +
"purchaseToken=" + purchase.getPurchaseToken() + "&" +
"purchaseTime" + purchase.getPurchaseTime()+ "&" +
"orderId" + purchase.getOrderId();
Activity activity = this;
StringRequest stringRequest = new StringRequest(
Request.Method.POST,
requestUrl,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject purchaseInfoFromServer = new JSONObject(response);
if(purchaseInfoFromServer.getBoolean("isValid")) {
ConsumeParams consumeParams = ConsumeParams.newBuilder().setPurchaseToken(purchase.getPurchaseToken()).build();
billingClient.consumeAsync(
consumeParams,
new ConsumeResponseListener() {
#Override
public void onConsumeResponse(#NonNull BillingResult billingResult, #NonNull String s) {
if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
Toast.makeText(activity, "Consumed!", Toast.LENGTH_LONG).show();
}
}
}
);
}
} catch (Exception err) {
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
);
Volley.newRequestQueue(this).add(stringRequest);
}
here some more code
private void getProductDetails(){
List<String> productIds = new ArrayList<>();
productIds.add("itemone");
//item2 test
productIds.add("itemtwo");
SkuDetailsParams getProductDetailsQuery = SkuDetailsParams
.newBuilder()
.setSkusList(productIds)
.setType(BillingClient.SkuType.INAPP)
.build();
Activity activity = this;
billingClient.querySkuDetailsAsync(
getProductDetailsQuery,
new SkuDetailsResponseListener() {
#Override
public void onSkuDetailsResponse(#NonNull BillingResult billingResult, #Nullable List<SkuDetails> list) {
if(billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK &&
list != null){
TextView itemNameTextView = findViewById(R.id.itemName);
Button itemPriceButton = findViewById(R.id.itemPrice);
SkuDetails itemInfo = list.get(0);
//item2 test
TextView itemName2TextView = findViewById(R.id.itemName2);
Button itemPrice2Button = findViewById(R.id.itemPrice2);
SkuDetails itemInfo2 = list.get(1);
itemNameTextView.setText(itemInfo.getTitle());
itemPriceButton.setText(itemInfo.getPrice());
//item2 test
itemName2TextView.setText(itemInfo2.getTitle());
itemPrice2Button.setText(itemInfo2.getPrice());
itemPriceButton.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
billingClient.launchBillingFlow(
activity,
BillingFlowParams.newBuilder().setSkuDetails(itemInfo).build()
);
}
}
);
//item2 test
itemPrice2Button.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
billingClient.launchBillingFlow(
activity,
BillingFlowParams.newBuilder().setSkuDetails(itemInfo2).build()
);
}
});
}
}
}
);
}
here i got the two different buy buttons working, with different prices and Ingame Items, but i dont know how to give the right item on the right button.

my list is not showing while i click on the button

Actually i couldn't find any error here. I think i m missing something here. this filtersbutton is not working. Your help will be appreciated. Thank you
This is my fragment.class
sortByLeastExpensive = rootView.findViewById(R.id.sort_by_least_expensive);
sortByMostExpensive = rootView.findViewById(R.id.sort_by_most_expensive);
sortByMostRecent = rootView.findViewById(R.id.sort_by_most_recent);
applyFiltersBtn = rootView.findViewById(R.id.apply_filters_btn);
sortByLeastExpensive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//set the filter; or call the viewmodel to set the filter?
mViewModel.sortBy.setValue(getResources().getString(R.string.sort_rooms_ascending));
}
});
sortByMostExpensive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mViewModel.sortBy.setValue(getResources().getString(R.string.sort_rooms_descending));
}
});
sortByMostRecent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mViewModel.sortBy.setValue("sort_most_recent");
}
});
return rootView;
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mViewModel = ViewModelProviders.of(getActivity()).get(FilterRoomsViewModel.class);
mViewModel.getSortBy().observe(this, Observer -> {
Log.i("Viewmodel", "Viewmodel ,sortby: " + mViewModel.sortBy.getValue());
});
applyFiltersBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FilterRoomsRepository roomsRepository = new FilterRoomsRepository();
roomsRepository.getFilteredRooms(mViewModel.sortBy.getValue());
}
});
}
This is viewmodel.class
i have updated my viewmodel.class. now its showing me another error on fragment.class
public FilterRoomsViewModel(Application application){
super();
FilterRoomsRepository filterRoomsRepository = new FilterRoomsRepository(application);
}
public MutableLiveData<String> getRooms(){
if (rooms==null){
rooms = new MutableLiveData<String>();
}
return rooms;
}
public LiveData<String> getSortBy() {
if (sortBy == null){
sortBy = new MutableLiveData<String>();
}
return sortBy;
}
this is repository.class
if(sortyBy.equals("ascending")){
Log.i("Sort by", "Rooms sorted in ascending order");
filterQuery.orderByAscending("roomRentalAmount");
}else if (sortyBy.equals("descending")){
Log.i("Sort by", "Rooms sorted in descending order");
filterQuery.orderByDescending("roomRentalAmount");
}else {
filterQuery.orderByDescending("updatedAt");
}
filterQuery.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if(e == null){
//success
Log.i("Rooms", "Filtered rooms, " + objects.get(0).getObjectId());
rooms.setValue(objects);
}else{
//error, handle accordingly
Log.e("Error", "Error filtering, " + e.getMessage());
}
}
});
Log.i("Rooms", "Live data rooms, " + rooms.getValue());
return rooms;
}
What do you mean that its not showing? It's not showing in the ui or in logs? Because when you call getFilteredRooms you don't do anything with the result.
What i would suggest is to move the repository call to the viewModel, so that instead of calling getFilteredRooms in the fragment, you would call sth like viewModel.getFilteredRooms and then, in the viewmodel, you call the repository and you use the result to set the value of the livedata.
Then, in the fragment you just need to observe this variable and based on that you update the ui. By doing so, you separate the logic (viewmodel and repository) from the ui part (fragment).
Here is a good tutorial on how to code with mvvm pattern: https://medium.com/#er.ankitbisht/mvvm-model-view-viewmodel-kotlin-google-jetpack-f02ec7754854

how to solve catch or finally expected error? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
How to solve "'catch' or 'finally' expected" error in android studio..?
a screenshot of the error
public class FragmentRecent extends Fragment {
View root_view, parent_view;
private RecyclerView recyclerView;
private AdapterChannel adapterChannel;
private SwipeRefreshLayout swipeRefreshLayout;
private Call<CallbackChannel> callbackCall = null;
private int post_total = 0;
private int failed_page = 0;
private InterstitialAd interstitialAd;
private OfflineDatabase databaseHelper;
int counter = 3;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root_view = inflater.inflate(R.layout.fragment_recent, null);
parent_view = getActivity().findViewById(R.id.main_content);
loadInterstitialAd();
swipeRefreshLayout = (SwipeRefreshLayout) root_view.findViewById(R.id.swipe_refresh_layout_home);
swipeRefreshLayout.setColorSchemeResources(R.color.orange, R.color.green, R.color.blue, R.color.red);
recyclerView = (RecyclerView) root_view.findViewById(R.id.recyclerViewHome);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setHasFixedSize(true);
//set data and list adapter
adapterChannel = new AdapterChannel(getActivity(), recyclerView, new ArrayList<Channel>());
recyclerView.setAdapter(adapterChannel);
// on item list clicked
adapterChannel.setOnItemClickListener(new AdapterChannel.OnItemClickListener() {
#Override
public void onItemClick(View v, Channel obj, int position) {
Intent intent = new Intent(getActivity(), ActivityDetailChannel.class);
intent.putExtra(Constant.KEY_CHANNEL_CATEGORY, obj.category_name);
intent.putExtra(Constant.KEY_CHANNEL_ID, obj.channel_id);
intent.putExtra(Constant.KEY_CHANNEL_NAME, obj.channel_name);
intent.putExtra(Constant.KEY_CHANNEL_IMAGE, obj.channel_image);
intent.putExtra(Constant.KEY_CHANNEL_URL, obj.channel_url);
intent.putExtra(Constant.KEY_CHANNEL_DESCRIPTION, obj.channel_description);
startActivity(intent);
showInterstitialAd();
}
});
// detect when scroll reach bottom
adapterChannel.setOnLoadMoreListener(new AdapterChannel.OnLoadMoreListener() {
#Override
public void onLoadMore(int current_page) {
if (post_total > adapterChannel.getItemCount() && current_page != 0) {
int next_page = current_page + 1;
requestAction(next_page);
} else {
adapterChannel.setLoaded();
}
}
});
// on swipe list
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
if (callbackCall != null && callbackCall.isExecuted()) callbackCall.cancel();
adapterChannel.resetListData();
requestAction(1);
}
});
requestAction(1);
return root_view;
}
private void displayApiResult(final List<Channel> channels) {
adapterChannel.insertData(channels);
swipeProgress(false);
if (channels.size() == 0) {
showNoItemView(true);
}
}
private void requestListPostApi(final int page_no) {
ApiInterface apiInterface = RestAdapter.createAPI();
callbackCall = apiInterface.getPostByPage(page_no, Config.LOAD_MORE);
callbackCall.enqueue(new Callback<CallbackChannel>() {
#Override
public void onResponse(Call<CallbackChannel> call, Response<CallbackChannel> response) {
CallbackChannel resp = response.body();
if (resp != null && resp.status.equals("ok")) {
post_total = resp.count_total;
displayApiResult(resp.posts);
} else {
onFailRequest(page_no);
}
}
#Override
public void onFailure(Call<CallbackChannel> call, Throwable t) {
if (!call.isCanceled()) onFailRequest(page_no);
}
});
}
private void onFailRequest(int page_no) {
failed_page = page_no;
adapterChannel.setLoaded();
swipeProgress(false);
if (NetworkCheck.isConnect(getActivity())) {
} else {
//showToast("Internet Not");
if (databaseHelper.getOfflineData("FragmentCategory").length() != 0) {
setJson(databaseHelper.getOfflineData("FragmentCategory"), false);
}
}
}
//databaseHelper.removeAll();
private void requestAction(final int page_no) {
showFailedView(false, "");
showNoItemView(false);
if (page_no == 1) {
swipeProgress(true);
} else {
adapterChannel.setLoading();
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
requestListPostApi(page_no);
}
}, Constant.DELAY_TIME);
}
#Override
public void onDestroy() {
super.onDestroy();
swipeProgress(false);
if (callbackCall != null && callbackCall.isExecuted()) {
callbackCall.cancel();
}
}
private void showFailedView(boolean show, String message) {
View lyt_failed = (View) root_view.findViewById(R.id.lyt_failed_home);
((TextView) root_view.findViewById(R.id.failed_message)).setText(message);
if (show) {
recyclerView.setVisibility(View.GONE);
lyt_failed.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_failed.setVisibility(View.GONE);
}
((Button) root_view.findViewById(R.id.failed_retry)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
requestAction(failed_page);
}
});
}
private void showNoItemView(boolean show) {
View lyt_no_item = (View) root_view.findViewById(R.id.lyt_no_item_home);
((TextView) root_view.findViewById(R.id.no_item_message)).setText(R.string.no_post_found);
if (show) {
recyclerView.setVisibility(View.GONE);
lyt_no_item.setVisibility(View.VISIBLE);
} else {
recyclerView.setVisibility(View.VISIBLE);
lyt_no_item.setVisibility(View.GONE);
}
}
private void swipeProgress(final boolean show) {
if (!show) {
swipeRefreshLayout.setRefreshing(show);
return;
}
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(show);
}
});
}
public void setJson(String result, Boolean isOnline) {
try {
//inseting result to database
if(isOnline) {
ContentValues offline_data = new ContentValues();
offline_data.put(OfflineDatabase.KEY_OFFLINE_DATA, result);
if(databaseHelper.getOfflineData("FragmentCategory").length()!=0) {
databaseHelper.update("FragmentCategory",offline_data);
} else {
offline_data.put(OfflineDatabase.KEY_ACTIVITY_NAME, "FragmentCategory");
databaseHelper.addOfflineData(offline_data, null);
//handle both exceptions
}
}}}
private void loadInterstitialAd() {
if (Config.ENABLE_ADMOB_INTERSTITIAL_ADS) {
interstitialAd = new InterstitialAd(getActivity());
interstitialAd.setAdUnitId(getResources().getString(R.string.admob_interstitial_unit_id));
interstitialAd.loadAd(new AdRequest.Builder().build());
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
interstitialAd.loadAd(new AdRequest.Builder().build());
}
});
} else {
Log.d("AdMob", "AdMob Interstitial is Enabled");
}
}
private void showInterstitialAd() {
if (Config.ENABLE_ADMOB_INTERSTITIAL_ADS) {
if (interstitialAd != null && interstitialAd.isLoaded()) {
if (counter == Config.ADMOB_INTERSTITIAL_ADS_INTERVAL) {
interstitialAd.show();
counter = 1;
} else {
counter++;
}
} else {
Log.d("AdMob", "Interstitial Ad is Disabled");
}
} else {
Log.d("AdMob", "AdMob Interstitial is Disabled");
}
}}
there you start with try:
public void setJson(String result, Boolean isOnline) {
try {
...
}
...
}
which has to continue with:
try {
...
} catch(Exception e) {
} finally {
}
where either catch or finally are optional (depending where the Exception shall be handled).

TimerTask behaving like running twice or more

I am trying to make a multiplayer (2 people) turn based game which lets users do whatever they want in 60 seconds. Added Timer and TimerTask to my project. When playing first time all is good, but when I return to main screen (previous intent) with something like exit game button and re-enter game counter seems to be running like twice. Instead of going like 60-59-58 it goes like 60-58-55-53 and so on. Should I do something to stop counter while exiting game?
Here is my code:
public class ikinciekren extends AppCompatActivity{
....
#Override
public void onBackPressed()
{
...
...
cikisonay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
kullanici.status(mDatabase,"lose");
Intent intocan = new Intent(ikinciekren.this, MainActivity.class);
intocan.putExtra("firebaseuser", facebookname);
intocan.putExtra("firebaseuid", myuid);
if(runstatus){
myTimer.cancel();
myTimer.purge();
}
startActivity(intocan);
}
});
cikisiptal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);
dialog.show();
}
#Override
public void onCreate(Bundle savedInstanceState) {
...
...
// On button click opponents timer starts to run
btn = (Button)findViewById(R.id.button2);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
TextView number = (TextView) findViewById(R.id.textView4);
String number2 = number.getText().toString();
if(number2!=null ||number2!=""){
if (number2.length()==4) {
status =false;
resetSomeTimer();
launchSomeTimer();
...
...
}
}
}
});
...
...
ValueEventListener postListener2 = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot != null && dataSnapshot.getValue() != null) {
String turn = String.valueOf(dataSnapshot.getValue());
//Read a node in firebase database and acts according to that
if ("true".equals(turn)) {
status =true;
}
if ("false".equals(turn)) {
status =false;
}
resetSomeTimer();
launchSomeTimer();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Context context = getApplicationContext();
Toast.makeText(context, "Failed to load post.",
Toast.LENGTH_SHORT).show();
}
};
...
...
}
protected void onDestroy(){
super.onDestroy();
///// added this just incase
if(runstatus){
myTimer.cancel();
myTimer.purge();
}
kullanici.status(mDatabase,"off");
finish();
}
public void cikis(View view) {
if(view.getId()==R.id.button3){
...
...
cikisonay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
...
...
...
///// added this just incase
if(runstatus){
myTimer.cancel();
myTimer.purge();
}
startActivity(intocan);
}
});
cikisiptal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
...
}
}
private void launchSomeTimer() {
runstatus=true;
oppenenttimertext.setText("60");
owntimertext.setText("60");
sayac =60;
counter = new TimerTask() {
#Override
public void run () {
runOnUiThread(new Runnable() {
#Override
public void run () {
sayac--;
if (status) {
owntimertext.setText(String.valueOf(sayac));
} else {
oppenenttimertext.setText(String.valueOf(sayac));
}
if (sayac == 0) {
myTimer.cancel();
kullanici.timenotice(mDatabase);
}
}
});
}
};
myTimer = new Timer();
myTimer.schedule(counter,1000,1000);
}
public void resetSomeTimer(){
if(runstatus){
myTimer.cancel();
myTimer.purge();
}
}
}

Categories