Android app quitting prematurely - java

I am new to android development using JAVA, and I'm having an issue with a simple app I created. (Please don't laugh at it!)
All it's supposed to do is display a number in an editable textview; The three buttons on this main activity are a +, -, and reset. Super simple, right? I can't tell what I did wrong, but everytime I run the app to test, and then click on any of the buttons, it exits the app and goes back to the android home screen. Not sure what I did wrong... but here's the code I have so far:
public class Main extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn_Plus;
Button btn_Minus;
Button btn_Reset;
final EditText sCount= (EditText) findViewById(R.id.txtCount);;
btn_Plus=(Button)findViewById(R.id.btnPlus);
btn_Minus=(Button)findViewById(R.id.btnMinus);
btn_Reset=(Button)findViewById(R.id.btnReset);
//One way I tried to work it
btn_Plus.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//gets the text in the textview, makes it a string,
//converts it to an int, calculates, then puts it
//back.
String iCounter = sCount.getText().toString();
int iCount = Integer.parseInt(iCounter);
iCount += 1;
Integer.toString(iCount);
sCount.setText(iCount);
}
});
//The second way I tried -- neither way works.
bM.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int iCount = Integer.parseInt(sCount.getText().toString());
iCount -= 1;
if(iCount >0)
iCount = 0;
Integer.toString(iCount);
sCount.setText(iCount);
}
});
bR.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int iCount = 0;
Integer.toString(iCount);
sCount.setText(iCount);
}
});
}
}
Thanks so much!

Use a TextView instead, unless you plan to allow the user to directly enter the number (which it seems like you don't). Rather than do text manipulation to get the number, why don't you just store the number as a member variable, update that when a button is pressed, and change the text accordingly? This is how I would write it:
public class Main extends Activity {
int count = 0;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView) findViewById(R.id.txtCount);
findViewById(R.id.btnPlus).setOnClickListener(this);
findViewById(R.id.btnMinus).setOnClickListener(this);
findViewById(R.id.btnReset).setOnClickListener(this);
}
private void updateText() {
String text = Integer.toString(count);
textView.setText(text);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.btnPlus:
count++;
break;
case R.id.btnMinus:
count--;
break;
case R.id.btnReset:
count = 0;
break;
}
updateText();
}
}

Related

Call void method from another method in the same class

At first my main problem was at how to call a method from the same class, even tough I think I found a way to do this, it's not working as I expected, and I would like to know what would be the best approach to my case.
This is the code I'm working on:
public class EscolhaAtendimento extends AppCompatActivity {
private ViewPager mSlideViewPager;
private LinearLayout mDotLayout;
String TAG = "TasksSample";
private TextView[] mDots;
private SliderAdapter sliderAdapter;
Dialog myDialog;
#Override
public void onCreate (Bundle SavedInstanceState){
super.onCreate(SavedInstanceState);
setContentView(R.layout.escolha_atendimento);
mSlideViewPager = findViewById(R.id.slideViewPager);
mDotLayout = findViewById(R.id.dotsLayout);
sliderAdapter = new SliderAdapter(this);
mSlideViewPager.setAdapter(sliderAdapter);
addDotsIndicator(0);
mSlideViewPager.addOnPageChangeListener(viewListener);
myDialog = new Dialog(this);
}
public void addDotsIndicator(int position){
mDots = new TextView[8];
mDotLayout.removeAllViews();
for (int i= 0; i < mDots.length; i++){
mDots[i] = new TextView(this);
mDots[i].setText(Html.fromHtml("•"));
mDots[i].setTextSize(35);
mDots[i].setTextColor(getResources().getColor(R.color.colorTransparentWhite));
mDotLayout.addView(mDots[i]);
}
if (mDots.length > 0){
mDots[position].setTextColor(getResources().getColor(R.color.colorWhite));
}
}
ViewPager.OnPageChangeListener viewListener = new ViewPager.OnPageChangeListener(){
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected (int i) {
switch (i) {
case 0: {
myDialog.show();
}
addDotsIndicator(i);
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
public void ShowPopup(View v) {
TextView txtclose;
//Button btnFollow;
myDialog.setContentView(R.layout.pop_upfinal);
txtclose = myDialog.findViewById(R.id.txtclose);
txtclose.setText("X");
//btnFollow = (Button) myDialog.findViewById(R.id.btnfollow);
txtclose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myDialog.dismiss();
}
});
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
myDialog.show();
}
}
This class is an activity that on user swipe, the text and image from the buttons will change, even though their IDs will stay the same. (That's controlled by another class, it's working well).
Now, I wanted the image button on the activity do something different depending on which page is selected, and that's why there is a initial switch on the onPageSelected method, inside the Page change listener. The image button in the layout has the android:onClick="ShowPopup" tag, and I guess that also complicates things for me, if I wanted it to do something different in that same activity? Also, calling it that way on the switch, every time I change pages, and go back to the first one the popup window will open, since my call is explicit there. (As I said, even tough I found a way to somehow call my method, or at least it's result, it's not working as I expected).
Edit
I tried then changing it like this, so that the button wouldn't rely on the android:onClick="ShowPopup" Tag, and also wouldn't need to call a void method directly on the switch:
Added
public ImageButton popupchoice;
And also this to onCreate method:
popupchoice = this.findViewById(R.id.imgslide1);
Inside the switch I called it like this to get the button ID:
popupchoice.setOnClickListener(image1);
And set the View.OnClickListener like this:
View.OnClickListener image1 = new View.OnClickListener() {
public void onClick(View v) {
TextView txtclose;
//Button btnFollow;
myDialog.setContentView(R.layout.pop_upfinal);
txtclose = myDialog.findViewById(R.id.txtclose);
txtclose.setText("X");
//btnFollow = (Button) myDialog.findViewById(R.id.btnfollow);
txtclose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myDialog.dismiss();
}
});
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
myDialog.show();
}
};
But that returns me:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnClickListener(android.view.View$OnClickListener)' on a null object reference at .EscolhaAtendimento$1.onPageSelected(EscolhaAtendimento.java:81) Line 81 is the one inside the switch with the popupchoice.setOnClickListener(image1).
This error happens on page change, when coming back to the first Page, and also the button click won't work anymore.
I think you can use
EscolhaAtendimento.this.ShowPopup from inside your switch.

image view not being visible based on number of clicks

In my MainActiviy class I want to display image views of smiley faces based on the number of clicks that occur on the buttons jokes, poems and funnystories combined. However my switch statement does not seem to working as no images appear. Also if any of those image views become visible, then they should remain visible even after the user closing the app and reopening it.
I also notice a click count increasing by one when the user opens the app which is not correct. It should increase based on the buttons mentioned previously being clicked.
public class MainActivity extends AppCompatActivity {
SharedPreferencesManager prefManager = SharedPreferencesManager.getInstance(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button jokesButton = findViewById(R.id.button_jokes);
Button poemsButton = findViewById(R.id.button_poems);
Button funnyStoriesButton = findViewById(R.id.button_funny_stories);
ImageView yellowSmileyFace = findViewById(R.id.yellow_happy);
ImageView greenSmileyFace = findViewById(R.id.green_happy);
ImageView redSmileyFace = findViewById(R.id.red_happy);
jokesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
prefManager.increaseClickCount();
openContentPage("jokes");
}
});
poemsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
prefManager.increaseClickCount();
openContentPage("poems");
}
});
funnyStoriesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
prefManager.increaseClickCount();
openContentPage("funnystories");
}
});
TextView clickCountText = findViewById(R.id.click_count);
clickCountText.setText(Integer.toString(prefManager.increaseClickCount()));
switch (prefManager.increaseClickCount()){
case 4 :
yellowSmileyFace.setVisibility(View.VISIBLE);
break;
case 8 :
greenSmileyFace.setVisibility(View.VISIBLE);
break;
case 12 :
redSmileyFace.setVisibility(View.VISIBLE);
break;
default :
yellowSmileyFace.setVisibility(View.INVISIBLE);
greenSmileyFace.setVisibility(View.INVISIBLE);
redsmileyFace.setVisibility(View.INVISIBLE);
}
}
private void openContentPage(String v) {
Intent intentContentPage = new Intent(MainActivity.this, Content.class);
intentContentPage.putExtra("keyPage", v);
startActivity(intentContentPage);
}
}
below is the Shared preferences class
public class SharedPreferencesManager {
private static final String APP_PREFS = "AppPrefsFile";
private static final String NUMBER_OF_CLICKS = "numberOfClicks";
private SharedPreferences sharedPrefs;
private static SharedPreferencesManager instance;
private SharedPreferencesManager(Context context) {
sharedPrefs = context.getApplicationContext().getSharedPreferences(APP_PREFS, MODE_PRIVATE);
}
public static synchronized SharedPreferencesManager getInstance(Context context){
if(instance == null)
instance = new SharedPreferencesManager(context);
return instance;
}
public int increaseClickCount() {
int clickCount = sharedPrefs.getInt(NUMBER_OF_CLICKS, 0);
clickCount++;
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putInt(NUMBER_OF_CLICKS, clickCount);
editor.apply();
return clickCount;
}
}
You need to add a getter for your clicks
public int getClicks(){
return sharedPrefs.getInt(NUMBER_OF_CLICKS, 0);
}
Whenever you want to get your clicks currently you are calling increaseClickCount() which causes your clicks to increment before returning them. That is why it gains clicks every time you open the stage and why your switch isn't working correctly
so add the above getter to your SharedPrefrenceManager and change these two lines
switch (prefManager.increaseClickCount()){
to
switch (prefManager.getClicks()){
clickCountText.setText(Integer.toString(prefManager.increaseClickCount()));
to
clickCountText.setText(Integer.toString(prefManager.getClicks()));
Tell me if that fixes your problem
The reason for counts' increase is you use increaseClickCount() to receive click count.You have to create another method to receive current clickCount. Your switch statement works only when they equal to 4,8 or 12. Maybe you should use if instead.
I also notice a click count increasing by one when the user opens the app which is not correct
It looks to me like this line of code, in MainActivity.onCreate() method will pass a text String of count 1 to clickCountText.
clickCountText.setText(Integer.toString(prefManager.increaseClickCount()));
Also, every time you call SharedPreferencesManager.increaseClickCount, you are assigning a value to clickCount, and whatever was there gets overwritten.
int clickCount = sharedPrefs.getInt(NUMBER_OF_CLICKS, 0);
What is that value?
System.out.println is your friend.
I use this pattern
System.out.println("MyClass, MyMethod, MyVariable:" + myVariable);
I always include the class and method because it can be annoying trying to figure out where println are coming from if you leave several in for debugging purposes and want to get rid of them later.

Java - Efficient method with multiple onClickListener

My app currently has 5 buttons (I'm going to add more later) and when each button is clicked, it'll assign a number to an item.
I'm wondering if there's a more efficient way of writing the setOnClickListner (it seems like I have to use that since I'm using this as a fragment. I found a way to do it if I was to assign an onClick in the xml but I can't apply that to this part of the code). I have it written out 5 times (and in the future it'll be more)
buttons[0] = (Button) view.findViewById(R.id.cut1Btn);
buttons[1] = (Button) view.findViewById(R.id.cut2Btn);
buttons[2] = (Button) view.findViewById(R.id.cut3Btn);
buttons[3] = (Button) view.findViewById(R.id.cut4Btn);
buttons[4] = (Button) view.findViewById(R.id.cut5Btn);
buttons[0].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "TESTING BUTTON CLICK 1",Toast.LENGTH_SHORT).show();
data = 1;
}
});
buttons[1].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "TESTING BUTTON CLICK 2",Toast.LENGTH_SHORT).show();
data = 2;
}
});
buttons[2].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "TESTING BUTTON CLICK 3",Toast.LENGTH_SHORT).show();
data = 3;
}
});
buttons[3].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "TESTING BUTTON CLICK 4",Toast.LENGTH_SHORT).show();
data = 4;
}
});
buttons[4].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "TESTING BUTTON CLICK 5",Toast.LENGTH_SHORT).show();
data = 5;
}
});
Could I maybe do a switch or a loop? Like assign i = 0, i < 5, i++ for the button array and then for data make that data = i + 1 ? If so, any suggestions on how I can do that?
Thanks!
THe other answers here will work, but either use the tag (generally a bad idea and prevents any other use) and aren't really object oriented. Instead you should make a class an instantiate it.
private class MyClickListener {
private int data;
public MyClickListener(int data) {
this.data = data;
}
public void onClick(View view) {
Toast.makeText(getActivity(), "TESTING BUTTON CLICK" + data,Toast.LENGTH_SHORT).show();
}
}
...
int i=0;
for(Button button : buttons) {
button.setOnClickListener(new MyClickListener(i++));
}
You could use a common method and then implement a switch case based upon R.id of your button
An example would in like this.
in onCreate(--) method
cut1Btn = (Button) view.findViewById(R.id.cut1Btn);
cut2Btn = (Button) view.findViewById(R.id.cut2Btn);
cut3Btn = (Button) view.findViewById(R.id.cut3Btn);
cut4Btn = (Button) view.findViewById(R.id.cut4Btn);
cut5Btn = (Button) view.findViewById(R.id.cut5Btn);
cut1Btn.setOnClickListener(this);
cut2Btn.setOnClickListener(this);
cut3Btn.setOnClickListener(this);
cut4Btn.setOnClickListener(this);
cut5Btn.setOnClickListener(this);
Implement View.onClickListener in your activity and override this method in your activity
public void onClick(View v){
switch(v.getId()){
case R.id.cut1Btn:
//Put Your Code Here
break;
case R.id.cut2Btn:
//Put Your Code Here
break;
case R.id.cut3Btn:
//Put Your Code Here
break;
case R.id.cut4Btn:
//Put Your Code Here
break;
case R.id.cut5Btn:
//Put Your Code Here
break;
}
}
You can implement a switch to do this things:
Your class must implement OnClickListener and override function OnClick(View view).
Then just set OnClickListener(this) like this on onCreate method
buttons[1].setOnClickListener(this)
buttons[2].setOnClickListener(this)
buttons[3].setOnClickListener(this)
do a switch-case on override function
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
// button 1 do
break;
case R.id.button2:
// button 2 do
break;
case R.id.button3:
// button 3 do
break;
}
}

How can I make this Variable by UserInput work? android

public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button)findViewById(R.id.okay);
mEdit = (EditText)findViewById(R.id.name);
final TextView questionOne =(TextView)findViewById(R.id.questionOne);
final String name = mEdit.getText().toString(); //
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
Log.v("EditText", mEdit.getText().toString());
}
});
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
questionOne.setText("Tell me your lucky number, " + name + "!");
} });
}
}
So, my goal is to let the user write his name and then print it out with the setText method. In order to do this I declared the variable "name". But when I run the app and enter my name, it just prints out "Tell me your lucky number, !". So the variable name is missing completely. Can someone tell me what I did wrong with the variable, please?
Thank you in advance!
First of all, you over-wrote the button's one click listener. You were logging the EditText content just fine at one point.
Anyways, this gets the text immediately when the View is loaded. (And unless you put default text into that field, it is an empty string)
final String name = mEdit.getText().toString();
And it is final, so that variable can never even change values.
You need to "react" to the button event. So, do that.
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String name = mEdit.getText().toString();
questionOne.setText("Tell me your lucky number, " + name + "!");
}
});

java physics app in android ( maths )

Basically, I'm new to java and I have to make an android application that can do simple physics equations such as I=Q*t.... etc etc, basically I cannot for the life of me get the result to output, has anyone got any idea's why this wont work on the emulator?
I have tried putting intents and all sorts in there. Help please
public class Current extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_current);
// Show the Up button in the action bar.
setupActionBar();
#SuppressWarnings("unused")
Intent intent = getIntent();
}
public void Main(String[]args){
Button calc1 = (Button)findViewById(string.Calculate_Current);
calc1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// IIIIII HATE JAVA
EditText Charge1 = (EditText)findViewById(R.id.number_input_2);
EditText Time1 = (EditText)findViewById(R.id.number_input_3);
TextView Distances_answer = (TextView)findViewById(R.id.Distances_answer);
double charge = Double.parseDouble(Charge1.getText().toString());
double Time = Double.parseDouble(Time1.getText().toString());
#SuppressWarnings("unused")
Intent intent = new Intent();
Distances_answer.setText("" + charge + Time);
}
});
I feel like you are taking input of charge and time from two edittexts and then on click of a button you are updating a textview to place that product of charge and time there.Try this out
public class Current extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_name);
// Show the Up button in the action bar.
setupActionBar();
Button calc1 = (Button)findViewById(R.id.buttons_id_in_layout);
calc1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText Charge1 = (EditText)findViewById(R.id.number_input_2);
EditText Time1 = (EditText)findViewById(R.id.number_input_3);
TextView Distances_answer = (TextView)findViewById(R.id.distances_answer);
double charge = Double.parseDouble(Charge1.getText().toString());
double time = Double.parseDouble(Time1.getText().toString());
//Time is a class in Java
Distances_answer.setText("" +charge*time);
}
});
}

Categories

Resources