not displaying calculation in textview from editview - android

I am trying to allow people to input hypothetical new loan information in to editText fields. Upon clicking on button "Calculator" I want it to calculate the monthly payment.
Below is the code on the calculator.java page I have.
public class AddDebt extends Activity implements OnClickListener {
Button Home;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_debt);
}
This part is for my Menu to switch between my pages (Activities):
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.default_menu, menu);
MenuItem newDebt = menu.findItem(R.id.newDebt);
Intent intent1 = new Intent(this, AddDebt.class);
newDebt.setIntent(intent1);
MenuItem About = menu.findItem(R.id.about);
Intent intent2 = new Intent(this, About.class);
About.setIntent(intent2);
MenuItem Calcu = menu.findItem(R.id.Calcu);
Intent intent3 = new Intent(this, Calculator.class);
Calcu.setIntent(intent3);
MenuItem Manu = menu.findItem(R.id.manu);
Intent intent4 = new Intent(this, ManuPage.class);
Manu.setIntent(intent4);
return true;
}
I have "android:onClick="ButtonOnClick"" declared in my .xml on the Calculator button:
public void ButtonOnClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.calculate:
EditText myEdit = (EditText) findViewById(R.id.editBalance);
String myEditValue = myEdit.getText().toString();
int myEditBal = Integer.parseInt(myEditValue);
EditText myEdit2 = (EditText) findViewById(R.id.editRate);
String myEditValue2 = myEdit2.getText().toString();
int myEditRate = Integer.parseInt(myEditValue2);
EditText myEdit3 = (EditText) findViewById(R.id.editTerm);
String myEditValue3 = myEdit3.getText().toString();
int myEditTerm = Integer.parseInt(myEditValue3);
Also FYI: I know this is not a valid loan calculation, I'm using it to ensure I get a valid number:
int editMnthlypmt = myEditBal + myEditRate + myEditTerm;
TextView textMnthlypmt = new TextView(this);
textMnthlypmt.setText("" + String.valueOf(editMnthlypmt));
break;
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
I can input the data; however, it does not populate the answer in to my TextView field "textMnthlypmt". Any ideas?

textMnthlypmt.setText("" + String.valueOf(editMnthlypmt));
Try this...

check out you xml once again and
use a already declared text view
TextView textMnthlypmt = new TextView(this);
with this code you are creating a new text view but not putting it on activity.

You have created an instance of TextView but you haven't added to parentView...
try like this..
TextView textMnthlypmt = new TextView(this);
textMnthlypmt.setText("" + String.valueOf(editMnthlypmt));
parentView.addView(textMnthlypmt);//where parentView is parent layout defined in layout.activity_new_debt
Hope this helps..

Related

How to access a TextView located in a Table Layout

I made a TableLayout 3x3 in "Activity A"(Chose a Table Layout, because I thought it suits my needs)
7 of the 9 cells are clickable and open "Activity B" which is a custom number picker I made.
I used an intent to pass an array and other data to activiy B
The idea of my number picker is to set a value in the cell I just clicked in Activiy A(I wanted something like the calendarDatePicker)
In "Activity B" I have a method to update the values from "Activity A" and finish() "Activity B" when an image View is clicked wich works very fine except that it does not set the value for the clicked Text View
How can I set the TextValue from another activity when the TextValue is contained in a Table Layout?
I don't use intent, because honestly I don't know how to handle it when the "Activity B" is closed.
I mean where in "Activity A" should I handle this intent from "Activity B"
Using the debugger I found out that trying to set the text using the TextView Id does not works as it shows a "null" object in the debugger.
Activiy A
package com.example.racu.threebythree;
public class threebythree extends AppCompatActivity {
public static ArrayList<Integer> ColumnA = new ArrayList<Integer>();
public static ArrayList<Integer> ColumnB = new ArrayList<Integer>();
public static ArrayList<Integer> ColumnC = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_three_by_three);
for (int i = 1; i < 28; i++) {
if (i > 0 && i < 10)
ColumnA.add(i);
if (i > 10 && i < 19)
ColumnB.add(i);
if (i > 19 && i < 28)
ColumnC.add(i);
}
}
public void openNumberPicker(View v) {
// I used this to "guess" the location of the cell in the table layout as I could not find a way to do it.
String cellName = v.getResources().getResourceName(v.getId());
String cellLetter = cellName.substring(cellName.lastIndexOf("/") + 1);
// Send intent
Intent intent = new Intent(this, NumberPicker.class);
intent.putExtra("Id", (cellLetter.substring(0, 1) + cellLetter.substring(2)).toUpperCase());
switch (cellLetter.substring(0, 1)) {
case ("a"):
intent.putIntegerArrayListExtra("Column", ColumnA);
break;
case ("b"):
intent.putIntegerArrayListExtra("Column", ColumnB);
break;
case ("c"):
intent.putIntegerArrayListExtra("Column", ColumnC);
break;
}
intent.putExtra("Cell ID", v.getId());
startActivity(intent);
}
}
Avtivity B
package com.example.racu.threebythree;
public class NumberPicker extends AppCompatActivity {
GridView numberPicker;
ArrayList<Integer> numbersToDisplay;
TextView viewToDisplay;
ImageView ok, cancel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_number_picker);
numberPicker = (GridView) findViewById(R.id.arrayNumbers);
viewToDisplay = (TextView) findViewById(R.id.number_to_select);
ok = (ImageView) findViewById(R.id.add_number_to_card);
ok.setClickable(false);
Intent intent = getIntent();
String idFromIntent = intent.getStringExtra("Id");
numbersToDisplay = intent.getIntegerArrayListExtra("Letter");
TextView numberPosition = (TextView) findViewById(R.id.numberPosition);
numberPosition.setText(idFromIntent);
final TextView chosenNumber = (TextView) findViewById(R.id.chosenNumber);
ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this, R.layout.number_for_picker, numbersToDisplay);
numberPicker.setAdapter(adapter);
numberPicker.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
chosenNumber.setText(((TextView) v).getText());
ok.setImageResource(R.drawable.ok_blue);
ok.setClickable(true);
}
});
}
public void updateThreByThree(View v) {
Intent intent = getIntent();
int currentCell = intent.getIntExtra("Cell ID", 0);
String idFromIntent = intent.getStringExtra("Id").substring(0, 1);
TextView chosenNumber = (TextView) findViewById(R.id.chosenNumber);
// Here I try to Set the text to the cell in Activity A, using its R.id, but in the debugger I get a null reference, therefore my app crashes
TextView currentCellToEdit = (TextView) findViewById(currentCell);
currentCellToEdit.setText(chosenNumber.getText());
int temp = Integer.parseInt(chosenNumber.getText().toString());
switch (idFromIntent) {
case "A":
threebythree.ColumnA.remove(Integer.valueOf(temp));
break;
case "B":
threebythree.ColumnB.remove(Integer.valueOf(temp));
break;
case "C":
threebythree.ColumnC.remove(Integer.valueOf(temp));
break;
}
finish();
}
public void cancel(View view) {
finish();
}
}
Thanks to Pavan for the hint I found two more very helpful post here and this one was EXACTLY what I was looking for.
Like that ( make sure you give the TableLayout an id ):
TableLayout tl = (TableLayout)findViewById( R.id.tableLayout );
TextView tv = (TextView)tl.findViewById( R.id.textView );

Undo Button for a WordSearch app

I'm new to android and I'm having a hard time finding solutions to my problem on my app.
My app is a wordsearch game that uses tapping on the tiles as an input. This is the code for the onClick() of the dynamic textviews on the tablelayout:
text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
w.setVisibility(View.VISIBLE);
//change the color of tapped textview
text.setTextColor(Color.WHITE);
text.setBackgroundColor(Color.parseColor(mColors[randomNum]));
String b = text.getText().toString();
uTxt.setText(""+uTxt.getText().toString() + b);
//check if answer is in the word grid
if(checkAns(uTxt, list))
{
w.setVisibility(View.GONE);
wC.setText(String.valueOf(Integer.parseInt(wC.getText()+"")-1));
if(Integer.parseInt(wC.getText()+"") == 0){
int newM = minutes*60 + seconds;
dataHelper.insertData(pNameC.getText().toString(), newM, currentDateandTime, Category.leve);
t.cancel();
Context mContext = getApplicationContext();
Activity mActivity = GameScreen.this;
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
// Inflate the custom layout/view
View customView = inflater.inflate(R.layout.gameover,null);
// Initialize a new instance of popup window
PopupWindow mPopupWindow = new PopupWindow(
customView,
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
Typeface font = Typeface.createFromAsset(getAssets(), "raw2.ttf");
TextView cattxt = (TextView)customView.findViewById(R.id.catTxt);
String ctg = ti.getText().toString();
cattxt.setTypeface(font);
cattxt.setText(ctg);
Button yesB = (Button) customView.findViewById(R.id.maglaro2);
yesB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(GameScreen.this, Category.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
GameScreen.this.finish();
}
});
Button noB = (Button) customView.findViewById(R.id.hindi);
noB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(GameScreen.this, MainActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
GameScreen.this.finish();
}
});
mPopupWindow.showAtLocation(table, Gravity.CENTER,0,0);
}
uTxt.setText("");
}
}
});
Now my problem is I want an UNDO Button that will delete the last character on the uTxt and will change back the color of the last touched textView
Does anyone have any ideas on how to do that?
If yes leave a comment, answer, or suggestion below. TIA!
Typical solution for this problem is the usage of the command pattern (excellent for undo redo functionality).
See https://en.wikipedia.org/wiki/Command_pattern

Add a note counter to android notebook project using shared preferences

I have a notebook sample project and I want to add a "note counter" to it using shared preferences and each time the user adds a note increment the counter in createNote() method. I also added a TextView to show the counter, but the counter is always zero and doesnt increment by creating a new note! ! Help me please!
public class MainActivity extends ListActivity {
private static final int EDITOR_ACTIVITY_REQUEST = 1001;
private static final int MENU_DELETE_ID = 1002;
private int currentNoteId;
private NotesDataSource datasource;
List<NoteItem> notesList;
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
datasource = new NotesDataSource(this);
refreshDisplay();
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(""+count);
}
private void refreshDisplay() {
notesList = datasource.findAll();
ArrayAdapter<NoteItem> adapter =
new ArrayAdapter<NoteItem>(this, R.layout.list_item_layout, notesList);
setListAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_create) {
createNote(null);
}
return super.onOptionsItemSelected(item);
}
public void createNote(View v) {
NoteItem note = NoteItem.getNew();
Intent intent = new Intent(this, NoteEditorActivity.class);
intent.putExtra(NoteItem.KEY, note.getKey());
intent.putExtra(NoteItem.TEXT, note.getText());
startActivityForResult(intent, EDITOR_ACTIVITY_REQUEST);
int defaultValue = getPreferences(MODE_PRIVATE).getInt("count_key", count);
++defaultValue;
getPreferences(MODE_PRIVATE).edit().putInt("count_key", defaultValue).commit();
count = getPreferences(MODE_PRIVATE).getInt("count_key", count);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
NoteItem note = notesList.get(position);
Intent intent = new Intent(this, NoteEditorActivity.class);
intent.putExtra(NoteItem.KEY, note.getKey());
intent.putExtra(NoteItem.TEXT, note.getText());
startActivityForResult(intent, EDITOR_ACTIVITY_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == EDITOR_ACTIVITY_REQUEST && resultCode == RESULT_OK) {
NoteItem note = new NoteItem();
note.setKey(data.getStringExtra(NoteItem.KEY));
note.setText(data.getStringExtra(NoteItem.TEXT));
datasource.update(note);
refreshDisplay();
}
}
}
Your help is appreciated. Thanks!
Based on discussion and answer given by #Rahul Tiwari...do the following modifications in your code.....
First create the instance TextView variable
//your instance variables
int count;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
//your code...
tv = (TextView) findViewById(R.id.textView1);
count = getSharedPreferences("NAME_FOR_SHARED_PREFERENCES", Context.MODE_PRIVATE).getInt("count_key", 0);
updateTextView();
}
void updateTextView(){
tv.setText(""+count);
}
//your code till here....
public void createNote(View v) {
NoteItem note = NoteItem.getNew();
SharedPreferences sharedPref = getSharedPreferences("NAME_FOR_SHARED_PREFERENCES", Context.MODE_PRIVATE);
sharedPref.edit().putInt("count_key", ++count).commit();
updateTextView()
/*for intial testing commenting this code block
Intent intent = new Intent(this, NoteEditorActivity.class);
intent.putExtra(NoteItem.KEY, note.getKey());
intent.putExtra(NoteItem.TEXT, note.getText());
startActivityForResult(intent, EDITOR_ACTIVITY_REQUEST);
*/
}
//your code.
Then you can start app multiple times and check want is the count value.
Note: When naming your shared preference files, you should use a name
that's uniquely identifiable to your app, such as
"com.example.myapp.PREFERENCE_FILE_KEY" for more detail refer
your counter is not being refreshed as you are not changing text in your text view after changing the count.
you need to use
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(""+count);
at the end of your createNote function
use getDefaultSharedPreferences to access your shared preference across activities in your app. refer this answer for example.

Datepicker to parse date

What i would like is when i select a date it filters the rss feed to display the roadworks on the day that is selected. Only for now i start an intent to take me to the next activity which displays all the roadworks and not the ones on the day selected. How would i go about this?
public class ChooseDate extends Activity {
RelativeLayout rl;
Button pick;
DatePicker date;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.date_picker);
rl = (RelativeLayout) findViewById(R.id.rl);
pick = (Button) findViewById(R.id.button1);
date = new DatePicker (ChooseDate.this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams
((int) LayoutParams.WRAP_CONTENT, (int) LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.CENTER_IN_PARENT);
date.setLayoutParams(params);
rl.addView(date);
pick.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "Date is : " +
date.getDayOfMonth() + "-"+(date.getMonth()+1) +
"-"+ date.getYear(), Toast.LENGTH_SHORT).show();
startActivity(new Intent("com.mobilerwts.robert.MainActivityOther"));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
If I understand this right, you want to pass the date from the first activity to the second. If you are going to do that, you need to include it in the Intent. Basically, you have to include the data in the intent. See How do I pass data between Activities in Android application? for how to do that.

How to change background color or theme of keys dynamically in Custom Keyboard Android

I am working on Custom keyboard app I need to set or change background theme or color of keyboard .their setting.xml view in my app where user can select different background theme and different color for key rows.
during first time launch of application it is working fine but next time when custom keyboard is displaying theme is not changed.
I am using this code:
public class SoftKeyboard extends InputMethodService
implements KeyboardView.OnKeyboardActionListener {
static final boolean DEBUG = false;
/**
* This boolean indicates the optional example code for performing
* processing of hard keys in addition to regular text generation
* from on-screen interaction. It would be used for input methods that
* perform language translations (such as converting text entered on
* a QWERTY keyboard to Chinese), but may not be used for input methods
* that are primarily intended to be used for on-screen text entry.
*/
static final boolean PROCESS_HARD_KEYS = true;
private static final int SELECT_PICTURE = 101;
private KeyboardView mInputView;
private CandidateView mCandidateView;
private CompletionInfo[] mCompletions;
private Context context = SoftKeyboard.this;
private StringBuilder mComposing = new StringBuilder();
private boolean mPredictionOn;
private boolean mCompletionOn;
private int mLastDisplayWidth;
private boolean mCapsLock;
private long mLastShiftTime;
private long mMetaState;
private LatinKeyboard mSymbolsKeyboard;
private LatinKeyboard mSymbolsShiftedKeyboard;
private LatinKeyboard mQwertyKeyboard;
private LatinKeyboard mSmilyKeyboard;
private LatinKeyboard mSmilyKeyboard1;
private LatinKeyboard mCurKeyboard;
private String mWordSeparators;
/**
* Main initialization of the input method component. Be sure to call
* to super class.
*/
#Override
public void onCreate() {
super.onCreate();
mWordSeparators = getResources().getString(R.string.word_separators);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("Name","");
Log.e("SoftKeyboard - ",""+name+"OnCreate Method Called--");
if(!name.equalsIgnoreCase(""))
{
name = name+" Sethi"; /* Edit the value here*/
}
}
And This is my Setting Class where i am setting or selecting color or theme:
public class Setting extends Activity implements OnClickListener {
LinearLayout roar, edge, burst, impact, blue_theme, orange_theme,
green_theme, black_brigthness, white_brightness;
Bundle bundle;
public static boolean isblackBrightness = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.setting);
// ----------UI intilisation---------------------
uiInitilisation();
}
public void uiInitilisation() {
roar = (LinearLayout) findViewById(R.id.ror_LL);
edge = (LinearLayout) findViewById(R.id.edge_LL);
burst = (LinearLayout) findViewById(R.id.burst_LL);
impact = (LinearLayout) findViewById(R.id.impact_LL);
// -------------Themes------------------------------
blue_theme = (LinearLayout) findViewById(R.id.blue_theme_LL);
orange_theme = (LinearLayout) findViewById(R.id.orange_theme_LL);
green_theme = (LinearLayout) findViewById(R.id.green_theme_LL);
// ------------Brightness----------------------------
black_brigthness = (LinearLayout) findViewById(R.id.black_brigthness_LL);
white_brightness = (LinearLayout) findViewById(R.id.white_brigthness_LL);
// --------------On Click Events-------------------
roar.setOnClickListener(this);
edge.setOnClickListener(this);
burst.setOnClickListener(this);
impact.setOnClickListener(this);
// -----------Theme-------------------------------------
blue_theme.setOnClickListener(this);
orange_theme.setOnClickListener(this);
green_theme.setOnClickListener(this);
// ------------------Brightness--------------------------
black_brigthness.setOnClickListener(this);
white_brightness.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.ror_LL:
startActivity(new Intent(Setting.this, MainActivity.class));
break;
case R.id.edge_LL:
startActivity(new Intent(Setting.this, MainActivity.class));
break;
case R.id.burst_LL:
startActivity(new Intent(Setting.this, MainActivity.class));
break;
case R.id.impact_LL:
startActivity(new Intent(Setting.this, MainActivity.class));
break;
case R.id.blue_theme_LL:
Intent i = new Intent(Setting.this,
MainActivity.class);
i.putExtra("color", "blue");
startActivity(i);
break;
case R.id.orange_theme_LL:
Intent i2 = new Intent(Setting.this,
MainActivity.class);
i2.putExtra("color", "orange");
startActivity(i2);
break;
case R.id.green_theme_LL:
Intent i3 = new Intent(Setting.this,
MainActivity.class);
i3.putExtra("color", "green");
startActivity(i3);
break;
case R.id.black_brigthness_LL:
Intent black_britness = new Intent(Setting.this,
MainActivity.class);
black_britness.putExtra("bright", "black");
startActivity(black_britness);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name","Harneet");
editor.commit();
isblackBrightness = true ;
Log.e("Black--","Black=="+isblackBrightness);
break;
case R.id.white_brigthness_LL:
Intent white_britness = new Intent(Setting.this,
MainActivity.class);
white_britness.putExtra("bright", "white");
startActivity(white_britness);
isblackBrightness = false;
Log.e("white--","White=="+isblackBrightness);
SharedPreferences preferences1 = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor1 = preferences1.edit();
editor1.putString("Name","Arun");
editor1.commit();
break;
}
}
}
I am not getting how to do this whether I have to set widget.
When the keyboard is shown, the framework calls onStartInputView. You can program that function to look at the values of the shared preferences and set the colors/themes appropriately on the keyboard view.
Get solution to change the layout of custom keyboard.
When keyboard first time load onCreateInputView() is called. After that when keyboard open onStartInputView(EditorInfo attribute, boolean restarting) called every time.
So, now layout of keyboard(Theme) have to define in onCreateInputView() Like This
public KeyboardView mInputView;
public View onCreateInputView() {
SharedPreferences pre = getSharedPreferences("test", 1);
int theme = pre.getInt("theme", 1);
if(theme == 1)
{
this.mInputView = (KeyboardView) this.getLayoutInflater().inflate(R.layout.input, null);
}else
{
this.mInputView = (KeyboardView) this.getLayoutInflater().inflate(R.layout.input_2, null);
}
this.mInputView.setOnKeyboardActionListener(this);
this.mInputView.setKeyboard(this.mQwertyKeyboard);
return this.mInputView;
}
and do this in onStartInputView
public void onStartInputView(EditorInfo attribute, boolean restarting) {
super.onStartInputView(attribute, restarting);
setInputView(onCreateInputView());
}

Categories

Resources