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
Related
I want to insert data to a database I have created. I have created an insert command at the OnCreate class. When viewing the database in SQLite Browser the data do not show. Can anyone help me
DatabaseHelper
Code:
package app.mobiledevicesecurity;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by Martin on 2015/07/28.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "mobilesec.db";
public static final String TABLE_NAME = "read_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "CATEGORY";
public static final String COL_3 = "HEADING";
public static final String COL_4 = "INFO";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
SQLiteDatabase db = this.getWritableDatabase();
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, CATEGORY TEXT, HEADING TEXT, INFO TEXT)");
ContentValues cv = new ContentValues();
cv.put(COL_2,"Malware");
cv.put(COL_3,"Virus");
cv.put(COL_4,"Harmfull for device");
db.insert(TABLE_NAME, null, cv);
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
}
MainActivity
Code:
package app.mobiledevicesecurity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
DatabaseHelper myDb;
private static Button readbtn;
private static Button quizbtn;
private static Button scoresbtn;
private static Button settingsbtn;
private static Button helpbtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new DatabaseHelper(this);
OnClickReadButtonListener();
OnClickQuizButtonListener();
OnClickScoresButtonListener();
OnClickSettingsButtonListener();
OnClickHelpButtonListener();
}
public void OnClickReadButtonListener() {
readbtn = (Button) findViewById(R.id.readbutton);
readbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Read_Category");
startActivity(intent);
}
}
);
}
public void OnClickQuizButtonListener() {
quizbtn = (Button) findViewById(R.id.quizbutton);
quizbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Quiz");
startActivity(intent);
}
}
);
}
public void OnClickScoresButtonListener() {
scoresbtn = (Button) findViewById(R.id.scoresbutton);
scoresbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Scores");
startActivity(intent);
}
}
);
}
public void OnClickSettingsButtonListener() {
settingsbtn = (Button) findViewById(R.id.settingsbutton);
settingsbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Settings");
startActivity(intent);
}
}
);
}
public void OnClickHelpButtonListener() {
helpbtn = (Button) findViewById(R.id.helpbutton);
helpbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Help");
startActivity(intent);
}
}
);
}
@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_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);
}
when I run the app on the emulator and open Android Device Monitor and get the database file and open it with SQlite Browser. Only the Column names are created the values are not shown. Why is this happening
Try to commit after you insert a record, also I think you can check what the insert command is returning to see if the insert command was successful or not...
The reason it isn't working is because you probably added the the insert after you had already created your database, so therefore onCreate is not being called anymore.
onUpgrade will only be called if you change the version of your database, so that will not be called either.
you should just make another method that is used to update your table, or explicitly call Oncreate.
what I did while I was testing is in the constructor of my database class, i would call a method that would drop all the tables, and then explicitly call onCreate after that. Remove this code when you are done testing
I want to show the result activity on the end of the quiz which is working. And then show the scores activity on press of a button on the main activity
Advice I got is to Create a listener for the scores button on Main Activity and add code to launch the Scores Activity with an intent where you pass the score. And then retrieve the bundle on the onCreate method on your ScoresActivity. Can someone help me on this please regarding the code.
MainActivity:
Code:
package app.mobiledevicesecurity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
DatabaseHelper myDb;
private static Button readbtn;
private static Button quizbtn;
private static Button scoresbtn;
private static Button settingsbtn;
private static Button helpbtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new DatabaseHelper(this);
myDb.insertData();
OnClickReadButtonListener();
OnClickQuizButtonListener();
OnClickScoresButtonListener();
OnClickSettingsButtonListener();
OnClickHelpButtonListener();
}
public void OnClickReadButtonListener() {
readbtn = (Button) findViewById(R.id.readbutton);
readbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Read_Category");
startActivity(intent);
}
}
);
}
public void OnClickQuizButtonListener() {
quizbtn = (Button) findViewById(R.id.quizbutton);
quizbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Quiz");
startActivity(intent);
}
}
);
}
public void OnClickScoresButtonListener() {
scoresbtn = (Button) findViewById(R.id.scoresbutton);
scoresbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Scores");
startActivity(intent);
}
}
);
}
public void OnClickSettingsButtonListener() {
settingsbtn = (Button) findViewById(R.id.settingsbutton);
settingsbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Settings");
startActivity(intent);
}
}
);
}
public void OnClickHelpButtonListener() {
helpbtn = (Button) findViewById(R.id.helpbutton);
helpbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Help");
startActivity(intent);
}
}
);
}
@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_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);
}
}
Result:
Code:
package app.mobiledevicesecurity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Result extends Activity {
private static Button playbtn;
private static Button menubutton;
int score;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
OnClickPlayButtonListener();
OnClickMenuButtonListener();
TextView textResult = (TextView) findViewById(R.id.textResult);
Bundle b = getIntent().getExtras();
score = b.getInt("score");
textResult.setText("You scored" + " " + score + " for the quiz.");
}
public void getScore()
{
Intent intent2 = new Intent(Result.this,
Scores.class);
Bundle bun = new Bundle();
bun.putInt("score", score);
intent2.putExtras(bun);
startActivity(intent2);
finish();
}
public void OnClickPlayButtonListener() {
playbtn = (Button) findViewById(R.id.btn);
playbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Quiz");
startActivity(intent);
}
}
);
}
public void OnClickMenuButtonListener() {
menubutton = (Button) findViewById(R.id.menubtn);
menubutton.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
);
}
}
Scores:
Code:
package app.mobiledevicesecurity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.content.Intent;
public class Scores extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scores);
Result res = new Result();
res.getScore();
TextView txtScore1 = (TextView) findViewById(R.id.txtScore1);
Bundle bun = getIntent().getExtras();
int score = bun.getInt("score");
txtScore1.setText("Last quiz score:" + " " + score + ".");
}
@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_scores, 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);
}
}
You should never create instances of activity with "new" keyword, because Activity is a part of Android ecosystem, not just a java class. So the line with
Code:
new Result();
is wrong. Then, if you want to pass some data from one activity to another when the latter is being opened after click, you need to put you data in the Intent (like you did it right, but in the wrong place in code)
Code:
scoresbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent2 = new Intent(Result.this,
Scores.class);
Bundle bun = new Bundle();
bun.putInt("score", score);
intent2.putExtras(bun);
startActivity(intent2);
}
}
);
That's it, your code on fetching the "score" variable out of Intent in Score activity is seemingly right.
svvorf said:
You should never create instances of activity with "new" keyword, because Activity is a part of Android ecosystem, not just a java class. So the line with
Code:
new Result();
is wrong. Then, if you want to pass some data from one activity to another when the latter is being opened after click, you need to put you data in the Intent (like you did it right, but in the wrong place in code)
Code:
scoresbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent2 = new Intent(Result.this,
Scores.class);
Bundle bun = new Bundle();
bun.putInt("score", score);
intent2.putExtras(bun);
startActivity(intent2);
}
}
);
That's it, your code on fetching the "score" variable out of Intent in Score activity is seemingly right.
Click to expand...
Click to collapse
Can you maybe show me where to put this in my code. And help me with the new Result() part
Hello!
i need some help, i am creating a Grid View with this java code:
MainActivity
public class MainActivity extends AppCompatActivity {
private GridView gridView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = (GridView)findViewById(R.id.gridview);
gridView.setAdapter(new GridAdapter(this));
}
@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_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);
}
}
Click to expand...
Click to collapse
Product
public class Product {
private static String nombrePizza;
private static String ingredientesPizza;
private static int imagenPizza;
private static int idThumbnail;
public Product(String nombrePizza, String ingredientesPizza, int imagenPizza){
this.nombrePizza = nombrePizza;
this.ingredientesPizza = ingredientesPizza;
this.imagenPizza = imagenPizza;
}
public String getNombrePizza(){return nombrePizza;}
public String getIngredientesPizza(){return ingredientesPizza;}
public int getImagenPizza(){return imagenPizza;}
public int getId(){return nombrePizza.hashCode();}
public static Product[] Pizzas={
new Product(
"Proscuito",
"Jamon York y queso",
R.drawable.imagenprueba),
new Product(
"Tropical",
"Jamon York, queso y piña",
R.drawable.imagenprueba),
new Product(
"Barbacoa",
"Carne picada, queso y salsa Barbacoa",
R.drawable.imagenprueba),
new Product(
"Romana",
"Jamon York, champiñones y queso",
R.drawable.cubo),
};
public static Product getItem(int id) {
for (Product item : Pizzas) {
if (item.getId() == id) {
return item;
}
}
return null;
}
}
Click to expand...
Click to collapse
Grid Adapter
public class GridAdapter extends BaseAdapter {
private final Context mContext;
public GridAdapter(Context c){
this.mContext = c;
}
@Override
public int getCount(){return Product.Pizzas.length;}
@Override
public Product getItem(int position){return Product.Pizzas[position];}
@Override
public long getItemId(int position){return 0;}
@Override
public View getView(int position, View ConvertView, ViewGroup viewGroup){
if(ConvertView == null){
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ConvertView = inflater.inflate(R.layout.grid_item, viewGroup, false);
}
TextView name = (TextView)ConvertView.findViewById(R.id.grid_mainText);
ImageView image = (ImageView) ConvertView.findViewById(R.id.grid_image);
TextView descripcion = (TextView) ConvertView.findViewById(R.id.grid_subText);
final Product item = getItem(position);
image.setImageResource(item.getImagenPizza());
name.setText(item.getNombrePizza());
descripcion.setText(item.getIngredientesPizza());
return ConvertView;
}
}
Click to expand...
Click to collapse
It work fine except for one thing, the app only shows the last product of the java code (Pizza romana)four times
I dont know why my app do this, can somebody help me??
Thank you! :fingers-crossed:
Goodmorning ,
I was dabbling with the parser of a web page through Android Studio, the problem is that the code I implemented can't take what i want, I'll explain:
on a website is a web page with the following html:
HTML:
</style>
</head>
<body>
<h1>TITLE PAGE</h1>
<h2><em></em></h2>
<h2>La data prossimae è:</h2>
<p><br />Lunedi 10/10/2016<br />Orario 13.00 - 18.00</p><input type="button" name="chiudi" value="Chiudi" onclick="javascript: self.close();" />
</body>
</html>
With the class JSOUP I'd like to take just the date which is enclosed within <p>, that is, "10/10/2016", is it possible? for now I could only print the page title or the entire text of the page.
here is the class code:
HTML:
package inducesmile.com.androidjsouphtmlparser;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.File;
import java.io.IOException;
public class MainActivity extends ActionBarActivity {
private Document htmlDocument;
private String htmlPageUrl = "website";
private TextView parsedHtmlNode;
private String htmlContentInStringFormat;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_livepage);
parsedHtmlNode = (TextView)findViewById(R.id.html_content);
Button htmlTitleButton = (Button)findViewById(R.id.button);
htmlTitleButton.setOnClickListener(new View.OnClickListener() {
[user=439709]@override[/user]
public void onClick(View v) {
JsoupAsyncTask jsoupAsyncTask = new JsoupAsyncTask();
jsoupAsyncTask.execute();
}
});
}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_livepage, menu);
return true;
}
[user=439709]@override[/user]
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);
}
private class JsoupAsyncTask extends AsyncTask<Void, Void, Void> {
[user=439709]@override[/user]
protected void onPreExecute() {
super.onPreExecute();
}
[user=439709]@override[/user]
protected Void doInBackground(Void... params) {
try {
htmlDocument = Jsoup.connect(htmlPageUrl).get();
htmlContentInStringFormat = htmlDocument.text();
// htmlDocument.title();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
[user=439709]@override[/user]
protected void onPostExecute(Void result) {
parsedHtmlNode.setText(htmlContentInStringFormat);
}
}
}
Thanks to everyone for help!
I want to send mail from Navigation Drawer using the intent. First, my MainActivity.
Code:
else if(id==R.id.nav_mail) {
fragment = new MailFragment();
}
and MailFragment.
Code:
public class MailFragment extends Fragment {
public MailFragment() {
Intent email = new Intent(Intent.ACTION_SEND);
email.setType("plain/text");
String[] address = {"********@gmail.com"};
email.putExtra(Intent.EXTRA_EMAIL, address);
email.putExtra(Intent.EXTRA_SUBJECT, "Subject___****");
email.putExtra(Intent.EXTRA_TEXT, "Text___****.\n\n");
startActivity(email);
}
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// TextView textView = new TextView(getActivity());
// textView.setText(R.string.hello_blank_fragment);
// return textView;
// }
}
Run to create crash. The reason why I used to use fragment is because I made the simple screen change function fragment.
If you need more code, comment plz.
I didn't get what you are trying to do. If you are trying to invoke the "Select your mail app" screen and then send a message thru the Intent all of this when the user clicks on a row on the drawer then you should just copy the code to
Code:
else if(id==R.id.nav_mail) {
// here
}
without switching any fragment.
By the way, as far as I know, the fragment's public constructor must be empty.
You cannot do it from Fragment's constructor. Move your code to onActivityCreated() method.
qlife1146 said:
I want to send mail from Navigation Drawer using the intent. First, my MainActivity.
Code:
else if(id==R.id.nav_mail) {
fragment = new MailFragment();
}
and MailFragment.
Code:
public class MailFragment extends Fragment {
public MailFragment() {
Intent email = new Intent(Intent.ACTION_SEND);
email.setType("plain/text");
String[] address = {"********@gmail.com"};
email.putExtra(Intent.EXTRA_EMAIL, address);
email.putExtra(Intent.EXTRA_SUBJECT, "Subject___****");
email.putExtra(Intent.EXTRA_TEXT, "Text___****.\n\n");
startActivity(email);
}
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// TextView textView = new TextView(getActivity());
// textView.setText(R.string.hello_blank_fragment);
// return textView;
// }
}
Run to create crash. The reason why I used to use fragment is because I made the simple screen change function fragment.
If you need more code, comment plz.
Click to expand...
Click to collapse
Creating a new Intent in the constructor is a really bad idea. An example from the android's developer guide
Code:
public class MainActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/** Called when the user taps the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.editText);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}