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
Related
I have written this code for searching a text file for a string. The problem is, it says that the string is not found even if it is present. Process is to receive the text from the EditText and then start the searching process. But it shows that string is found every time.
package com.example.demo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import android.content.Context;
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.EditText;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button;
final EditText obedittext;
button =(Button)findViewById(R.id.button1);
obedittext =(EditText)findViewById(R.id.editText1);
button.setOnClickListener(
new View.OnClickListener()
{
boolean textfound;
public void onClick(View view)
{
textfound = searchtext(obedittext.getText().toString());
if(textfound)
maketoast(obedittext.getText().toString());
else
maketoast("Unsuccessfull");
}
});
}
protected boolean searchtext(String string) {
// TODO Auto-generated method stub
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new InputStreamReader(getAssets().open("mneumo.txt")));
while ((sCurrentLine = br.readLine()) != null) {
if(sCurrentLine.equals(string)) {
return true;
}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
finally{
}
return false;
}
private void maketoast(String string) {
// TODO Auto-generated method stub
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, string , Toast.LENGTH_SHORT);
toast.show();
}
#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);
}
}
So when i tried to give the string inside the code itself instead of getting it from the edittext,it works fine. Like this,
string = "SPINAL ANESTHESIA AGENTS";
The sample text file is,
SPINAL ANESTHESIA AGENTS
XYLOCAINE: WHERE NOT TO USE WITH EPINEPHRINE
GENERAL ANAESTHESIA: EQUIPMENT CHECK PRIOR TO INDUCING
So how can i rectify this problem? Can anyone say why i am getting this problem?
Should i any other method to compare the strings?
The text file is correctly placed in the assets folder. And i accessed it using the assetmanager. And i am a total newbie to android development.
May be your editText contain some white space already, To get text from your editText try this:
obedittext.getText().toString().trim();
and inside your searchtext() method, replace your if condition with:
if(sCurrentLine.equalsIgnoreCase(string))
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)){
I am new to android. I am stuck with the spinner. There are two spinner item "FROM" and "TO".
I want to code as..if I want to search FROM Place1, To Place2. Then after clicking button, if condition matches, it should redirect to another page.
While running app, I am not getting any error, and no response comes out of clicking button.
Please see the below code. I have tried this thing by 3 way (*in comments), none of them gives desired output.
package com.aricent.aricentgroupapps;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Spinner;
public class SelectLocation extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_location);
Button route = (Button) findViewById(R.id.RouteButton);
final Spinner spin1 = (Spinner) findViewById(R.id.fromdropdrown);
final Spinner spin2 = (Spinner) findViewById(R.id.todropdrown);
route.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String str1 = spin1.getSelectedItem().toString();
String str2 = spin2.getSelectedItem().toString();
String plot31= "Plot 31";
String plot314= "Plot 314";
/* if(String.valueOf(spin1.getSelectedItem())== "Plot 17" && String.valueOf(spin2.getSelectedItem())== "Plot 16")
{
Intent i = new Intent(SelectLocation.this, Route1.class);
startActivity(i);
}
if (spin1.equals("Plot 17") && spin2.equals("Plot 16"))
{
Intent i = new Intent(SelectLocation.this, Route1.class);
startActivity(i);
}
*/
if (str1== plot31 && str2==plot314)
{
Intent i = new Intent(SelectLocation.this, Route1.class);
startActivity(i);
}
}
});
}
protected String valueOf(Object selectedItem) {
// TODO Auto-generated method stub
return getString(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.select_location, menu);
return true;
}
}
use this one
spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> main, View view, int position,
long Id) {
if(position==0){
//your code
}
if(position==1){
//your code
}
}
}
use this-
if(str1.equals("plot16")&&str2.equals("plot17")){
//do functionality
}
if (str1.equals( plot31) && str2.equals(plot314))
{
Intent i = new Intent(SelectLocation.this, Route1.class);
startActivity(i);
}
try this. == is used to compare the references whereas equals() method is used to compare values.
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.
on clicking the button the 'x' value is storing in array[0][0]. But in the check method both if statements in the for loop are exicuting , i don't know why the conditions are exicuting.
So i put a dialogue box in the if statement, while i am giving the array[0][0] to setMessage
it printing "x", But if i am giving the array[i][j] it printing the null value even both i and j values are zero.
i don't know what is the problem.
package com.example.tictactoe3;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.app.AlertDialog;
public class MainActivity extends Activity {
String array[][]=new String[3][3];
void check(String array[][])
{
int i=0,j=0;
for(i=0;i<3;i++)
{
for(j=0;j<1;j++)
{
if(array[i][j]==array[i][j+1])
{
if(array[i][j]==array[i][j+2])
{
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
dlgAlert.setMessage(array[0][0]);
dlgAlert.setTitle("Tic Tac Toe");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
}
}
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button bt1= (Button) findViewById(R.id.button1);
bt1.setOnClickListener(new View.OnClickListener() {
boolean value=true;
public void onClick(View v) {
// TODO Auto-generated method stub
bt1.setText("x");
array[0][0]="x";
check(array);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
For strings, you should compare using
if (strOne.equals(strTwo))
or
if (strOne.equalsIgnoreCase(strTwo))
Not using "==" operator
So replace
if(array[i][j]==array[i][j+1])
with
if(array[i][j].equalsIgnoreCae(array[i][j+1]))
and
if(array[i][j]==array[i][j+2])
with
if(array[i][j].equalsIgnoreCase(array[i][j+2]))