Make app more effecient by eliminating extra codes - java

I currently have the following code which starts from A all the way to Z :
if (someId.matches("A") || someId.matches("a")) {
tvLetCap.setText("A");
tvLetLow.setText("a");
ivLetterIcon.setImageResource(R.drawable.apple);
btnDisplayWord.setText("A is for APPLE");
btnPlay.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
stopPlaying();
mpSound = MediaPlayer.create(MyClass.this, R.raw.a);
mpSound.setLooping(false);
mpSound.start();
btnPlay.setVisibility(View.GONE);
btnStop.setVisibility(View.VISIBLE);
btnStop.setOnClickListener(stopSound);
mpSound.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
btnPlay.setVisibility(View.VISIBLE);
btnStop.setVisibility(View.GONE);
}
});
}
});
}
if (someId.matches("B") || someId.matches("b")) {
tvLetCap.setText("B");
tvLetLow.setText("b");
ivLetterIcon.setImageResource(R.drawable.ball);
btnDisplayWord.setText("B is for BALL");
btnPlay.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
stopPlaying();
mpSound = MediaPlayer.create(MyClass.this, R.raw.b);
mpSound.setLooping(false);
mpSound.start();
btnPlay.setVisibility(View.GONE);
btnStop.setVisibility(View.VISIBLE);
btnStop.setOnClickListener(stopSound);
mpSound.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
btnPlay.setVisibility(View.VISIBLE);
btnStop.setVisibility(View.GONE);
}
});
}
});
}
Would this work as oppose to the above:
switch(someId) {
case A:
setLetter("A");
addIcon("apple");
break;
case B:
setLetter("B");
addIcon("ball");
break;
default:
break;
}
public void setLetter(String strLetter) {
tvLetCap.setText(strLetter);
tvLetLow.setText(strLetter.toLowerCase());
}
public void addIcon(String iconLetter) {
ivLetterIcon.setImageResource(R.drawable. + iconLetter);
btnDisplayWord.setText(iconLetter.charAt(0).toUpperCase() + " is for " + iconLetter.toUpperCase());
}
I am guessing the only issue might be with this line and how would I fix it?:
ivLetterIcon.setImageResource(R.drawable. + iconLetter);
Also will it be possible to take the entire btnPlay function to a different function and just pass the letter like I did with the other functions so it's not repeated over?

I don't know what R and R.drawable are; and what are R.drawable.apple, R.drawable.ball, etc.? Assuming those all have the same type, you might want to make R.drawable an array where the index is 0 for 'A', 1 for 'B', etc., and initialize it so that R.drawable[0] = (whatever the "apple" is supposed to be), R.drawable[1] = (same for "ball"); then use something like
R.drawable[someId.charAt(0).toUpperCase() - 'A']
and similarly for R.raw. Then you wouldn't need a switch at all.
EDIT by kcoppock:
For example:
int[] icons = {
R.drawable.a,
R.drawable.b,
//etc.
};
int[] sounds = {
R.raw.a,
R.raw.b,
//etc.
}
and use icons[index] and sounds[index] to map your values.

Simplest solution: add another parameter to addIcon:
public void addIcon(String iconLetter, int iconResource){
ivLetterIcon.setImageResource(iconResource);
btnDisplayWord.setText(iconLetter.charAt(0).toUpperCase() + " is for " + iconLetter.toUpperCase());
}
Then call it with
setIcon("apple", R.drawable.apple);
As far as reusing the on click listener, it's certainly possible. You could have a single onClick listener that's listening to all the views. When a view is clicked, it's passed in as the argument to the onClick(View view) method. You can use that to find the start/stop button for that view and do whatever to them. Also, there's a useful (and often abused) method pair: setTag(Object object), and getTag(). You might want to look into using those to store the resource ID for the raw audio file you want to play when a button is clicked.

Related

Setting Listeners programmatically to an array of CheckBoxes

So far, I've encountered the issue "variable x is accessed within inner class,needs to be declared final. I am able to initialize the CheckBox's but I am unable to set a listener to them after initialization in the loop. Below is my code so far.
for(int i=0;i<checkBox_fiber_ID.length;i++){
int temp=getResources().getIdentifier(checkBox_fiber_ID[i],"id",getPackageName());
checkBoxes_fiber[i]=findViewById(temp);
checkBoxes_fiber[i].setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if(checkBoxes_fiber[i].isChecked()){
//do something
}
}
});
}
Any tips on how to solve this?
Take final String[] x={"defaultvalue Emptry"}
Then after inside onclick Listener set value of x using below code.
x[0]="new value"
and use this value in different function.
as per your code it look likes blow:
final String x[] ={""}
for(int i=0;i<checkBox_fiber_ID.length;i++){
int temp=getResources().getIdentifier(checkBox_fiber_ID[i],"id",getPackageName());
checkBoxes_fiber[i]=findViewById(temp);
checkBoxes_fiber[i].setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
if(checkBoxes_fiber[i].isChecked()){
x[0]=checkBoxes_fiber[i].getvalue==> value name
}
}
});
}
Outside function get value of x using
String name=x[0]
You can try to create separate class of listener
private View.OnClickListener mCheckboxListener = new View.OnClickListener() {
public void onClick(View v) {
if(((CheckBox)view).isChecked())
{
int checkBoxId = (int)v.getTag(); //You can get Id for specific checkbox
//do other stuff with checkBoxId
}
}
};
And set Id to each checkbox like
for(int i=0;i<checkBox_fiber_ID.length;i++){
int temp=getResources().getIdentifier(checkBox_fiber_ID[i],"id",getPackageName());
checkBoxes_fiber[i]=findViewById(temp);
checkBoxes.setTag(i); //set check box id as tag for later usage
checkBoxes_fiber[i].setOnClickListener(mCheckboxListener);
}
I guess you are trying to do something base on the checkbox IDs. You can set a tag for a checkBox and get back the tag in future. Also, the view object in method void onClick(View view) is now an CheckBox. Just change a little in your code:
for(int i=0;i<checkBox_fiber_ID.length;i++){
int temp=getResources().getIdentifier(checkBox_fiber_ID[i],"id",getPackageName());
checkBoxes_fiber[i]=findViewById(temp);
checkBoxes_fiber[i].setTag(i); //mark the check box id for later usage
checkBoxes_fiber[i].setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
if(((CheckBox)view).isChecked()){
int checkBoxId = (int)view.getTag();
doSomething(checkBoxId);
}
}
});
}
}
And write a new method for business code:
public void doSomething(int no){
if(no==1){
//do something
}
else if(no==2){
//do something
}
//...
}

Android : how to use single button for multiple task

I have 1 button in activity. i want to use this 1 button for multiple task.
So how can i do ?
If i pressed 1st time this button then it's change 2 button
if i pressed 2nd time then it's update my data
but it's only work 1st time 2nd time it's not work
see my code what i tried
Intent extras = getIntent();
{
if (extras.hasExtra("edit")) {
if (extras.getStringExtra("edit").equals("home")) {
etCompanyName.setEnabled(false);
etWebsite.setEnabled(false);
etEmail.setEnabled(false);
etPhoneHome.setEnabled(false);
etPhonePrimary.setEnabled(false);
etAddressLine1.setEnabled(false);
etAddressLine2.setEnabled(false);
etCity.setEnabled(false);
spStates.setEnabled(false);
etZip.setEnabled(false);
spContries.setEnabled(false);
//1st time use hear
txtSave.setText(getResources().getString(R.string.label_edit));
txtClose.setText(getResources().getString(R.string.label_back));
txtSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtSave.setText(getResources().getString(R.string.label_add));
txtClose.setText(getResources().getString(R.string.label_cancel));
etCompanyName.setEnabled(true);
etWebsite.setEnabled(true);
etEmail.setEnabled(true);
etPhoneHome.setEnabled(true);
etPhonePrimary.setEnabled(true);
etAddressLine1.setEnabled(true);
etAddressLine2.setEnabled(true);
etCity.setEnabled(true);
spStates.setEnabled(true);
etZip.setEnabled(true);
spContries.setEnabled(true);
}
});
if (extras != null) {
Company value = (Company) extras.getSerializableExtra("company");
etCompanyName.setText(value.getName());
etWebsite.setText(value.getWebsite());
etEmail.setText(value.getEmail());
etPhoneHome.setText(value.getPhoneHome());
etPhonePrimary.setText(value.getPhonePrimary());
etAddressLine1.setText(value.getAddressLine1());
etAddressLine2.setText(value.getAddressLine2());
etCity.setText(value.getCity());
etZip.setText(value.getZipcode());
}
} else {
//2nd time use hear
txtSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Company company = new Company();
company.setName(etCompanyName.getText().toString().trim());
company.setWebsite(etWebsite.getText().toString().trim());
company.setEmail(etEmail.getText().toString().trim());
company.setPhoneHome(etPhoneHome.getText().toString().trim());
company.setPhonePrimary(etPhonePrimary.getText().toString().trim());
company.setAddressLine1(etAddressLine1.getText().toString().trim());
company.setAddressLine2(etAddressLine2.getText().toString().trim());
company.setZipcode(etZip.getText().toString().trim());
company.setCity(etCity.getText().toString().trim());
company.setState(spStates.getSelectedItem().toString());
company.setCountry(spContries.getSelectedItem().toString());
company.setDate(Util.getInstance(AddCompanyActivity.this).getCurrentDate());
long isUpdated = myDb.updateCompany(company);
if (isUpdated != -1) {
Toast.makeText(getApplicationContext(), "Company Update Successfully: " + isUpdated, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Something wrong", Toast.LENGTH_SHORT).show();
}
finish();
}
});
}
}
}
You can see my above code i can used txtSave button for perform 2 task but it's only change two buttons and i'll change data and click on button then it's can't perform
Try this way, first declare global variable on your activity class file like below :
int count = 0;
After that add your click listener like that:
yourButton.setOnClickListener(v -> {
if (count == 0) { // the first click
count++;
// do your stuff
}else { // the second click
count = 0; // initialize the count to limit the button click just for the first and the second time only
// do your stuff
}
});
You should not create multiple OnClickListener for Button , Create only 1 and use it
example:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(btn.getText().equals("1")){
//perform action for 1
btn.setText("2");
//change button1 to button2
}else if(btn.getText().equals("2")){
//perform action for 2
btn.setText("3");
}
}
});
you could use single onclicklistener with switch case
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
swtich(extras.getStringExtra().toLowerCase(){
case "1":
// do something
break;
case "2":
// do something else
break;
}
});
}

How to start and stop 2 or more progressbar?

Hello stackoverflow citizen!
I want start and stop 2 progressBars on 1 activity.
I think oll progressBars must start in new thread and join with others.
For 1 progressBar i am write this code.
startBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
handler.post(runnable);
}
});
stopBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
handler.removeCallbacks(runnable);
}
});
}
int prolength=0;
Runnable runnable=new Runnable() {
#Override
public void run() {
prolength = inProgressBar.getProgress() + 1;
inProgressBar.setProgress(prolength);
timeTextView.setText(String.valueOf(prolength));
if (prolength < 100) {
handler.postDelayed(runnable, 1000);
}
else {
inProgressBar.setProgress(0);
timeTextView.setText(String.valueOf(0));
handler.post(runnable);
}
}
};
Thank you advance for help!
I suggest you to use sendMessage Api instead of post Api.
You can pass some information using Message object in your case (contentProgressBar1 or 2 or3 view) and refactor you implementation to this design..
Make sure to cleanup handler in activity life cycle else you will introduce memory leak and unwanted bugs.

ANDROID JAVA - Define all id's at once. (+create easy buttons)

I am new to programming in Java, i've managed to create a little calculator as a little test app.
But i think i am using way to much code for my needs.
So i've given a Button a name: buttonname
Now to change it's text when clicked i need to:
public class MyActivity extends Activity {
Button buttonname;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
buttomname = (Buttom) findViewById(R.id.buttomname);
}
public void buttonnameOnClick(View v) {
button1.setText ("NewText")
}
}
(i've bolted everything i had to add)
So i had to do everything above + connect the buttonClick through the xml file.
So i was wondering if there is a easier way to define all objects so i dont have to do: Button buttonname; and buttomname = (Buttom) findViewById(R.id.buttomname); all the time.
And i was wondering if there is a easier way to auto create button events.
(I am used to Visual Studio, but now i am kinda lost in Android Studio. So on Visual Studio i just had to double click the button and type: buttonname.Text = "NewText";)
There is a library called Butter Knife to do approximately that
However, I'm not sure if you really need it.
Oh, and you don't have to find the same Button every time. You find it once in onCreate and store in a field.
First of all you have typo in
buttomname = (Buttom) findViewById(R.id.buttomname);
It should be
buttomname = (Button) findViewById(R.id.buttomname);
and you forgot ; in one line "didn't your IDE show error to you!!" and also small correction in
public void buttonnameOnClick(View v) {
button1.setText ("NewText")
}
it should be
buttomname.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
buttomname.setText ("NewText");
}
});
inside protected void onCreate.
2nd method:
And if you have define android:onclick="buttonnameOnClick" in XML then
public void buttonnameOnClick(View v) {
button1.setText ("NewText")
}
To be corrected to
public void buttonnameOnClick(View v) {
buttomname.setText ("NewText");
}
You can do it in a loop if you have a lot of identical buttons to process
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
for (int btn_id : new int[]{
R.id.buttomname
, R.id.buttomname2
, R.id.buttomname3
}) {
View v = view.findViewById(btn_id);
if (v != null) {
v.setOnClickListener(onClickButton);
}
}
}
//
private View.OnClickListener onClickButton = new View.OnClickListener() {
#Override
public void onClick(View view) {
// .. handle click
if (view.getId()==R.id.buttomname2){
}
}
Your code is partly correct,
however the
(Buttom) is wrong change it to (Button)
the other thing
public void buttonnameOnClick(View v) {
button1.setText ("NewText")
}
can just be changed to:
public void buttonnameOnClick(View v) {
Button buttonTemp = (Button)v;
buttonTemp.setText ("NewText");
}
Assuming you are calling the method from layout xml file.
you must use the onClickListener() method for Button object.
Your code like this structure;
buttonname = (Button)findViewById(R.id.buttonname);
buttonname.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
I recommend to your visit Button | Android Dev page for Button.

Nested onClick Listener

I have some codes that I need help with. My plan for this code is simple. I have 3 buttons which are the yellowBar, greenBar and redBar. I also have 3 images that is colored yellow, green and red. What I wanted to do is when I start my app, the images I have will randomly pop out and whichever color comes out, I should be able to click the button with the corresponding color. I also have a time, so basically I want to click correctly as much as possible, but my code only runs it one time. my time continues to go down but this code only runs one time. How can I fix this so that it will continue to pop random color images until the time runs out?
while(gameTime > 0){
colorNum = new Random();
colorNumber = colorNum.nextInt(2);
switch (colorNumber){
case 0: colors.setDisplayedChild(0);
break;
case 1: colors.setDisplayedChild(1);
break;
case 2: colors.setDisplayedChild(2);
break;
}
colors.setVisibility(View.VISIBLE);
yellowBar.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if(colorNumber == 0){
points ++;
score.setText(String.valueOf(points));
}
}
});
greenBar.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if(colorNumber == 1){
points ++;
score.setText(String.valueOf(points));
}
}
});
redBar.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if(colorNumber == 2){
points++;
score.setText(String.valueOf(points));
}
}
});
}
The better solution would be to render your graphics onClick event.
When you press a button, you check if the answer was right, then you render the graphics.
using while loop like you do it now is wrong, since your graphics will be rendered all the time (whether button is pressed or not)
Basically (this is not a solution, rather a guideline based on your code):
public void initialize(){
yellowBar.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if(colorNumber == 0){
points ++;
score.setText(String.valueOf(points));
updateColors();
}
}
});
greenBar.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if(colorNumber == 1){
points ++;
score.setText(String.valueOf(points));
updateColors();
}
}
});
redBar.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if(colorNumber == 2){
points++;
score.setText(String.valueOf(points));
updateColors();
}
}
});
}
}
public void updateColors(){
colorNum = new Random();
colorNumber = colorNum.nextInt(2);
switch (colorNumber){
case 0: colors.setDisplayedChild(0);
break;
case 1: colors.setDisplayedChild(1);
break;
case 2: colors.setDisplayedChild(2);
break;
}
colors.setVisibility(View.VISIBLE);
}

Categories