Hi all,
Some days ago I decided to make an app to help me in my job with some Maths, so I'm reading a lot and watching some classes on youtube to make it possible. I'm trying to make, basically, a calculator for some specific maths.
By a simple way, I learned how to make my EditText,TextView , and do the Math when I push one BUTTON, but in some cases, for a fast and easy result, would be better to update the "children" field, just when I edit the "parent" field, or when I leave it.
Like, if I type the number 1 in my first field, the second field that depends on it should update automatically using this reference that I just edited.
Is there possible ? If yes, recommended or it makes the app too "heavy" ? Considering that each activity would have just few maths, far from any big known app.
Thanks in advanced.
Barata
Hello,
Let's suppose you have one EditText and one TextView, with ids in your xml: myedittext1 and mytextview2. You can easily achieve that. I don't think that it will be heavy just for few maths But also if it is heavy, it can be done without making the UI thread unresponsive, using thread for the calculations.
So
Code:
final EditText et1 = (EditText) findViewById(R.id.myedittext1);
final TextView tv2 = (TextView) findViewById(R.id.mytextview2);
et1.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable arg0) {
//This is called AFTER the text has changed
//Now update the tv2
String textOutput = ...;
//tv2.setText(textOutput);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
//This is called BEFORE the text has changed
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
//This is called WHENEVER the text has changed
}
});
Button b1 = (Button) findViewById(R.id.mybutton);
b1.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
//do your math calculations here (if they are heavy, start a thread here)
//Edit the et1 here
//tv2 will be edited automatically according to the afterTextChanged above
}
});
If you would like to start a thread (if your maths are heavy), to avoid UI pausing and slow response from UI, follow the below code
//Thread solution (avoid making UI "laggy")
Before onCreate inside you Activity class:
Code:
EditText et1 = null;
TextView tv2 = null;
Thread t1 = null;
MyCalc mycalc = null;
MyCalc2 mycalc2 = null;
private class MyCalc implements Runnable{
public MyCalc(){
}
@Override
public void run(){
//Do you math here
final String outputText = ...;
try{
runOnUiThread(new Runnable() {
@Override
public void run() {
//Here set et1 text
et1.setText(outputText);
//tv2 text will be updated automatically
}
});
}catch (InterruptedException e){
}
});
}
private class MyCalc2 implements Runnable{
public MyCalc2(){
}
@Override
public void run(){
//Do you math here
final String outputText = ...;
try{
runOnUiThread(new Runnable() {
@Override
public void run() {
//Here set et1 text
et1.setText(outputText);
//tv2 text will be updated automatically
}
});
}catch (InterruptedException e){
}
});
}
Inside onCreate:
Code:
et1 = (EditText) findViewById(R.id.myedittext1);
tv2 = (TextView) findViewById(R.id.mytextview2);
et1.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable arg0) {
//This is called AFTER the text has changed
//if you need to do calculation here also, do:
mycalc2 = new MyCalc2(); //where MyCalc2 is the same as MyCalc but with different calculations :P
t1 = new Thread(mycalc2);
t1.start();
//Set tv2 text here.
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
//This is called BEFORE the text has changed
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
//This is called WHENEVER the text has changed
}
});
Button b1 = (Button) findViewById(R.id.mybutton);
b1.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
mycalc = new MyCalc();
t1 = new Thread(mycalc);
t1.start();
}
});
In onDestroy:
Code:
if(t1!=null){
if(t1.isAlive()==true){
if(t1.isInterrupted()==false){
t1.interrupt();
try{
t1.join();
}catch (InterruptedException e){
}
}
}
t1= null;
}
If you still need help, feel free to ask
Really thanks for the reply @MMDeveloper, but had some problems here, I'm trying to find a Solution for almost 1hr, and nothing.. I saw some ppeople with the same problem, but couldnt use the answers I've read to solve this code.
With the first solution you gave to me, I just delete the button part, just to try make all automatic. In this first sample I have just a simple math that should convert a CV power do kW
The studio shows that to me:
addTextChangedListener - Cannot resolve symbol;
TextWatcher - Invalid method declaration, return type required;
@Override - Annotations are not allowed here;
Editable arg0 - Cannot resolve symbols, for both;
I tried to put this code in different places in my main java, but nothing. Below is my XML and then my Java, could you take a look in it please ? I guess I'm used to copy and paste some codes from some classes, and that is harming me, i really need to start all over from the java sintaxe.
The fields I've changed to be those in your code are: torque_p_cv (edit) and torque_p_cv (view)
XML:
Code:
<RelativeLayout xmlns:android="CANT SHOW LINK UNDER 10 POSTS"
xmlns:tools="CANT SHOW LINK UNDER 10 POSTS"
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=".Calculos001_Main">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cálc. do torque em função de P e n"
android:id="@+id/torque_titulo"
android:layout_gravity="center_horizontal"
android:textAlignment="center"
android:layout_marginTop="10dp"
android:textSize="20dp"
android:textStyle="bold|italic" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="50dp">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="P"
android:id="@+id/torque_tits_p" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Potência do motor"
android:id="@+id/textView"
android:layout_marginStart="10dp" />
<EditText
android:layout_width = "0dp"
android:layout_height="wrap_content"
android:id="@+id/torque_p_cv"
android:layout_weight="1"
android:inputType="number"
android:hint="Potência"
android:gravity="end"
android:layout_marginStart="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="CV"
android:id="@+id/unidade_CV"
android:textAlignment="textEnd"
android:gravity="end"
android:layout_marginStart="10dp" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="xxxxx"
android:id="@+id/torque_p_kw"
android:textAlignment="textEnd"
android:gravity="end"
android:layout_marginStart="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="kW"
android:id="@+id/unidade_kW"
android:textAlignment="textEnd"
android:gravity="end"
android:layout_marginStart="10dp" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
and the Java:
Code:
package com.example.tbarata.calculos_001;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
public class Calculos001_Main extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculos001__main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_calculos001__main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
final EditText et1 = (EditText) findViewById(R.id.torque_p_cv);
final TextView tv2 = (TextView) findViewById(R.id.torque_p_kw);
et1.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable arg0) {
//This is called AFTER the text has changed
//Now update the tv2
String textOutput = "0";
//tv2.setText(textOutput);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
//This is called BEFORE the text has changed
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
//This is called WHENEVER the text has changed
}
});
}
Really thanks,
Barata
Hello again!!
I was watching some classes now on youtube, and I made some tests that almost worked for what I want.
In this code, I cant edit one EditText and show a message in the 3 situations, before, on and after change the text.... and I did changes in the TextView created with AFTER, but just changed to a simple word, a text. That worked perfectly.
Now I'm trying to make a simple math, but I'm making some mistake with numbers and texts. I just need to multiply the EditText for a number (0.7354988) and put the result in the TextView, so I would convert CV to kW, but it gives me a message that I cant do it. I create one double CVtokWfactor with that value, but I'm not sure if I did it right.
this is the error:
Error44, 49) error: bad operand types for binary operator '*'
first type: EditText
second type: double
Below the JAVA:
Code:
package com.example.tbarata.textvalidation;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class TextValidation extends Activity implements TextWatcher{
EditText ed1;
TextView tv2;
double CVtokWfactor = 0.7354988;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_text_validation);
ed1=(EditText) findViewById(R.id.editText1);
ed1.addTextChangedListener(this);
tv2=(TextView) findViewById(R.id.textView2);
}
public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
Toast.makeText(this, "before", Toast.LENGTH_SHORT).show();
}
@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
Toast.makeText(this, "on change", Toast.LENGTH_SHORT).show();
}
@Override
public void afterTextChanged(Editable editable) {
Toast.makeText(this, "after", Toast.LENGTH_SHORT).show();
tv2.setText(String.format("%.2f", (ed1 * CVtokWfactor)));
}
}
What should I change to multiply these numbers ?
Thanks again.
Barata
Hello
For your first reply:
You have to put the code with the EditText inside the onCreate method. You made it work in the above code that you posted (outside onCreate) because you implemented the TextWatcher interface. You could avoid that by adding the code related with TextWatcher inside the onCreate method as I posted above
For your second reply:
In the afterTextChanged method, at
Code:
tv2.setText(String.format("%.2f", (ed1 * CVtokWfactor)));
You multiply the EditText ed1 with the double CVtokWfactor. You can't multiply an EditText with a number. The operand * needs numbers (int, double, float, etc )
You need to get the text of the ed1, convert it to double (I suppose edittext has double number) and then multiply, like this:
Code:
tv2.setText(String.format("%.2f", (Double.parseDouble(ed1.getText().toString()) * CVtokWfactor)));
Also I recommend to remove the Toasts from the methods beforeTextChanged, onTextChanged and afterTextChanged. They are called each time you type something on the EditText ed1.
If you still need help, feel free to ask
Hi!
Now it worked perfectly @MMDeveloper!! really thanks !
Agree with you about the Toast code, I forgot to delete it before paste here, it was just a test to see the events
About the way of using the TextWatcher, should I use the first way that you said, for some specific reason or basically both are the same ?
And now that's working, came the idea to improve the math, for an easy way of using it.
Now I can convert power in CV to kW, but lets say that I have one value in kW already, and need to convert to CV, would be posible using this same code/activity ? So I would convert in the same activity both units. Or, its gonna be some redundant thing ? My idea to save space, is use just the 2 fields, without one third to get the result.
This is the code now, already changed for a second EditText and not TextView anymore, until now it's working to convert the unit CV to kW, just when I clean out the EditTex1 field, the EditText2 keeps the conversion from the last number in the EditText1. Actually it's not a problem for now, the important is just convert it
Code:
public class Calc001Activity extends Activity implements TextWatcher {
EditText ed1;
EditText ed2;
double CVtokWfactor = 0.7354988;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calc001);
ed1=(EditText) findViewById(R.id.editText1);
ed1.addTextChangedListener(this);
ed2=(EditText) findViewById(R.id.editText2);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
try {
ed2.setText(String.format("%.2f", (Double.parseDouble(ed1.getText().toString()) * CVtokWfactor)));
}
catch (NumberFormatException e) {}
}
}
Thanks in advanced.
Barata.
Let's fix the issue with the old conversion first
When you clear the ed1 your
Code:
ed2.setText(String.format("%.2f", (Double.parseDouble(ed1.getText().toString()) * CVtokWfactor)));
}
should cause your app to crash, because Double conversion from an empty string would throw the NumberFormatException.
You are already catching it so it silently ignores it, and the ed2 is not updated.
To solve this just make a check:
Code:
@Override
public void afterTextChanged(Editable s) {
if(doNoEnterEd1==true){
return;
}
doNotEnterEd2 = true;
try {
if(ed1.getText().toString().equals("")){
ed2.setText("");
}
else{
ed2.setText(String.format("%.2f", (Double.parseDouble(ed1.getText().toString()) * CVtokWfactor)));
}
}
catch (NumberFormatException e) {}
doNotEnterEd2 = false;
}
Now it should clear the ed2 too, when you clear the ed1.
Now for the TextWatcher, you should do it as I mentioned in my first reply, only for having a separate TextWatcher for each EditText, but there is no problem with implenting the TextWatcher, as you did. Just for code clarity. Furthermore, for code clarity (and reusability), the text watcher should be in a separate Java class, but no need for such a small application So you are ok with that.
You can easily do the reverse conversion (from ed2 to ed1) as follows:
Inside your class outside any method, where you declared your EditText add:
Code:
boolean doNotEnterEd1=false;
boolean doNotEnterEd2=false;
in the onCreate method:
Code:
ed2=(EditText) findViewById(R.id.editText2);
ed2.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable arg0) {
if(doNoEnterEd2==true){
return;
}
doNotEnterEd1 = true;
try {
if(ed2.getText().toString().equals("")){
ed1.setText("");
}
else{
ed1.setText(String.format("%.2f", (Double.parseDouble(ed2.getText().toString()) * CVtokWfactor))); //Here do the conversion as you like, replace CVtokWfactor.
}
}
catch (NumberFormatException e) {}
doNotEnterEd1=false;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
I think it should work like intended now.
If you still encounter a problem feel free to ask
Hello!
@MMDeveloper, thanks man!!!
The code is working perfectly!! I changed the code as in the first reply and with these last modifications, its 100%!
Now I'm gonna improve the layout and add the others inputs for the math, but the base code is fully working
Really thanks for you time, helping me.
As reference, this is my code now (still without the improvement):
Code:
package com.example.barata.calc001;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class Calc001Activity_002 extends Activity {
double CVtokWfactor_2 = 0.7354988;
boolean doNotEnterEd1=false;
boolean doNotEnterEd2=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calc001_activity_002);
final EditText ed1_2 = (EditText) findViewById(R.id.editText02_1);
final EditText ed2_2 = (EditText) findViewById(R.id.editText02_2);
ed1_2.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if(doNotEnterEd1==true){
return;
}
doNotEnterEd1 = true;
try {
if(ed1_2.getText().toString().equals("")){
ed2_2.setText("");
}
else{
ed2_2.setText(String.format("%.3f", (Double.parseDouble(ed1_2.getText().toString()) * CVtokWfactor_2)));
}
}
catch (NumberFormatException e) {}
doNotEnterEd2 = false;
}
});
ed2_2.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable arg0) {
if(doNotEnterEd2==true){
return;
}
doNotEnterEd1 = true;
try {
if(ed2_2.getText().toString().equals("")){
ed1_2.setText("");
}
else{
ed1_2.setText(String.format("%.3f", (Double.parseDouble(ed2_2.getText().toString()) * CVtokWfactor_2))); //Here do the conversion as you like, replace CVtokWfactor.
}
}
catch (NumberFormatException e) {}
doNotEnterEd1=false;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
}
public void vemPara001(View view) {
Intent vem001 = new Intent(this, Calc001Activity.class);
startActivity(vem001);
finish();
}
public void vaiPara003(View view) {
Intent vai003 = new Intent(this, Calc001Activity_003.class);
startActivity(vai003);
finish();
}
}
Thanks again!
barata.
Hi again!!
Sorry bring this topic back, but I gave up of doind my sliding tabs to get a nice layout in this app... so I got this one with a sliding menu from left, the I thought would be nice to use.
This is the link:
https://github.com/JulienGenoud/android-percent-support-lib-sample
Actually, the focus on its sample is to use the PERCENT lib, but that I don't care, just need to use the sliding menu;
I tried to replace the view1.xml for that with the code above (with textWatcher) and created one view_1.java with the codes, but nothing happens when I type a number in the editText....
Because the app uses a Drawer or fragment, should I change the way of doing that and automatically update the fields?
Thanks again!
Barata
I am have been working on this app for a few weeks now. I have never done any coding in my life, until I started this app. I have a few secret codes/dial codes that I use often, but i forget what code to use when sometimes, so I wanted to make an app that would make it as simple as clicking a button, and the app would send the code for me.
I have all my buttons, and I have them programmed. I gave the permissions that I think it needs, but when I run the app on my phone I get nothing. In Android Studio, I can read this,
"W/BroadcastQueue: Permission Denial: broadcasting Intent { act=android.provider.Telephony.SECRET_CODE dat=android_secret_code://XXXXXX flg=0x10 } from com.myapp.appname (pid=7540, uid=10128) requires android.permission.CONTROL_INCALL_EXPERIENCE due to receiver com.google.android.apps.tycho/.receivers.DialerCodeReceiver"
for permissions I have:
AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.CONTROL_INCALL_EXPERIENCE" />
MainActivity.java:
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button)findViewById(R.id.Button);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String secretCode1 = "xxxxx";
String action = "android.provider.Telephony.SECRET_CODE";
Uri uri = Uri.parse("android_secret_code://" + xxxxx);
Intent button1 = new Intent(action, uri);
sendBroadcast(button1);
}
});
Activity_main.xml - Textview
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button"
android:id="@+id/Button"
android:layout_gravity="center_horizontal"
androidnClick="onbuttonclick" />
Please, let me know what I did wrong, or if you need more information to fix it.
I did also try the dial intent, but when the button was pressed it would only dial * and not the #*#code#*#*
I hate to bump but I have had no response yet.
Have you resolved this problem? I'm running into a similar issue and am curious if you were able to resolve this.
You've written -
<uses-permission android:name="android.permission.CONTROL_INCALL_EX PERIENCE" />
There's a space between EX and PERIENCE..
I'm sure that's causing the error..
Hey Guys,
I'm pretty new to all this and slowly learning little by little.
This is my 1st post to any android forum about developing and I've started a little project to help me learn as I go.
I'm looking to work up a basic "step by step" app. (added a quick pic to show what I'm talking about somewhat)
So it won't let me add photos yet.
I would like to have MainActivity with several buttons: Sandwich, Burger and Hotdog for this example.
Click on Sandwich and it opens up to a "Sandwich Main" which would have additional buttons: Ham, Turkey
Click on Ham and we move to "Step 1" of the how-to... Get two pieces of bread.
Next Button takes you to step #2 and so on and so on...
Just a pretty dumb and I hope simple project I can use to learn some basics.
I used the following when I was testing a single button:
public void buttonOnClick (View view) {
Button button = (Button) view;
startActivity (new Intent(getApplicationContext(), Main2Activity.class));
}
This was straight forward easy way to get a single button to move to a new activity.
Now when I attempted to add a second button to the mix, it didn't work.
If there is a way to easily add multiple button to the above, let me know please... I found this way to be easiest for me to get so far.
So next I tried to go about it at a different angle:
activity_main.xml:
<RelativeLayout xmlns:android=".... (WON'T LET ME TYPE LINKS)
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="104dp"
android:layout_marginTop="20dp"
android:text="Button1" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_below="@+id/button1"
android:layout_marginTop="34dp"
android:text="Button2" />
MainActivity.java:
public class MainActivity extends Activity implements OnClickListener {
Button b1,b2,
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button)findViewById( R.id.button1);
b2 = (Button)findViewById(R.id.button2);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
}
@override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
Toast.makeText(getApplicationContext(), "button1 is working", 3000).show();
break;
case R.id.button2:
Toast.makeText(getApplicationContext(), "button2 is working", 3000).show();
break;
}
}
}
By doing the above I end up with the activity2 button clicking to activity3 first rather than activity2.
Activity3 button clicked correctly to activity3.
Another quick pic below to show what is going on... (whoops, won't let me post pics until I have 10 posts)
*MainActivity (BtnActivity2) and (BtnActivity3)
--- BtnActivity2 > opens Activity3 - (press phone back button) > Activity2 - (press back button again) > MainActivity
--- BtnActivity3 > opens Activity3 - (press phone back button) > Main Activity *** WORKING CORRECTLY ****
Any help would be appreciated!
I know that no one has posted up any replies but I thought I would update on my progress.
Does anyone see any possible issues I will have by going this route?
I've gotten each button to open each desired activities now by using the following:
AndroidManifest.xml
<?xml version-“1.0” encoding=”utf-8”?>
<manifest xmlns:android=”……..”
Package=”com……..”>
<application
Android:allowBackup=”true”
Android:icon=”@mipmap/ic_launcher”
Android:label=”My Application”
Android:supportsRt1=”true”
Android:theme=”@style/AppTheme”>
<activity android:name=”.MainActivity”
<intent-filter>
<action android:name=”android.intent.action.MAIN” />
<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
<activity android:name=”.Main2Activity” />
<activity android:name=”.Main3Activity” />
</application>
</manifest>
activity_main.xml
<?xml version-“1.0” encoding=”utf-8”?>
<RelativeLayout xmlns:android=”………”
Xmlns:tools=”……….”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
androidaddingBottom=”16dp”
androidaddingLeft=”16dp”
androidaddingRight=”16dp”
androidaddingTop=”16dp”
tools:context=”com…..”
android:background=”#88c2ff”>
<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Act 2”
android:id=”@+id/button”
android:clickable=”true”
androidnClick=”onClick”
android:layout_centerVerticle=”true”
android:layout_centerHorizontal=”true” >
<Button
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:text=”Act 3”
android:id=”@+id/button2”
android:clickable=”true”
androidnClick=”onClick”
android:layout_centerVerticle=”true”
android:layout_centerHorizontal=”true” >
</RelativeLayout>
MainActivity.java
package com……
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.content.Intent;
public class MainActivity extends Activity implements OnClickListener {
Button button, button2;
@override
protected void onCreate(Bundle savedInstantState) {
super.onCreate(savedInstantState);
setContentView (R.layout.activity_main);
button=(Button) findViewById(R.id.button);
button2=(Button) findViewById(R.id.button2);
}
@override
public void onClick(View view) {
switch (view.getId()){
case R.id.button:
startActivity(new Intent(getApplicationContext(), Main2Activity.class));
break;
case R.id.button:
startActivity(new Intent(getApplicationContext(), Main2Activity.class));
break;
}
}
}
Yes you are on the right path... The key is to add each Activity (view) to your Manifest (You already did), if not when you are traversing to separate Activities by button click it wont work. If you run into any other issues let me know, ill be glad to help.
andre3 said:
Yes you are on the right path... The key is to add each Activity (view) to your Manifest (You already did), if not when you are traversing to separate Activities by button click it wont work. If you run into any other issues let me know, ill be glad to help.
Click to expand...
Click to collapse
Yeah, I think I've pretty much gotten the hang of the methods used when implementing buttons within the activities.
I'm pretty new at this and try to learn as I go and when I get time to set down and mess with it all.
Right now I'm attempting to learn more and more about using fragments and when it is best to do so.
zrollins said:
Yeah, I think I've pretty much gotten the hang of the methods used when implementing buttons within the activities.
I'm pretty new at this and try to learn as I go and when I get time to set down and mess with it all.
Right now I'm attempting to learn more and more about using fragments and when it is best to do so.
Click to expand...
Click to collapse
Sounds good. We are in the same boat; Fragments + Material Design is the new trend, I try to learn as much as I can and use them as much as I can. Good luck!
hello,
i have a problem with my app, i am trying to add NFC for a point system, like get points at a NFC tag.
my java.start (without links)
package plopmenzinc.nsapp;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.nfc.NfcAdapter;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class Start extends AppCompatActivity {
int number = 0;
public void onClickBtn(View v)
{
TextView var = (TextView) findViewById(R.id.score);
number++;
String disp = Integer.toString(number);
var.setText(disp);
}
public class MainActivity extends Activity {
public static final String MIME_TEXT_PLAIN = "text/plain";
public static final String TAG = "NfcDemo";
private TextView mTextView;
private NfcAdapter mNfcAdapter;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (mNfcAdapter == null) {
// Stop here, we definitely need NFC
Toast.makeText(this, "This device doesn't support NFC.", Toast.LENGTH_LONG).show();
finish();
return;
}
if (!mNfcAdapter.isEnabled()) {
mTextView.setText("NFC is disabled.");
}
handleIntent(getIntent());
}
@override
protected void onResume() {
super.onResume();
/**
* It's important, that the activity is in the foreground (resumed). Otherwise
* an IllegalStateException is thrown.
*/
setupForegroundDispatch(this, mNfcAdapter);
}
@override
protected void onPause() {
/**
* Call this before onPause, otherwise an IllegalArgumentException is thrown as well.
*/
stopForegroundDispatch(this, mNfcAdapter);
super.onPause();
}
@override
protected void onNewIntent(Intent intent) {
/**
* This method gets called, when a new Intent gets associated with the current activity instance.
* Instead of creating a new activity, onNewIntent will be called. For more information have a look
* at the documentation.
*
* In our case this method gets called, when the user attaches a Tag to the device.
*/
handleIntent(intent);
}
private void handleIntent(Intent intent) {
TextView var = (TextView) findViewById(R.id.score);
number++;
String disp = Integer.toString(number);
var.setText(disp);
}
/**
* @param activity The corresponding {@link Activity} requesting the foreground dispatch.
* @param adapter The {@link NfcAdapter} used for the foreground dispatch.
*/
public void setupForegroundDispatch(final Activity activity, NfcAdapter adapter) {
final Intent intent = new Intent(activity.getApplicationContext(), activity.getClass());
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
final PendingIntent pendingIntent = PendingIntent.getActivity(activity.getApplicationContext(), 0, intent, 0);
IntentFilter[] filters = new IntentFilter[1];
String[][] techList = new String[][]{};
// Notice that this is the same filter as in our manifest.
filters[0] = new IntentFilter();
filters[0].addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
filters[0].addCategory(Intent.CATEGORY_DEFAULT);
try {
filters[0].addDataType(MIME_TEXT_PLAIN);
} catch (IntentFilter.MalformedMimeTypeException e) {
throw new RuntimeException("Check your mime type.");
}
adapter.enableForegroundDispatch(activity, pendingIntent, filters, techList);
}
public void stopForegroundDispatch(final Activity activity, NfcAdapter adapter) {
adapter.disableForegroundDispatch(activity);
}
}
}
my activity: (without links)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="(link)"
xmlns:tools="(link)"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
androidrientation="vertical"
androidaddingBottom="@dimen/activity_vertical_margin"
androidaddingLeft="@dimen/activity_horizontal_margin"
androidaddingRight="@dimen/activity_horizontal_margin"
androidaddingTop="@dimen/activity_vertical_margin"
tools:context="plopmenzinc.nsapp.Start"
android:saveEnabled="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Uw aantal punten:"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="50dp"
android:singleLine="true"
android:textColor="#FF2646B0"
android:textSize="22sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/disp"
android:id="@+id/score"
android:layout_alignBottom="@+id/textView"
android:layout_toRightOf="@+id/textView"
android:layout_toEndOf="@+id/textView"
android:textSize="22sp" />
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Add Points"
androidnClick="onClickBtn"
android:layout_marginBottom="73dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
if you need other files/scripts, just ask.
thank you
EDIT: removed the public class MainActivity extends Activity {} and works perfect now