Retrieve text from edittext to array string in android eclipse - android

I am making text to voice conversion app. I want to take text from user and change it to voice. when i made input text hard coded. my app works perfectly.
static final String[] texts = {"what's up dude"};
TextToSpeech tts;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b = (Button)findViewById(R.id.btexttovoice);
b.setOnClickListener(this);
tts = new TextToSpeech(textvoice.this,new TextToSpeech.OnInitListener(){
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
if(status!= TextToSpeech.ERROR)
{
tts.setLanguage(Locale.US);
}
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
if(tts!= null)
{
tts.stop();
tts.shutdown();
}
super.onPause();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Random r = new Random();
String random = texts[r.nextInt(3)];
tts.speak(random, TextToSpeech.QUEUE_FLUSH, null);
}
}
it works great but if i want to take input from user through Edit text
i make the following changes:
String[] texts ;
text = (EditText)findViewById(R.id.ttexttovoice);
texts = text.getText().toString();
Here i get error since texts is the array type. How can i get text from edit text to array type of string?
if i do this without array string
String texts ;
text = (EditText)findViewById(R.id.ttexttovoice);
texts = text.getText().toString();
i get no error but i didn't find the desired output. In fact no voice is received.
it seems a simple problem but i am stuck here. kindly help me. Thanks in advance.

String[] texts = new String[3];
text = (EditText)findViewById(R.id.ttexttovoice);
texts[0] = text.getText().toString();

Related

How to split phrase into word and display corresponding image in each word?

I've already tried this codes below but it only reads word not a phrase and this codes worked and didn't meet what I want.Each word that the user input it will only add and add to an empty array-list. What I want to achieve is when an user input a phrase it will split by space and store in an empty array-list. That array-list will compare to another array-list that contains words when the condition is true it will display a corresponding image and will now read the next word in the phrase.
private List<String> wordsList;
private ArrayList<String>wordsToDisplay=new ArrayList<>();
boolean missingGIF;
int counter;
wordsList= new ArrayList(Arrays.asList(getResources().getStringArray(R.array.sample)));
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String input = editText.getText().toString();
String[]splited = input.split("//s+");
int count = splited.length;
for(int i=0;i<count;i++){
String word = splited[i];
if(wordsList.contains(word)){
wordsToDisplay.add(splited[i]);
}
else
missingGIF = true;
}
sample();
}
});
}
This is the sample method.
if(wordsToDisplay.size()>0){
counter=0;
gifImageView.setImageResource(getResources().getIdentifier(wordsToDisplay.get(0),"drawable",getPackageName()));
animation = (GifDrawable)gifImageView.getDrawable();
resetAnimation();
startAnimation();
animation.addAnimationListener(this);
}
And this is my animation listener which display corresponding images in all the words that have been inputted by the user.
#Override
public void onAnimationCompleted(int loopNumber) {
if(wordsToDisplay.size()>1){
if(counter<wordsToDisplay.size()){
try{
counter++;
gifImageView.setImageResource(getResources().getIdentifier(wordsToDisplay.get(counter),"drawable",getPackageName()));
animation = (GifDrawable)gifImageView.getDrawable();
resetAnimation();
startAnimation();
animation.addAnimationListener(this);
}
catch(IndexOutOfBoundsException e){
Log.d("Expected",e.toString());
}
}
}
}
Remove counter and use below logic
#Override
public void onAnimationCompleted(int loopNumber) {
if(!wordsToDisplay.isEmpty()){
String nextWord = wordsToDisplay.remove(0);
gifImageView.setImageResource(getResources().getIdentifier(nextWord,"drawable",getPackageName()));
animation = (GifDrawable)gifImageView.getDrawable();
resetAnimation();
startAnimation();
animation.addAnimationListener(this);
}
}

How to extract text from pdf document using MuPDF in Android

I am trying to extract text from a PDF file using MuPDF library in Android platform.
Is it possible to extract text within a rectangle specified by coordinates (left, top, right, bottom)?
Note: I didn't compile the library from source. I am using compiled libraries which is distributed in https://github.com/libreliodev/android.
yeah sure
here is the way you can do.
1.GeneratedText activity
public class GeneratedText extends Activity {
private Button close;
private Button clear;
private TextView tv;
private String data;
String text = "";
Intent i;
Context mContext;
// MuPDFPageView pdfview = new MuPDFPageView(mContext, null, null);
private EditText edit;
private Button undo;
public static GeneratedText screen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_generated_text);
close = (Button)findViewById(R.id.close);
clear = (Button)findViewById(R.id.clear);
tv = (TextView)findViewById(R.id.text1);
edit = (EditText)findViewById(R.id.edit);
undo = (Button)findViewById(R.id.undo);
undo.setEnabled(false);
i = getIntent();
data = i.getStringExtra("data");
tv.setText(data);
String mypattern = "Name and address of the Employee \n";
Pattern p = Pattern.compile(mypattern,Pattern.DOTALL);
if(data.matches(mypattern))
{
System.out.println("Start Printing name");
}
else
//do nothing
edit.setText(data);
System.out.println("hello user "+"/n"+"user1"+ "\n"+ "user2");
SharedPreferences pref = getSharedPreferences("key", 0);
SharedPreferences.Editor editor = pref.edit();
editor.putString("text", data);
editor.commit();
clear.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
tv.setText("");
edit.setText("");
undo.setEnabled(true);
}
});
close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
undo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String value = "";
SharedPreferences pref = getSharedPreferences("key", 0);
value = pref.getString("text", value);
edit.setText(value);
tv.setText(value);
undo.setEnabled(false);
}
});
}
}
1. now in mupdfactivity write this
public void Showtext( )
{
destroyAlertWaiter();
core.stopAlerts();
MuPDFPageView pdfview = new MuPDFPageView(MuPDFActivity.this, core, null);
String data = "";
pdfview.setFocusable(true);
data = pdfview.getSelectedText();
Intent i = new Intent(getApplicationContext(),GeneratedText.class);
i.putExtra("data",data);
startActivity(i);
}
call Showtext in OnAcceptButtonClick
and you will get your text.
Yes it is possible to extract text from PDF document with the help of MuPDF library. There is method called text() in mupdf.c which is defined in MuPDFCore.java which returns the text of the page. You need to call that method by page wise.
Steps:
1. gotopage(pagenumber)
2. text()

why i get invalid integer exception each time i click my button?

I have is an android class. I get some data from get extra which are displayed fine. All of the data is strings. Here is my class:
package adapter;
public class AddToCart extends Activity {
EditText quantity=null;
TextView total=null;
TextView name=null;
TextView price=null;
TextView ava=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.info);
Intent intent = getIntent();
final String itemprice = intent.getStringExtra("price");
String itemname = intent.getStringExtra("item");
final String itemava = intent.getStringExtra("ava");
int imagehandler = intent.getIntExtra("image", 0);
Log.e("image handler",imagehandler+"");
name = (TextView)findViewById(R.id.textView2);
price = (TextView)findViewById(R.id.textView4);
total = (TextView)findViewById(R.id.textView7);
ava = (TextView)findViewById(R.id.textView9);
quantity = (EditText)findViewById(R.id.editText1);
Button addtocart = (Button)findViewById(R.id.button1);
ImageView imageview=(ImageView)findViewById(R.id.imageView1);
name.setText(itemname);
price.setText(itemprice);
ava.setText(itemava);
imageview.setImageResource(imagehandler);
addtocart.setOnClickListener(new OnClickListener() {
int currentava = Integer.parseInt(itemava);
#Override
public void onClick(View v) {
try{
String checked = quantity.getText().toString();
if(checked==null) {
Toast.makeText(AddToCart.this,"please enter quantity for your item", Toast.LENGTH_LONG).show();
}
else {
int x=0;
double y=0.0;
x = Integer.parseInt(quantity.getText().toString());
y = Double.parseDouble(itemprice);
Log.e("x",x+"");
Log.e("y",y+"");
double totalprice=x*y;
total.setText(totalprice+"");
Toast.makeText(AddToCart.this,"your item added succesfully !", Toast.LENGTH_LONG).show();
}
}//view
catch(Exception e){
e.printStackTrace();
}
}
});
}
}
As you can see that quantity is edit text and when some number inserted into it multiply it by price value and show the total price in text view which works just fine when i click the button, but what I really need to do is to handle this functionality with two if statements. First if the edit text for quantity was empty and the user click the button I want a toast to be displayed to says : "please enter a value for quantity" and the other statement that if quantity larger than available to refuse the value and also toast : "please enter value less than available" It doesn't work as I have an invalid integer value exception. Please what is wrong with my code and how can i handle the previous issues?
Declare "itemava" globally and try again
Looks to me where you use ,
if(checked==null){
Toast.makeText(AddToCart.this,"please enter quantity for your item", Toast.LENGTH_LONG).show();
}
that there are 2 alternatives to this.
1.
Probably the easiest
if(checked==null || quantity.isEmpty()){
Toast.makeText(AddToCart.this,"please enter quantity for your item", Toast.LENGTH_LONG).show();
}
The addition is the || quantitiy.isEmpty()
I had tons of issues trying to solve for cases when the string was empty and this is the best way and also uses built in functions that are very easy to use.
2.
Not quite as easy but probably the better bet
Rather than checking to see if the string itself is null, it would be best to check if the editText has been changed at all, and then if it has been changed, make sure that it was changed to a non-empty string, like in 1. To do this add a textChangedListener like so:
quantity.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
//set a textChangedFlag to true
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
This will require a boolean flag that should always be initialized to false. Then after setting the flag to true in the onTextChanged method, you should still double check the string, just to be safe (this may be overkill, but I tend to error on the side of caution) by using a similar method as in 1.
if(textChangedFlag && !(checked == NULL || quantity.isEmpty())){
//do your math here
}
else{
Toast.makeText(AddToCart.this,"please enter a valid quantity", Toast.LENGTH_LONG).show();
}
Text can still be empty... Try something like this:
import android.text.TextUtils;
String value = quantity.getText().toString();
if (TextUtils.isEmpty(value)) {
// enter a value toast
} else if (!TextUtils.isDigitsOnly(value)) {
// must be numeric toast (notice the exclamation mark in condition)
} else {
int valueInt = Integer.parseInt(value);
// ...
}

can't get integer number from EditText

Hello I am very new in android
I am trying to get integer value from an EditText, But When I am parsing string to Integer I got NumberFormatException.
Please help me to come out of this error.
thanks in advance.
Program is:
int day,month,year;
EditText expense,ammount;
String[] exp=new String[10];
int[] amt=new int[10];
int count=0;
/** Called when the activity is first created. */
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Calendar cal=Calendar.getInstance();
day=cal.get(Calendar.DAY_OF_MONTH);
month=cal.get(Calendar.MONTH)+1;
year=cal.get(Calendar.YEAR);
final TextView txtdate=(TextView)findViewById(R.id.txtdate);
expense=(EditText)findViewById(R.id.exp);
ammount=(EditText)findViewById(R.id.amnt);
final Button add=(Button)findViewById(R.id.btnadd);
final Button cancel=(Button)findViewById(R.id.btncancel);
final Button done=(Button)findViewById(R.id.btndone);
txtdate.setText(day+"/"+month+"/"+year);
add.setOnClickListener(new OnClickListener() {
public void onClick(final View v) {
getval();
}
});
cancel.setOnClickListener(new OnClickListener() {
public void onClick(final View v) {
clean();
}
});
done.setOnClickListener(new OnClickListener() {
public void onClick(final View v) {
total();
getval();
clean();
final TextView tv=(TextView)findViewById(R.id.textView1);
tv.setText(Integer.toString(total()));
}
private int total() {
int total = 0;
// TODO Auto-generated method stub
for(int i=0;i<=count;i++)
{
total+=amt[i];
}
return total;
}
});
}
protected void clean() {
// TODO Auto-generated method stub
expense.setText(" ");
ammount.setText(" ");
}
protected void getval() {
// TODO Auto-generated method stub
final Editable e2=expense.getText();
final Editable e1=ammount.getText();
final int i=Integer.parseInt(e1.toString());
amt[count]=i;
exp[count]=e2.toString();
System.out.println(amt[count]);
System.out.println(exp[count]);
count++;
}
}
Exception is:
java.lang.NumberFormatException: unable to parse ' 600' as integer
Remove any leading or trailing spaces from the number first:
int inputNumber = Integer.parseInt(editText.getText().toString().trim());
Alternatively, you can remove all non-numeric characters from the string using regular expressions:
String cleanInput = editText.getText().toString().replaceAll("[^\\d]", "");
int inputNumber = Integer.parseInt(cleanInput);
Though if non-numeric input characters is a problem you'd probably want to restrict the EditText to numeric only. See this question. It says to add the following attribute to the EditText:
android:inputType="number"
You have a space in your integer.
Add the following attribute to your EditText in your xml to only allow entering integers:
android:inputType="number"
Try this..
final int i=Integer.parseInt(e1.toString().trim());
bacause there is a space before that number see ' 600' that's why that error..
Hope this will help..
use this code
final int f = -1; // or other invalid value
if (edittext.getText().toString().length() > 0)
f = Integer.parseInt(edittext.getText().toString());

Printing Stuff on Screen in Android

Ok i am developing a cows and bulls game, i am confused how to print messages to the user, i dont want to use dialogs or toasts! As far as i know, the only way is to update textviews , is that the only other option? or can i use something else to display stuff on the screen?
my code till now :
public class Play extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.play);
CowsNBulls();
}
private void CowsNBulls() {
// TODO Auto-generated method stub
int target=0;
final String targetStr = target +"";
boolean guessed= false;
final int guess;
final String Sguess;
System.out.print("Guess a 4-digit number with no duplicate digits");
EditText guess1 = (EditText)findViewById(R.id.etGuess);
Sguess=guess1.getText().toString();
Button ent = (Button) findViewById(R.id.bEnter);
guess= Integer.parseInt(Sguess);
ent.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int guesses=0;
int bulls=0;
int cows=0;
if(hasDupes(guess)||guess < 1000){
guesses++;
String guessStr = guess + "";
for(int i= 0;i < 4;i++){
if(guessStr.charAt(i) == targetStr.charAt(i)){
bulls++;
}else if(targetStr.contains(guessStr.charAt(i)+"")){
cows++;
}}}}});
any ideas?
TextView or EditText will be your only possibility. You'd have to attach it to the Layout and maybe even wrap it in a ScrollView to make room for enough statements.

Categories

Resources