I designed a custom keyboard using ImageButtons for Android (using Eclipse). I want to click on a button to write on the text, but every time I click a button, it resets the text, erasing what I previously wrote.
How can I get it to continue writing from the previous text?
This is a basic bit of my code, using two buttons and a text field.
package com.example.nonachan;
import android.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends Activity {
char g;
char h;
int i = 0;
//char buf[] = new char[10];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText t =(EditText)findViewById(R.id.t1);
ImageButton n = (ImageButton)findViewById(R.id.b1);
n.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
g = 'd';
// buf[i] = 'd';
t.setText( "" + g);
i++;
}
});
ImageButton a = (ImageButton)findViewById(R.id.b2);
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
// buf[i] = 'h';
h = 'h' ;
t.setText( "" +h);
i++;
}
});
Button l = (Button)findViewById(R.id.b3);
l.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
}
#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;
}
}
t.setText( "" + g);
The above line in your code says to set t's text to "" + g which is equal to "d". It will never append the text since you don't tell it to.
Try adding the existing text in the text field:
t.setText(t.getText().toString() + g);
And you'll have to do the same with t.setText( "" +h); as well.
Related
Hi I am a total newb to Android Development and I have been banging my head against the wall about this for weeks. Basically I have a SeekBar and I want to have it do something whenever the SeekBar moves. I tried to set up an onSeekBarChange event handler and as soon as I added that the app will not run anymore, and crashes at launch. I have looked all over the place online, and all the examples I find match my code EXACTLY, so I'm just wondering if I am putting it in the wrong place or something. Here is my entire MainActivity class file.
package com.slistersoft.scottlisterlab11;
import java.text.DecimalFormat;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends Activity {
String custName, phoneNum, carChoice;
double miles, costBeforeTip, tipPercentage, tipAmount, totalCost;
private SeekBar tipBar = null;
public void MsgBox(String message){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message)
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void showToast(String message, int durationMS){
Toast.makeText(getApplicationContext(), message, durationMS).show();
}
public void calculateCost(View v){
final EditText nameBox = (EditText)findViewById(R.id.nameBox);
final EditText phoneBox = (EditText)findViewById(R.id.phoneNumber);
final EditText milesBox = (EditText)findViewById(R.id.milesBox);
final Spinner car = (Spinner)findViewById(R.id.carPickerDropDown);
final SeekBar tipBar = (SeekBar)findViewById(R.id.tipBar);
if(nameBox.getText().toString().equals(""))
showToast("Please enter your name", 5000);
else if(phoneBox.getText().toString().equals("") )
showToast("Please enter your phone number",5000);
else if(milesBox.getText().toString().equals(""))
showToast("Please enter the amount of miles you need to travel",5000);
else{
custName = nameBox.getText().toString();
phoneNum = phoneBox.getText().toString();
miles = Double.parseDouble(milesBox.getText().toString());
carChoice = car.getSelectedItem().toString();
costBeforeTip = (3.25 * miles) + 3.00;
tipPercentage = tipBar.getProgress();
tipAmount = (tipPercentage/100) * costBeforeTip;
totalCost = costBeforeTip + tipAmount;
DecimalFormat currency = new DecimalFormat("$###,###.##");
MsgBox("Hello " + custName + ",\n\n" +
"Your estimated cost will be " + currency.format(costBeforeTip) +
"\n\nWith a " + tipPercentage + "% tip of " + currency.format(tipAmount) + " that brings your total cost to " + currency.format(totalCost) +
"\n\nA " + carChoice + " will pick you up ASAP. \n\nWe will call you at " + phoneNum + " when we are getting close. \n\nThank you for using CrAzY TaXi.");
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tipBar = (SeekBar)findViewById(R.id.tipBar);
tipBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// TODO Auto-generated method stub
}
});
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#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) {
// 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
If anybody has any ideas on this I would greatly appreciate it.
does the seekbar belong to fragment_main.xml? I am guess it does. So move initialization to onCreateView of fragment. use rootView.findViewById – Raghunandan 10 hours ago
I'm trying to write code so that when the hints option is checked in settings it should display hints, but when I do s it says there is no getContext() method defined. What will this method do and where will i have to define this ?
Here is my code for the logic of my maths app:
package com.gamesup.braingame;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Easy extends Activity implements OnClickListener{
EditText display;
// This Array says , I am an array that holds arrays
String [][] multiArray = {{"4 + 5 = ", "9"},
{"20 * 3 - 1 = ","59"},
{"99 - 9 = ","90"},
{"50 / 2 + 18 = ","43"},
{"9 * 8 = ","72"},
{"4 + 20 - 20 = ","4"},
{"75 / 5 = ","15"},
{"99 - 1 * 3 = ","96"},
{"75 + 25 = ","100"}};
TextView displayExpression;
TextView displayAnswer;
TextView setAnswer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.easy);
display = (EditText)findViewById(R.id.displayText);
display.setText("?");
displayExpression = (TextView) findViewById(R.id.expression);
displayAnswer = (TextView) findViewById(R.id.answer_status);
setAnswer = (TextView) findViewById(R.id.answer);
Button generate = (Button) findViewById(R.id.random_gen);
generate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Random ranGenerate = new Random ();
int random = ranGenerate.nextInt(multiArray.length) ;
// Fetch your random question
String Rquestion = multiArray[random][0];
displayExpression.setText(Rquestion);
displayAnswer.setText("");
setAnswer.setText("?");
}
});
}
static boolean isEmpty = true;
public void num_Clicked(View v){
Button btn = (Button) findViewById(v.getId());
//getting the button object and using a view to get the id of the buttons
if (v.getId()== R.id.del_button){
String s = display.getText().toString();
s = s.substring(0, s.length() - 1);
display.setText(s);
return;
}
if(isEmpty){
display.setText(btn.getText());
isEmpty = false;
}
else{
display.append(btn.getText().toString());
}
}
//xml attribute to views called android:onclick, that can be used to handle
//clicks directly in the view's activity without need to implement any interface.
public void hash_Clicked(View v){
// Get the Answer from your EditText
String answer = display.getText().toString();
setAnswer.setText(answer);
// Using a for loop iterate on the base index
for(int i = 0; i < multiArray.length ; i++)
{
// if the answer is in position 1 of Array [i]
if(answer.equals(multiArray[i][1]))
{
// We have found the answer, Congratulate the User
displayAnswer.setTextColor(getResources().getColor(R.color.green));
displayAnswer.setText("CORRECT");
break;
}else{
// Tell them how bad they are since they can't solve simple equations!
displayAnswer.setTextColor(getResources().getColor(R.color.red));
displayAnswer.setText("INCORRECT");
//this is where i am getting the error
if(Prefs.getHints(getContext())){
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.brain_game, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.settings:
startActivity(new Intent(this,Prefs.class));
return true;
// more items go here if any
}
return false;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
And the Prefs class:
package com.gamesup.braingame;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.os.Bundle;
import android.content.Context;
public class Prefs extends PreferenceActivity {
//option names and default values
private static final String OPT_HINTS = "hints";
private static final boolean OPT_HINTS_DEF = true;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
/**Get the current value of the hints option*/
public static boolean getHints (Context context){
return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(OPT_HINTS, OPT_HINTS_DEF);
}
}
Just use this, you already are in an Activity, which is a Context:
if(Prefs.getHints(this)){
Don't need to use other context because if you are calling that function in your Activity then you just need to pass this or yourActivityName.this which are also Context.
So change
if(Prefs.getHints(this)){
or
if(Prefs.getHints(YourActivityName.this)){
Consider:
package com.example.practicealpha;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity implements OnClickListener {
Button next,previous;
ImageView image;
Integer[] id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
id[0] = R.drawable.aa;
id[1] = R.drawable.bb;
id[2] = R.drawable.cc;
id[3] = R.drawable.dd;
next=(Button)findViewById(R.id.buttonNext);
previous=(Button)findViewById(R.id.buttonPrevious);
image=(ImageView)findViewById(R.id.imageView1);
// image.setImageDrawable(id[0]);
// image.setImageResource(id[i]);
/*
next.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v)
{
if (i<=3)
{
i++;
image.setImageResource(id[i]);
if(i==4)
next.setEnabled(false);
}
}
});
previous.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v)
{
if(i>=1)
{
i--;
image.setImageResource(id[i]);
if(i==0)
next.setEnabled(false);
}
}
});
*/
}
#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 void onClick(View v) {
// TODO Auto-generated method stub
}
}
id[0] = R.drawable.aa;
This line is causing my app to stop forcefully. How can I fix this problem?
I am trying to intialise an integer array with images id and then trying to go through the image listed in drawable folder.
Change
Integer[] id;
to
int[] id;
You have to initialize the ids for the size:
int[] id = new int[size];
You cannot use the id array directly. Initialise it first:
id[0] = R.drawable.aa;
I'm trying to start another activity in my main activity using this method:
public void switchToRead(){// Switches to the reading view which displays the text that the tts engine reads off.
Intent intent = new Intent(getApplicationContext(),ReadOut.class);
intent.putExtra("response", res);
startActivity(intent);
}
This starts the following class:
package com.example.webview;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.speech.tts.TextToSpeech;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class ReadOut extends Activity implements TextToSpeech.OnInitListener, OnClickListener {
boolean paused = false;
String leftToRead = null;
String res = null;
TextToSpeech tts;
protected void onPreExecute()
{
System.out.println("Pre-execute");
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.read_out);
Intent intent = getIntent();
res = intent.getExtras().getString("response");
TextView textv = (TextView) findViewById(R.id.textView1);
textv.setText(res);
textv.setMovementMethod(new ScrollingMovementMethod());
android.view.Display display = ((android.view.WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
textv.setHeight((int)(display.getHeight()*0.76));
System.out.println("START");
tts = new TextToSpeech(this, this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
return true;
}
public String speakFull(String text){
System.out.println("Speaking: " + text);
System.out.println("Speaking");
String[] sentences = text.split("\n|\\.(?!\\d)|(?<!\\d)\\."); // Regex that splits the body of text into the sentences of that body which are stored in a String array.
for(int i = 0; i < sentences.length; i++){
if(!tts.isSpeaking() && !paused){
System.out.println("Speaking: " + i);
tts.speak(sentences[i], TextToSpeech.QUEUE_FLUSH, null);
}else if(paused){
System.out.println("Paused");
String paused = "";
int k = 0;
if(i != 0){
k = i-1;
}
leftToRead = null;
for(int j = k; j < sentences.length; j++){
leftToRead += sentences[j];
}
return leftToRead;
}else{
i--;
System.out.println("Sleeping");
System.out.println("Speaking : " + tts.isSpeaking());
try {
Thread.sleep(1000);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
if(i == sentences.length - 1){
return "Message 001: Complete";
}
}
return null;
}
#Override
public void onInit(int arg0) {
System.out.println("speakFull");
leftToRead = speakFull(res);
}
public void clickPause(View v){
if(paused){
paused = false;
Button b = (Button) findViewById(R.id.button1);
b.setText("Play");
}else{
paused = true;
Button b = (Button) findViewById(R.id.button1);
b.setText("Pause");
if(leftToRead == null){
leftToRead = speakFull(res);
}else{
leftToRead = speakFull(leftToRead);
}
}
}
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
}
After the ReadOut class is started one of a couple things can happen,
either the screen turns black, the text to speech begins reading, and the app is telling me it's not responding, OR it shows me the view for ReadOut, reads in text to speech, and then tells me it's not responding.
I'm really confused as to why this is happening, and any insight would be appreciated.
I don't know anything about using TTS but I can tell you that this line is probably causing a problem
Thread.sleep(1000);
It appears you are calling it on the UI Thread which isn't a good idea. You need to use a background Thread and update it with something like runOnUiThread() or AsyncTask or you could use a Handler.
The code works fine it takes the contant split when there is a space and replace
what ever word the user enter to the word in V2
the problem is when i put the IF statment to check the
word the user entered it does not work whats wrong with the if ?
package com.example.split;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText te1 = (EditText)findViewById(R.id.t1);
final EditText te2 = (EditText)findViewById(R.id.t2);
final Button b = (Button)findViewById(R.id.b1);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//imva.setImageResource(R.id.b1);
String t=te1.getText().toString();
String[] t1= t.split(" ");
if (t1[0] == "hello")
{
String v1= t1[0];
String v2 = " true ";
String a = v1.replaceAll(v1, v2);
te2.setText(a);
}
}
});
}
#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;
}
}
Change
if (t1[0] == "hello"){...}
to
if (t1[0].equals("hello")){...}
1)
if (t1[0] == "hello")
don't ever compare Strings and Objects like that. That way you can compare only object references, not the contents
Java String.equals versus ==
2)
v1.replaceAll(v1, v2);
Takes first argument as a regular expression. And I doubt that is what you want.
I bet you want
v1.replace(v1, v2);
http://developer.android.com/reference/java/lang/String.html#replace%28java.lang.CharSequence,%20java.lang.CharSequence%29