Hide ad banner with in app billing - android

How do i remove the banner ads and text view after the user has made purchase with in app billing. After the user made a payment, the banner and text does go away but as soon as they terminate the app and open again, the banner and textview still shows up but the difference is when they tap the textview, the toast "Thanks for your purchase" shows and the text and banner disappear then. How can i make them to not appear at all upon oncreate. thanks
MAIN
public class MainActivity extends AppCompatActivity implements BillingProcessor.IBillingHandler{
BillingProcessor bp;
AdView Adview;
TextView textView6;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bp = new BillingProcessor(this, "YOUR LICENSE KEY FROM GOOGLE PLAY CONSOLE HERE", this);
MobileAds.initialize(this,"ca-app-pub-3940256099942544~3347511713");
Adview=findViewById(R.id.adView);
textView6=findViewById(R.id.textView6);
AdRequest adRequest = new AdRequest.Builder()/*.addTestDevice("")*/.build();
Adview.loadAd(adRequest);
}
public void onClickAds(View view){
bp.purchase(MainActivity.this, "android.test.purchased");
}
#Override
public void onProductPurchased(#NonNull String productId, #Nullable TransactionDetails details) {
Toast.makeText(this, "Thank you for your purchase",Toast.LENGTH_LONG).show();
ViewGroup parent1 = (ViewGroup) Adview.getParent();
ViewGroup parent2 = (ViewGroup) textView6.getParent();
parent1.removeView(Adview);
parent2.removeView(textView6);
parent1.invalidate();
parent2.invalidate();
}
#Override
public void onPurchaseHistoryRestored() {
}
#Override
public void onBillingError(int errorCode, #Nullable Throwable error) {
Toast.makeText(this, "AN ERROR OCCURED.",Toast.LENGTH_LONG).show();
}
#Override
public void onBillingInitialized() {
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (!bp.handleActivityResult(requestCode, resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
#Override
public void onDestroy() {
if (bp != null) {
bp.release();
}
super.onDestroy();
}
}
XML
<com.google.android.gms.ads.AdView xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
ads:adSize="BANNER"
ads:adUnitId="ca-app-pub-3940256099942544/6300978111"
ads:layout_constraintBottom_toBottomOf="parent"
ads:layout_constraintEnd_toEndOf="parent"
ads:layout_constraintStart_toStartOf="parent"
ads:layout_constraintTop_toBottomOf="#+id/constraintLayout"
ads:layout_constraintVertical_bias="0.42"></com.google.android.gms.ads.AdView>
<TextView
android:id="#+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickAds"
android:text="Don't like seeing ads? Tap Here!"
android:textColor="#android:color/background_light"
android:textStyle="bold|italic"
app:layout_constraintBottom_toTopOf="#+id/adView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />

Try using shared preference for this issue
following step will help you
step 1. Initialize at top
private static final String PREF_FILE = "PREF_FILE";
private static final String IS_PRODUCT_PURCHASE = "IS_PRODUCT_PURCHASE";
step 2. inside onProductPurchased() method add these line
SharedPreferences.Editor editor = getSharedPreferences(PREF_FILE, MODE_PRIVATE).edit();
editor.putBoolean(IS_PRODUCT_PURCHASE,true);
editor.commit();
setp 3.call this method inside onCreate() at last
private void checkForIsPurchase() {
SharedPreferences preferences = getSharedPreferences(PREF_FILE, MODE_PRIVATE);
boolean isPurchase = preferences.getBoolean(IS_PRODUCT_PURCHASE, false);
if (isPurchase) {
Adview.setVisibility(View.GONE);
textView6.setVisibility(View.GONE);
}
}

Related

Two activities using the same fragment - problem

Two activities using the same fragment. The fragment has a text view.
Main activity writes “message 1” into the text view and it shows up.
A button in the main activity launches the second activity “for result”.
The Second activity writes “message 2” into the text view and it shows up.
A button in the second activity does set Result Activity.RESULT_OK and then finish().
The main activity gets the “onActivityResult” Result OK and writes “message 3” into the text view.
However “Message 3” does not show up in the text view. Instead “message 1” shows up.
public class MainActivity extends AppCompatActivity {
private static Context context;
private static Button btn_main;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
btn_main = findViewById(R.id.btn_main);
FragmentDisplay.setMessage1("Message 1");
btn_main.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
secondactivityLauncher.launch(intent);
}
});
}
ActivityResultLauncher<Intent> secondactivityLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
FragmentDisplay.setMessage1("Message 3");
}
}
});
public static Context getContext(){
return context;
}
}
public class SecondActivity extends AppCompatActivity {
private static Button btn_second;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
btn_second = findViewById(R.id.btn_second);
FragmentDisplay.setMessage1("Message 2");
btn_second.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = getIntent();
setResult(Activity.RESULT_OK, intent);
finish();
}
});
}
}
public class FragmentDisplay extends androidx.fragment.app.Fragment {
private static TextView textView1;
public FragmentDisplay() {
// Required empty public constructor
}
RecyclerView mRecyclerView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.display_fragment, null);
textView1 = (TextView)view.findViewById(R.id.tv1);
return view;
}
public static void setMessage1(String str){
textView1.setText(str);
}
} // end of class
//activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".main.MainActivity">
<fragment
android:id="#+id/display_fragment"
android:name="ddi.pos.display.FragmentDisplay"
android:layout_width="700dp"
android:layout_height="180dp"
android:background="#00CC00"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="80dp" />
<Button
android:id="#+id/btn_main"
android:layout_below="#+id/display_fragment"
android:layout_marginTop="100dp"
android:layout_marginLeft="50dp"
android:layout_width="200dp"
android:layout_height="200dp"
android:background="#FFFFFF00"
android:textSize="25sp"
android:text="Start Second Activity"
/>
//second_activity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".main.MainActivity">
<fragment
android:id="#+id/display_fragment"
android:name="ddi.pos.display.FragmentDisplay"
android:layout_width="700dp"
android:layout_height="180dp"
android:background="#00CC00"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="80dp" />
<Button
android:id="#+id/btn_second"
android:layout_below="#+id/display_fragment"
android:layout_marginTop="100dp"
android:layout_marginLeft="300dp"
android:layout_width="200dp"
android:layout_height="200dp"
android:background="#000000"
android:textSize="25sp"
android:text="Finish Second Activity"
/>
//display_fragment.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#CC5500"
>
<TextView android:id="#+id/tv1"
android:background="#0055FF"
android:layout_height="60dp"
android:layout_width="600dp"
android:text=""
android:layout_marginLeft="30dp"
android:layout_marginTop="30dp"
android:textSize="20dp"
android:textColor="#ff000000"
/>
Caveat: I suspect that what you posted is not what you actually want to do, but a workaround of some kind so this answer may or may not actually address your use-case. It does, however, produce the behavior you asked for in the question. You said you are not trying to send data between activities, but you want the message in the first activity to change in response to actions in the second activity which implies information may be shared.
Main Answer:
The example below, using a shared ViewModel between Activity and Fragment and using data transfer across activities using intents has the behavior you describe in your question.
The ViewModel allows sharing of data between the Activity and Fragment, since the Fragment can observe the LiveData and respond when the activity changes it. Since the question calls startActivityForResult and handles the result, I used those to handle passing data back to change the message.
MainActivity.java
public class MainActivity extends AppCompatActivity {
ActivityResultLauncher<Intent> secondActivityLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
// as you indicated:
//viewModel.setMessage("Message 3");
// or like this if you sent data
Intent data = result.getData();
if( data != null ) {
Bundle extras = data.getExtras();
if( extras != null ) {
String msg = extras.getString("response");
viewModel.setMessage(msg);
}
}
}
}
});
private MainViewModel viewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewModel = new ViewModelProvider(this).get(MainViewModel.class);
// Always initialize the message to "Message 1"
viewModel.setMessage("Message 1");
Button btn = findViewById(R.id.btn_main);
btn.setOnClickListener(view -> {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("message", "Message 2");
secondActivityLauncher.launch(intent);
});
}
}
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
// This ViewModel instance is "not" the same instance as the one from MainActivity, it is
// just to facilitate communication between the Activity and Fragment
MainViewModel viewModel = new ViewModelProvider(this).get(MainViewModel.class);
// as you had it with hard-coded message 2
// viewModel.setMessage("Message 2");
// or like this if you sent the message
Intent i = getIntent();
Bundle b = i.getExtras();
if( b != null ) {
String msg = b.getString("message");
viewModel.setMessage(msg);
}
Button btn = findViewById(R.id.btn_second);
btn.setOnClickListener(view -> {
Intent intent = new Intent();
intent.putExtra("response", "Message 3");
setResult(Activity.RESULT_OK, intent);
finish();
});
}
}
MainViewModel.java
public class MainViewModel extends ViewModel {
private final MutableLiveData<String> message_to_display = new MutableLiveData<>();
LiveData<String> message() { return message_to_display; }
void setMessage(String msg) {
message_to_display.postValue(msg);
}
}
DisplayFragment.java
public class DisplayFragment extends Fragment {
public DisplayFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_display, container, false);
}
#Override
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
TextView txt = view.findViewById(R.id.tv1);
// Get the ViewModel from the hosting activity, could be
// Main or Second, and observe its message. Update the
// TextView if the message is changed.
MainViewModel viewModel = new ViewModelProvider(requireActivity()).get(MainViewModel.class);
viewModel.message().observe(getViewLifecycleOwner(), s -> {
txt.setText(s);
});
}
}

Android check box tik mark disappear randomly when moving from one fragment to another using android-material-stepper

Instead of getting checkbox like this(i am getting it only few times randomly when moving from on fragment to another).
I am getting like this(checkbox is still true but only tik mark is missing randomly)
I am using onSaveInstanceState and onViewStateRestored. The problem is the checkbox tik mark only disappears and comes back few times but the state of checkbox is still selected i see blue color around all the selected check boxes that selected color doesn't go away only the tik mark goes away and comes back randomly.
Layout:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<CheckBox
android:id="#+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:drawableLeft="#drawable/ic_tv"
android:text="TV"
android:theme="#style/CheckBoxTheme"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="Tv" />
</android.support.constraint.ConstraintLayout>
</ScrollView>
My Fragment:
public class StepFragmentTwo extends Fragment implements BlockingStep {
private static final String CLICKS_KEY = "clicks";
private static final String TAG = "ADERVERTISMENT";
private int i = 0;
FragmentManager fm = getFragmentManager();
CheckBox c;
Boolean tv = false ;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(getLayoutResId(), container, false);
c = (CheckBox)v.findViewById(R.id.checkBox);
//initialize your UI
return v;
}
protected int getLayoutResId() {
return getArguments().getInt(String.valueOf(R.layout.step2));
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putInt(CLICKS_KEY, i);
super.onSaveInstanceState(outState);
if(outState!=null) {
outState.putBoolean("c", c.isChecked());
}
}
#Override
public void onViewStateRestored(#Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
if(savedInstanceState!=null) {
tv = savedInstanceState.getBoolean("c");
}
}
#Override
public void onResume() {
super.onResume();
c.setChecked(tv);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
public void onNextClicked(final StepperLayout.OnNextClickedCallback callback) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (c.isChecked()) {
tv = true;
}
SharedPreferences shared = getActivity().getSharedPreferences("Mypref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
editor.putBoolean("tv", tv);
editor.apply(); // This line is IMPORTANT !!!
callback.goToNextStep();
}
}, 200L);
}
#Override
#UiThread
public void onCompleteClicked(final StepperLayout.OnCompleteClickedCallback callback) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
callback.complete();
}
}, 2000L);
}
public static StepFragmentTwo newInstance(#LayoutRes int layoutResId) {
Bundle args = new Bundle();
args.putInt(String.valueOf(R.layout.step2), layoutResId);
StepFragmentTwo fragment = new StepFragmentTwo();
fragment.setArguments(args);
return fragment;
}
#Override
public VerificationError verifyStep() {
//return null if the user can go to the next step, create a new VerificationError instance otherwise
return null;
}
#Override
public void onSelected() {
//update UI when selected
}
#Override
public void onError(#NonNull VerificationError error) {
//handle error inside of the fragment, e.g. show error on EditText
}
public void onBackClicked(StepperLayout.OnBackClickedCallback callback) {
//Toast.makeText(this.getContext(), "Your custom back action. Here you should cancel currently running operations", Toast.LENGTH_SHORT).show();
callback.goToPrevStep();
}
}
In short you can do,
#Override
public void onResume() {
super.onResume();
SharedPreferences shared = getActivity().getSharedPreferences("Mypref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
tv = editor.getBoolean("tv", tv);
c.setChecked(tv);
}

Android layout is not being displayed when input is required

I have an app that uses several activities. One activity is to manually enter some values and I have four buttons in that activity. When one of the buttons is clicked it starts a new activity to get the input.
The problem is that the layout for the activity is not displayed when the get_input() function of this activity is run. It should get a decimal value from an EditText. but I keep getting a runtime error of "Invalid Float """.
If I comment out the get_input() function then the layout for the activity is shown fine.
Here is the xml file :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/manually_entry" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Please enter the decimal Latitude"
android:singleLine="true"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="Negative is South"
android:singleLine="true"
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:inputType="numberDecimal|numberSigned"
android:id="#+id/enter_decimal_number" />
</LinearLayout>
And here is the calling activity :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lat_long_manual_entry);
}
// manual entry dialog buttons
public void enter_lat_dec_deg(View v) {
Intent intent = new Intent(this.getApplicationContext(), ManuallyEnterNumbers.class);
startActivity(intent);
}
And here is the called activity that requests the actual input from the user :
package com.example.david.gpstest;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
/**
* Created by david on 06/03/16.
*/
public class ManuallyEnterNumbers extends Activity {
private EditText input;
private float decimal_input;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.manually_enter_numbers);
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onResume() {
super.onResume();
get_input();
}
public void get_input() {
input = (EditText) findViewById(R.id.enter_decimal_number);
input.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
decimal_input = Float.valueOf(input.getText().toString());
return true;
}
return false;
}
});
}
}
I am showing the function get_input() in the onStart() method but IO have also tried it in the onResume() method and that does not work either.
Any help here would be very much appreciated.
Thank You.
Float.valueOf(input.getText().toString());
The common mistake here newbies ofter make is lack of string sanitization prior attempting conversion. Even , (comma) instead of . (dot) entered as decimal part separator will cause exception to be thrown. So you simply must make string convertable (i.e. by checking what's inside, replacing , with . etc) not to mention you should expect exception to come and use try/catch to catch it to avoid app crash you are facing now.
David, hello, this is yourself. Basically you can forget about sanitizing the input. Because you have android:inputType="numberDecimal|numberSigned" in your xml you will get a numeric keypad with the comma, and space disabled. So all that the user can enter is digits a decimal point and a minus sign. Exactly what you want. Secondly, you can forget about the onStart() and onResume() methods and stick everything in onCreate() and then it will work. Your xml is absolutely fine. Your calling activity absolutely fine too although it would be a good idea to use an intent.putExtra() and an intent.getExtra() to pass the decimal_input value back to the calling activity. I have posted the code for the calling activity and the called activity below to help you out a bit.
public class ManualEntry extends Activity {
// private View layout;
// private PopupWindow enter_manual_dec_deg;
// LayoutInflater inflater;
// private EditText input;
// private float decimal_input;
// private String result;
static final int REQUEST_CODE = 1;
String button_pressed;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lat_long_manual_entry);
}
#Override
protected void onResume() {
super.onResume();
}
// manual entry dialog buttons
public void enter_lat_dec_deg(View v) {
Intent intent = new Intent(this.getApplicationContext(), ManuallyEnterNumbers.class);
button_pressed = "lat_dec_deg";
intent.putExtra("Button pressed", button_pressed);
startActivityForResult(intent, REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE) {
if (resultCode == RESULT_OK) {
double result = data.getDoubleExtra("returnData", 0.0d);
if (result < -180 || result > 180) {
Toast.makeText(this, "Value outside range - Range is -180 to 180", Toast.LENGTH_LONG).show();
}
else {
DecimalFormat var = new DecimalFormat("###.########");
Toast.makeText(this, var.format(result), Toast.LENGTH_LONG).show();
disable_button(button_pressed);
}
}
}
}
void disable_button(String pressed_button) {
Button dec_deg_button = (Button) findViewById(R.id.button_lat_dec_deg);
Button d_m_s_button = (Button) findViewById(R.id.button_lat_deg_min_sec);
if (pressed_button != null) {
if (pressed_button == "lat_dec_deg" || button_pressed == "lat_d_m_s") {
dec_deg_button.setEnabled(false);
d_m_s_button.setEnabled(false);
}
}
}
}
/*
public void enter_lat_d_m_s (View v) {
}
public void enter_lon_dec_deg(View v) {
}
public void enter_lon_d_m_s(View v) {
}
*/
And the called activity
package com.example.david.gpstest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
/**
* Created by david on 06/03/16.
*/
public class ManuallyEnterNumbers extends Activity {
private EditText input;
private String inValue;
private double decimal_input;
private Bundle extras;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.manually_enter_numbers);
extras = getIntent().getExtras();
if (extras != null) {
String buttonPressed = extras.getString("Button pressed");
if (buttonPressed.contentEquals(buttonPressed) ) {
((TextView) findViewById(R.id.enter_decimal_number)).setHint("Decimal degrees of Latitude");
TextView title_text = (TextView) findViewById(R.id.manual_entry_hint);
title_text.setText("Please enter the decimal Latitude");
TextView hint_text = (TextView) findViewById(R.id.manual_entry_hint);
hint_text.setText("(Negative is South)");
}
}
get_input();
}
#Override
protected void onStart() {
super.onStart();
// get_input();
}
#Override
protected void onResume() {
super.onResume();
// get_input();
}
public void get_input() {
input = (EditText) findViewById(R.id.enter_decimal_number);
input.setOnEditorActionListener(new TextView.OnEditorActionListener(){
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
// do stuff here
inValue = input.getText().toString();
if (inValue.isEmpty()) {
Toast.makeText(getApplicationContext(), "Enter a value", Toast.LENGTH_SHORT).show();
}
else {
// some input
decimal_input = Double.parseDouble(inValue);
Intent returnIntent = getIntent();
returnIntent.putExtra("returnData", decimal_input);
setResult(RESULT_OK, returnIntent);
finish();
}
}
return true;
}
});
/*
Intent returnIntent = getIntent();
returnIntent.putExtra("returnData", decimal_input);
setResult(RESULT_OK, returnIntent);
finish();
*/
}
}
I hope that this helps you out a bit.
David.

in app purchase saving buttons states

I am trying to develop an app with in app purchases in it, simply what I want to do is to have two buttons one to make the purchase(enabled) the second button to open the activity after purchase (at first is disabled then after purchase is enabled).
Two problems the first was to save the buttons state after the purchase as they were getting reset every time I restart the app. So I did some researches and found about shared preference and I did implemented it but the second problem came out that buttons statuses doesn’t seem to work right (between disabled to enabled) after implementing shared preference.
Note that in the app I have two buttons that do the same thing one enables the other buttons but with no purchase made and they work fine with shared preference, but the buttons associated with the in app purchase stopped changing their status from disabled to enabled after the purchase is made (they stay disabled after the purchase)
Here is my xml code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainScreen">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity 1"
android:id="#+id/act1"
android:onClick="Activity1"
android:layout_marginTop="84dp"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/buyall"
android:layout_toStartOf="#+id/buyall"
android:enabled="false" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Buy Act 1"
android:id="#+id/buyButton"
android:onClick="buyClick"
android:layout_alignTop="#+id/act1"
android:layout_toRightOf="#+id/act1"
android:layout_toEndOf="#+id/act1"
android:layout_marginLeft="45dp"
android:layout_marginStart="45dp"
android:enabled="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity 2"
android:id="#+id/act2"
android:layout_below="#+id/act1"
android:layout_alignLeft="#+id/act1"
android:layout_alignStart="#+id/act1"
android:onClick="Activity2"
android:enabled="false" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Buy act 2"
android:id="#+id/buyact2"
android:layout_alignBottom="#+id/act2"
android:layout_alignLeft="#+id/buyButton"
android:layout_alignStart="#+id/buyButton"
android:onClick="buyAct2"
android:enabled="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity 3"
android:id="#+id/act3"
android:layout_below="#+id/act2"
android:layout_alignLeft="#+id/act2"
android:layout_alignStart="#+id/act2"
android:onClick="Activity3"
android:enabled="false" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Buy act 3"
android:id="#+id/buyact3"
android:layout_alignBottom="#+id/act3"
android:layout_alignLeft="#+id/buyact2"
android:layout_alignStart="#+id/buyact2"
android:onClick="buyAct3"
android:enabled="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Buy all"
android:id="#+id/buyall"
android:onClick="buyAll"
android:enabled="true"
android:layout_below="#+id/eact4"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ACT 4"
android:id="#+id/act4"
android:onClick="ACT4"
android:layout_below="#+id/act3"
android:layout_alignLeft="#+id/act3"
android:layout_alignStart="#+id/act3"
android:enabled="false" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enable ACT 4"
android:id="#+id/eact4"
android:onClick="EACT4"
android:layout_below="#+id/buyact3"
android:layout_alignLeft="#+id/buyact3"
android:layout_alignStart="#+id/buyact3"
android:enabled="true" />
And that’s my java code:
package com.aseng90_test.smiap2;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.aseng90_test.smiap2.util.IabHelper;
import com.aseng90_test.smiap2.util.IabResult;
import com.aseng90_test.smiap2.util.Purchase;
public class MainScreen extends ActionBarActivity {
private static final String TAG = "com.aseng90_test.smiap2";
IabHelper mHelper;
private static final String ITEM_SKU = "com.aseng90_test.smiap2_button555";
private static final String ITEM_SKU2 = "com.aseng90_test.smiap2_buyact222";
private static final String ITEM_SKU3 = "com.aseng90_test.smiap2_buyact333";
private static final String ITEM_SKU4 = "com.aseng90_test.smiap2_buyall_11";
private Button Activity1;
private Button Activity2;
private Button Activity3;
private Button buyButton;
private Button buyAct2;
private Button buyAct3;
private Button buyAll;
private Button EAct4;
private Button Act4;
private SharedPreferences prefs;
private String prefName = "MyPref";
boolean Activity1_isEnabled;
boolean Activity2_isEnabled;
boolean Activity3_isEnabled;
boolean Act4_isEnabled;
boolean buyButton_isEnabled;
boolean buyAct2_isEnabled;
boolean buyAct3_isEnabled;
boolean buyAll_isEnabled;
boolean EAct4_isEnabled;
private static final String Activity1_state = "Activity1_state";
private static final String Activity2_State = "Activity2_state";
private static final String Activity3_State = "Activity3_state";
private static final String buyButton_State = "buyButton_state";
private static final String buyAct2_State = "buyAct2_state";
private static final String buyAct3_State = "buyAct3_state";
private static final String buyAll_State = "buyAll_state";
private static final String Act4_State = "Act4_state";
private static final String EAct4_State = "EAct4_state";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
buyButton = (Button) findViewById(R.id.buyButton);
buyAct2 = (Button) findViewById(R.id.buyact2);
buyAct3 = (Button) findViewById(R.id.buyact3);
buyAll = (Button) findViewById(R.id.buyall);
Activity1 = (Button) findViewById(R.id.act1);
Activity2 = (Button) findViewById(R.id.act2);
Activity3 = (Button) findViewById(R.id.act3);
EAct4 = (Button) findViewById(R.id.eact4);
Act4 = (Button) findViewById(R.id.act4);
String base64EncodedPublicKey =
"";
mHelper = new IabHelper(this, base64EncodedPublicKey);
mHelper.startSetup(new
IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
if (!result.isSuccess()) {
Log.d(TAG, "In-app Billing setup failed: " + result);
} else {
Log.d(TAG, "In-app Billing is set up OK");
}
}
});
}
public void EACT4(View view) {
EAct4.setEnabled(false);
Act4.setEnabled(true);
}
public void ACT4(View view) {
Toast.makeText(MainScreen.this,
"ACt4 Clicked", Toast.LENGTH_LONG).show();
}
public void buyClick(View view) {
mHelper.launchPurchaseFlow(this, ITEM_SKU, 10001,
mPurchaseFinishedListener, "mypurchasetoken");
}
public void buyAct2(View view) {
mHelper.launchPurchaseFlow(this, ITEM_SKU2, 10002, mPurchaseFinishedListener, "buyact2");
}
public void buyAct3(View view) {
mHelper.launchPurchaseFlow(this, ITEM_SKU3, 10003, mPurchaseFinishedListener, "buyact3");
}
public void buyAll(View view) {
mHelper.launchPurchaseFlow(this, ITEM_SKU4, 10004, mPurchaseFinishedListener, "buyall");
}
#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 (purchase.getSku().equals(ITEM_SKU)) {
Activity1.setEnabled(true);
buyButton.setEnabled(false);
}
if (purchase.getSku().equals(ITEM_SKU2)) {
Activity2.setEnabled(true);
buyAct2.setEnabled(false);
}
if (purchase.getSku().equals(ITEM_SKU3)) {
Activity3.setEnabled(true);
buyAct3.setEnabled(false);
}
if (purchase.getSku().equals(ITEM_SKU4)) {
Activity1.setEnabled(true);
Activity2.setEnabled(true);
Activity3.setEnabled(true);
buyAll.setEnabled(false);
buyButton.setEnabled(false);
buyAct2.setEnabled(false);
buyAct3.setEnabled(false);
}
}
};
public void Activity1(View view) {
startActivity(new Intent(MainScreen.this, Click1.class));
}
public void Activity2(View view) {
startActivity(new Intent(MainScreen.this, Activity2.class));
}
public void Activity3(View view) {
startActivity(new Intent(MainScreen.this, Activity3.class));
}
#Override
public void onDestroy() {
super.onDestroy();
if (mHelper != null) mHelper.dispose();
mHelper = null;
}
#Override
protected void onPause(){
super.onPause();
if (Act4.isEnabled()){
Act4_isEnabled = true;
}
else {
Act4_isEnabled = false;
}
if (Activity1.isEnabled()){
Activity1_isEnabled = true;
}
else {
Activity1_isEnabled = false;
}
if (Activity2.isEnabled()){
Activity2_isEnabled = true;
}
else {
Activity2_isEnabled = false;
}
if (Activity3.isEnabled()){
Activity3_isEnabled = true;
}
else {
Activity3_isEnabled = false;
}
if (buyButton.isEnabled()){
buyButton_isEnabled = true;
}
else {
buyButton_isEnabled = false;
}
if (buyAct2.isEnabled()){
buyAct2_isEnabled = true;
}
else {
buyAct2_isEnabled = false;
}
if (buyAct3.isEnabled()){
buyAct3_isEnabled = true;
}
else {
buyAct3_isEnabled = false;
}
if (buyAll.isEnabled()){
buyAll_isEnabled = true;
}
else {
buyAll_isEnabled = false;
}
prefs = getSharedPreferences(prefName,MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(Activity1_state,this.getLocalClassName());
editor.putBoolean(Act4_State,Act4_isEnabled);
editor.putBoolean(EAct4_State,EAct4_isEnabled);
editor.putBoolean(Activity1_state,Activity1_isEnabled);
editor.putBoolean(Activity2_State,Activity2_isEnabled);
editor.putBoolean(Activity3_State,Activity3_isEnabled);
editor.putBoolean(buyButton_State,buyButton_isEnabled);
editor.putBoolean(buyAct2_State,buyAct2_isEnabled);
editor.putBoolean(buyAct3_State,buyAct3_isEnabled);
editor.putBoolean(buyAll_State,buyAll_isEnabled);
editor.apply();
}
#Override
protected void onResume(){
super.onResume();
prefs = getSharedPreferences(prefName,MODE_PRIVATE);
Act4.setEnabled(prefs.getBoolean(Act4_State,false));
Activity1.setEnabled(prefs.getBoolean(Activity1_state,false));
Activity2.setEnabled(prefs.getBoolean(Activity2_State,false));
Activity3.setEnabled(prefs.getBoolean(Activity3_State,false));
EAct4.setEnabled(prefs.getBoolean(EAct4_State,true));
buyButton.setEnabled(prefs.getBoolean(buyButton_State,true));
buyAct2.setEnabled(prefs.getBoolean(buyAct2_State,true));
buyAct3.setEnabled(prefs.getBoolean(buyAct3_State,true));
buyAll.setEnabled(prefs.getBoolean(buyAll_State,true));
}
So Any suggestions if I have something wrong in my code?
Thanks a lot.
Try to call methods from Java part , don't call from xml using android:onClick
Use default value of the button(buy) state to false in shared preference .
and in this screen implement this if check inside oncreate() method as:
if(button(buy) state ==false)
{
//make button(buy) state enable
//make activity button state disable
}
else
{
//make button(buy) state disable
//make activity button state enable
}
And make button(buy) and activity calling button state to true/false according to result after in app purchase and also update shared prefrence state according to result

Android: Data obtained from JSON not appearing complete in textview

In my app, I am getting text content from JSON and that content I am showing into text view. But, problem is text is not appearing complete and it is not formatted as well. I had checked my JSON using http://jsonformatter.curiousconcept.com/ and it showed the JSON is valid. I had printed the content that I received on the log and it is complete. Even, after setting it to textview and again getting back from it, I am getting complete data. But, it is not displaying complete text.
I am not getting where the problem is. The textview is inside scrollview.
Below is my code:
Base Activity
public class TIEBaseActivity extends MapActivity
{
//private ProgressDialog dialog;
public AlertDialog _alertDialog;
protected HeaderBar _headerBar;
protected FooterBar _footerBar;
protected LinearLayout _manager;
protected LinearLayout form;
protected TIEBaseActivity _self;
public void createDefaultView(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.basescreen);
this._self=this;
initView();
}
public void loadFormFromResource(int resourceID)
{
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(resourceID, null);
_manager.addView(view);
}
public void loadDefaultForm()
{
form=new LinearLayout(this);
form.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
form.setOrientation(LinearLayout.VERTICAL);
form.setGravity(Gravity.CENTER);
_manager.addView(form);
}
public void initView()
{
_headerBar = (HeaderBar) findViewById(R.id.baseHeaderBar);
_manager = (LinearLayout) findViewById(R.id.baseScrollContent);
//_footerBar = (FooterBar) findViewById(R.id.baseFooterBar);
_headerBar.view.setVisibility(View.GONE);
//_footerBar.view.setVisibility(View.GONE);
}
protected void showScreen(Intent intent) {
startActivity(intent);
}
public void setHeaderTitle(String title) {
if (_headerBar!=null) {
_headerBar.setTitle(title);
}
}
public Handler progressCloseHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (_alertDialog != null)
_alertDialog.cancel();
}
};
private Handler alertViewHandler = new Handler() {
public void handleMessage(Message msg) {
String message=(String)msg.obj;
AlertDialog.Builder _alert = new AlertDialog.Builder(TIEBaseActivity.this);
_alert.setMessage(message)
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
}
});
_alert.create().show();
}
};
public void DisplayAlert(String message) {
Message msg=Message.obtain(alertViewHandler);
msg.obj=message;
alertViewHandler.sendMessage(msg);
}
public void DisplayAlert(String message, int id) {
Message msg=Message.obtain(alertViewHandler);
msg.obj=message;
msg.what=id;
alertViewHandler.sendMessage(msg);
}
private Handler closeViewHandler=new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
_self.finish();
}
};
public void closeScreen() {
closeViewHandler.sendMessage(Message.obtain(closeViewHandler));
}
public void openRating()
{
Intent marketIntent = new Intent(Intent.ACTION_VIEW,Uri.parse("market://details?id=com.dzo.tie"));
startActivity(marketIntent);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
public void openShare()
{
String mMailSubject = "OIE App. - Get the All Indian Events happening in Overseas";
String mMailMessage = null;
mMailMessage = "Hi,\n I found this great Application. This application customize for Overseas Indian Events.";
mMailMessage += "\n";
mMailMessage += "Go to: https://market.android.com/details?id=com.dzo.oie";
mMailMessage += ",\n Please visit: http://www.dotzoo.net to see more about Dotzoo Inc.";
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("text/*");
emailIntent.putExtra(Intent.EXTRA_SUBJECT, ""+mMailSubject);
emailIntent.putExtra(Intent.EXTRA_TEXT, mMailMessage);
startActivity(Intent.createChooser(emailIntent, "Share via..."));
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
Layout for BaseActivity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:background="#color/white"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="#+id/baseLayout">
<com.dzo.tie.ui.HeaderBar
android:id="#+id/baseHeaderBar"
android:layout_width="fill_parent"
android:layout_height="50dp"/>
<ScrollView
android:scrollbars="vertical"
android:fillViewport="true"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:id="#+id/baseScrollContent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center"
android:layout_gravity="center"
android:layout_width="fill_parent">
</LinearLayout>
</ScrollView>
I am extending this base activity in my activity class:
My Activity
public class TIEInfo extends TIEBaseActivity
{
TextView txtTieInfo;
String contents;
private String infoUrl = "http://www.tradeineu.com/tie_app/aboutTie.php";
protected void onCreate(Bundle savedInstanceState)
{
super.createDefaultView(savedInstanceState);
_headerBar.view.setVisibility(View.VISIBLE);
super.setHeaderTitle("Info");
init();
new TIEInfoAsyncTask(getParent(), infoUrl, txtTieInfo).execute();
}//onCreate
public void init()
{
loadFormFromResource(R.layout.tieinfo);
txtTieInfo = (TextView)findViewById(R.id.txtTieInfo);
}//init
}//TIEInfo
Layout for my activity
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/txtTieInfo"
android:textSize="12sp"
android:textColor="#color/copper_gold"
android:lineSpacingExtra="5dp"/>
You need to scroll to see the rest of your text.
Place your textview inside a scrollView and it will be ok.

Categories

Resources