How can I DRY my code in the context below(android) - java

I am new to android development and using shared preferences to show ads after a number of buttons clicks. I have several buttons(Like the example below) each with a different intent. What would be the best implementation for my single logic below so that my code is DRY(Don't Repeat Yourself) for all other buttons with different intent.
My Adapter class extends RecyclerView
public class ImageAdaptor extends RecyclerView.Adapter<ImageAdaptor.MyViewHolder> {
#####################################
######################################
########################################
public class MyViewHolder extends RecyclerView.ViewHolder {
public MyViewHolder(View v) {
MobileAds.initialize(acontext, "ca-app-pub-3940256099942544~3347511713");
final InterstitialAd mInterstitialAd = new InterstitialAd(acontext);
mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
//Here is my working example on first button
//I want to achieve something like this on other clicks with different intents
//I don't want to repeat the logic over and over again
**Button1**.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final ModelStatus modelStatus = arrayList.get(getAdapterPosition());
final Intent intent = new Intent(acontext, Activity1.class);
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
acontext.startActivity(intent);
}
});
SharedPreferences preferences = acontext.getSharedPreferences("PREFRENCE",
Context.MODE_PRIVATE);
int clickCount = preferences.getInt("KEY_CLICK_COUNT", 1);
if (clickCount % 6 == 0) {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
acontext.startActivity(intent);
};
}else {
acontext.startActivity(intent);
}
clickCount++;
preferences.edit().putInt("KEY_CLICK_COUNT", clickCount).apply();
}
});
**Button2**.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Intent intent = new Intent(acontext, Activity2.class);
//Some code with an intent
// I want my logic to go in here for 5 clicks per ad.
// I don't want to repeat myself since i have several such
//buttons with a different intent
}
});
}
}

As easy as pie
public void handleClick(Class destination, int buttonType){
final ModelStatus modelStatus = arrayList.get(getAdapterPosition());
final Intent intent = new Intent(getAppContext(), destination);
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
acontext.startActivity(intent);
}
});
SharedPreferences preferences = acontext.getSharedPreferences("PREFRENCE",
Context.MODE_PRIVATE);
int clickCount = preferences.getInt("KEY_CLICK_COUNT"+buttonType, 1);
if (clickCount % 6 == 0) {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
acontext.startActivity(intent);
};
}else {
acontext.startActivity(intent);
}
clickCount++;
preferences.edit().putInt("KEY_CLICK_COUNT"+buttonType, clickCount).apply();
}
Button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handleClick(Activity1.class, 1);
}
Button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handleClick(Whatever.class, 2);
}

Related

Click Listeners to RecyclerView [duplicate]

This question already has answers here:
RecyclerView: how to catch the onClick on an ImageView?
(2 answers)
Closed 4 years ago.
What I am trying to accomplish is to create a listener for the ImageView inside the row of RecyclerView.
This code is working already, but this is not the solution that I wanted to have, because you need to double click the ImageView before getting the desired result.
// row click listener
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, final int position) {
ImageView viewContent = (ImageView)view.findViewById(R.id.btnViewContent);
ImageView deleteContent = (ImageView)view.findViewById(R.id.btnDeleteContent);
viewContent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "VIEW CONTENT", Toast.LENGTH_SHORT).show();
}
});
deleteContent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "DELETE CONTENT", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onLongClick(View view, int position) {}
}));
Any idea how to translate this into single click solution? Advice or even a single comment would help me a lot.
This is not the right way as one of our friend suggested onBindViewHolder is caleed again and again during scrolling so it is not the best practice to add listener there.
Best way is to add it on ViewHolder as I suggested. Check my answer above.
Add your imageView click listener in OnBindViewHolder method
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, int position) {
holder.btnClassAddCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do what you want here
}
});
}
Then there is no need to implement recyclerView.addOnItemTouchListener , inside Viewholder just add clicklistener on the view(image) you want below is the example for reference.
` public static class HeaderViewHolder extends RootViewHolder {
#BindView(R.id.cardview)
CardView cardview;
#BindView(R.id.main_container)
LinearLayout main_container;
#BindView(R.id.music_cardview)
CardView music;
#BindView(R.id.shabad_cardview)
CardView shabadvaani;
#BindView(R.id.news_cardview)
CardView news;
#BindView(R.id.donate_cardview)
CardView donate;
#BindView(R.id.bs_cardview)
CardView bs;
#BindView(R.id.bl_cardview)
CardView bl;
#BindView(R.id.bng_cardview)
CardView bng;
#BindView(R.id.more_cardview)
CardView more;
#BindView(R.id.vid_cardview)
CardView vid;
#BindView(R.id.medi_cardview)
CardView medi;
//
// #BindView(R.id.ama_cardview)
// CardView ama;
public HeaderViewHolder(final View itemView,final OnItemClickListener mOnItemClickListener) {
super(itemView);
ButterKnife.bind(this, itemView);
news.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mOnItemClickListener != null) {
mOnItemClickListener.openDrawer();
}
//Intent i= new Intent(ctx,);
//open drawer code
}
});
shabadvaani.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ctx, IndexActivity.class);
ctx.startActivity(i);
}
});
music.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ctx, MainActivity.class);
i.putExtra("slug","audiobhajan");
ctx.startActivity(i);
//open drawer code
}
});
more.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Intent i = new Intent(ctx, stayrocks.jambh.vani.auth.MainActivity.class);
// ctx.startActivity(i);
if (mOnItemClickListener != null) {
mOnItemClickListener.openDrawer();
}
//open drawer code
}
});
bs.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent= new Intent(ctx, AmaActivity.class);
ctx.startActivity(intent);
}
});
bl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ctx, ItemListActivity.class);
ctx.startActivity(i);
//open drawer code
}
});
bng.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// String appPackage = "com.my.bishnoi.nextgen";
// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackage));
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Intent intent= new Intent(ctx, WallpaperActivity.class);
ctx.startActivity(intent);
//open drawer code
}
});
medi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// String appPackage = "com.my.bishnoi.nextgen";
// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackage));
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Intent intent= new Intent(ctx, stayrocks.jambh.vani.activities.jyot.MainActivity.class);
ctx.startActivity(intent);
//open drawer code
}
});
vid.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// String appPackage = "com.my.bishnoi.nextgen";
// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackage));
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Intent intent= new Intent(ctx, VideoListDemoActivity.class);
ctx.startActivity(intent);
//open drawer code
}
});
// ama.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
//// String appPackage = "com.my.bishnoi.nextgen";
//// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackage));
//// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Intent intent= new Intent(ctx, AmaActivity.class);
// ctx.startActivity(intent);
// //open drawer code
// }
// });
}
}
`
Add your imageView click listener in OnBindViewHolder method
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, int position) {
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do what you want here
}
});
}

How to use onSetClickListener with Interstitial ads and Intent together?

I'm using a click listener for both interstitial ads and intent to pass control to another activity:
Can anyone modify below code to use it together?
register_button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
}
});
register_button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent register_intent = new Intent(home.this,register.class);
startActivity(register_intent);
}
});
If this:
register_button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
Intent register_intent = new Intent(home.this, register.class);
startActivity(register_intent);
}
});
is not what you want/doesn't work, then your flow is incorrect.

Previous button and next button

I have <> and <> buttons in my quiz app, but if the user is in the first question since there is no previous question there should be toast which says "this is the first question" and the same with <>button.
Here is my code for buttons (which is incorrect):
mNextButton = (Button)findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurreentIndex=0;
if (mCurreentIndex>mQuestionBank.length){
Toast.makeText(QuizActivity.this,R.string.last_question,Toast.LENGTH_LONG).show();
}
updateQuestion();
}
});
mPreviousButton = (Button)findViewById(R.id.previous_button);
mPreviousButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurreentIndex--;
if (mCurreentIndex<mQuestionBank.length){
Toast.makeText(QuizActivity.this, R.string.first_question,Toast.LENGTH_LONG).show();
}
updateQuestion();
}
});
mNextButton = (Button)findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//mCurreentIndex=0;// not valid
if (mCurreentIndex>=mQuestionBank.length){
Toast.makeText(QuizActivity.this,getString(R.string.last_question),Toast.LENGTH_LONG).show();
return;
}
mCurreentIndex++;
updateQuestion();
}
});
mPreviousButton = (Button)findViewById(R.id.previous_button);
mPreviousButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mCurreentIndex<=0){
Toast.makeText(QuizActivity.this, getString(R.string.first_question),Toast.LENGTH_LONG).show();
return;
}
mCurreentIndex--;
updateQuestion();
}
});
Try this
mPreviousButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mCurreentIndex<=0){
Toast.makeText(QuizActivity.this, R.string.first_question,Toast.LENGTH_LONG).show();
}else{
mCurreentIndex--;
updateQuestion();
}
}
});
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mCurreentIndex>=mQuestionBank.length){
Toast.makeText(QuizActivity.this,getString(R.string.last_question),Toast.LENGTH_LONG).show();
}else{
mCurreentIndex++;
updateQuestion();
}
}
});
You have just display toast message but next statement also execute after displaying toast. For your solution you need to use "return" or if..else block.
mNextButton = (Button)findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurreentIndex=0;
if (mCurreentIndex>mQuestionBank.length){
Toast.makeText(QuizActivity.this,R.string.last_question,Toast.LENGTH_LONG).show();
return;
}
updateQuestion();
}
});
mPreviousButton = (Button)findViewById(R.id.previous_button);
mPreviousButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurreentIndex--;
if (mCurreentIndex<mQuestionBank.length){
Toast.makeText(QuizActivity.this, R.string.first_question,Toast.LENGTH_LONG).show();
return;
}
updateQuestion();
}
});
//Previous Button Condition;
mCurreentIndex--;
if (mCurreentIndex<mQuestionBank.length && mCurreentIndex>=0){
Toast.makeText(QuizActivity.this, R.string.first_question,Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(QuizActivity.this, "This is first question",Toast.LENGTH_LONG).show();
mCurreentIndex++;
}
//Next Button Condition;
mCurreentIndex++;
if (mCurreentIndex<mQuestionBank.length){
Toast.makeText(QuizActivity.this,R.string.last_question,Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(QuizActivity.this, "This is last Question",Toast.LENGTH_LONG).show();
mCurreentIndex--;
}
public class QuizActivity extends AppCompatActivity {
private static final String TAG = "QuizActivity";
private static final String KEY_INDEX = "index";
private Button mTrueButton;
private Button mFalseButton;
private Button mNextButton;
private Button mPreviousButton;
private TextView mQuestionTextView;
private Question[] mQuestionBank = new Question[]{
new Question(R.string.question_australia, true),
new Question(R.string.question_oceans, true),
new Question(R.string.question_mideast, false),
new Question(R.string.question_africa, false),
new Question(R.string.question_americas, true),
new Question(R.string.question_asia, true),
};
private int mCurreentIndex = 0;
private boolean[] QuestionsAnswered = new boolean[mQuestionBank.length];
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG,"onCreate(Bundle) called");
setContentView(R.layout.activity_quiz);
if (savedInstanceState != null) {
mCurreentIndex =savedInstanceState.getInt(KEY_INDEX, 0);
QuestionsAnswered = savedInstanceState.getBooleanArray(KEY_INDEX);
}
mQuestionTextView = (TextView)findViewById(R.id.question_text_view);
mTrueButton = (Button)findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(true);
}
});
mFalseButton = (Button)findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkAnswer(false);
}
});
mNextButton = (Button)findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurreentIndex = (mCurreentIndex+mQuestionBank.length +1) % mQuestionBank.length;
updateQuestion();
}
});
mPreviousButton = (Button)findViewById(R.id.previous_button);
mPreviousButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurreentIndex= (mCurreentIndex+ mQuestionBank.length - 1) % mQuestionBank.length;
updateQuestion();
}
});
updateQuestion();
}
#Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart() called");
}
#Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume() called");
}
#Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause() called");
}
#Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt(KEY_INDEX,mCurreentIndex);
savedInstanceState.putBooleanArray(KEY_INDEX,QuestionsAnswered);
}
#Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop() called");
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy() called");
}
private void updateQuestion(){
int question = mQuestionBank[mCurreentIndex].getTextResId();
mQuestionTextView.setText(question);
mTrueButton.setEnabled(!QuestionsAnswered[mCurreentIndex]);
mFalseButton.setEnabled(!QuestionsAnswered[mCurreentIndex]);
}
private void checkAnswer(boolean userPressedTrue) {
boolean answerIsTrue = mQuestionBank[mCurreentIndex].isAnswerTrue();
int messageResId = 0;
if (userPressedTrue == answerIsTrue) {
messageResId = R.string.correct_toast;
} else {
messageResId = R.string.incorrect_toast;
}
Toast.makeText(this, messageResId, Toast.LENGTH_LONG).show();
QuestionsAnswered[mCurreentIndex] = true;
mTrueButton.setEnabled(false);
mFalseButton.setEnabled(false);
}
}

How to start needed Activity, when I saved data in file?

When app starts at first, start Activity with two button: Create File and Settings. Then if I click on button Create File - start Activity where I write text and save in file.
If we have error when file saved - start activity with two button. Else start another Activity with three buttons: Look file, Edit File, Settings.
How organize correct transitions between this Activity and How start activity with three buttons if file already saved?
public class MainFirstActivity extends AppCompatActivity {
private Button createFile;
private Button settings;
private boolean start = true;
private static final String MY_SETTINGS = "my_settings";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_first);
createFile = (Button) findViewById(R.id.create_file);
settings = (Button) findViewById(R.id.settings);
createFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainFirstActivity.this, CreateFileActivity.class);
startActivity(intent);
// MainFirstActivity.this.finish();
}
});
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainFirstActivity.this, SettingActivity.class);
startActivity(intent);
}
});
}
#Override
protected void onResume() {
super.onResume();
File f = new File(CreateFileActivity.FILE_NAME);
if(!f.exists() && !f.isDirectory() && start) {
Intent intent = new Intent(MainFirstActivity.this, MainWithFileActivity.class);
startActivity(intent);
//start=false;
MainFirstActivity.this.finish();
Log.e("err", "intent");
}
}
}
MainWithFileActivity
public class MainWithFileActivity extends AppCompatActivity {
public static final String MY_SETTINGS = "MY_SETTINGS";
private Button lookFile;
private Button editFile;
private Button settings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_if_first);
lookFile = (Button) findViewById(R.id.look_file);
settings = (Button) findViewById(R.id.settings);
editFile = (Button) findViewById(R.id.edit_file);
lookFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainWithFileActivity.this, LookFileActivity.class);
startActivity(intent);
}
});
editFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainWithFileActivity.this,CreateFileActivity.class);
startActivity(intent);
}
});
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainWithFileActivity.this, SettingActivity.class);
startActivity(intent);
}
});
}
}
Simply check if the file exists. If it does not, hide the lookFile button
Add this in your MainWithFileActivity onCreate method
File f = new File(CreateFileActivity.FILE_NAME);
if(!f.exists() && !f.isDirectory()) {
lookFile.setVisibility(View.GONE);
}

How to close popup window?

I have an activity with custom popup window (quickaction style). There are some buttons leading to other activities. I want to close popup after pressing button (about or email button) in this popup (now when I go back popup appears again).
public class FirstActivity extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// some code
Button quickButton = (Button) findViewById(R.id.button_quickaction);
quickButton.setOnClickListener(this);
final ActionItem about = new ActionItem();
final ActionItem email = new ActionItem();
quickButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
QuickAction qa = new QuickAction(v);
qa.addActionItem(about);
qa.addActionItem(email);
qa.setAnimStyle(QuickAction.ANIM_GROW_FROM_RIGHT);
qa.show();
}
});
about.setTitle("About");
about.setIcon(getResources().getDrawable(R.drawable.about));
about.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//some code
}
});
email.setTitle("Email");
email.setIcon(getResources().getDrawable(R.drawable.email));
email.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//some code
}
});
}
}
Please, help.
Added:
I need something like this:
about.setTitle("About");
about.setIcon(getResources().getDrawable(R.drawable.about));
about.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
qa.dismiss();
}
});
But qa cannot be resolved. Even if I add final to QuickAction qa = new QuickAction(v);.
try finish() on button's onClick method.
updated:
QuickAction qa;
quickButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
qa = new QuickAction(v);
qa.addActionItem(about);
qa.addActionItem(email);
qa.setAnimStyle(QuickAction.ANIM_GROW_FROM_RIGHT);
qa.show();
}
});
about.setTitle("About");
about.setIcon(getResources().getDrawable(R.drawable.about));
about.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(qa.isShowing())
qa.dismiss();
//some code
}
});
email.setTitle("Email");
email.setIcon(getResources().getDrawable(R.drawable.email));
email.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(qa.isShowing())
qa.dismiss();
//some code
}
});
you can also put private QuickAction qa; at your activity.

Categories