getting text from EditText in android - android

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))

Related

In wireshark, I cannot see the packet I sent from android multicast socket

I follow the step here to set up a multicast server, but for some reason, I am not able to see my packet in wireshark. I am monitoring my wifi interface. Here is the code I used
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener((e) -> {
try {
boom();
} catch (Exception e1) {
e1.printStackTrace();
}
});
}
private void boom() throws Exception
{
new AsyncServer().execute("");
}
#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);
}
class AsyncServer extends AsyncTask<String, Void, Void> {
private Exception exception;
protected Void doInBackground(String... args)
{
String msg = "Hello";
InetAddress group = null;
try {
group = InetAddress.getByName("239.1.2.3");
MulticastSocket s = new MulticastSocket(4333);
// s.setInterface(InetAddress.getByName("192.168.232.2")); // To use wifi interface, but doesn't seem to be necessary. The message I will send at 75 and receive at 79 will have address 192.168.232.2
s.joinGroup(group);
DatagramPacket hi = new DatagramPacket(msg.getBytes(), msg.length(), group, 4333);
s.send(hi);
byte[] buf = new byte[1000];
DatagramPacket recv = new DatagramPacket(buf, buf.length);
s.receive(recv);
System.out.println("Received Message: " + recv.getData());
System.out.println("Send By: " + recv.getAddress());
// OK, I'm done talking - leave the group...
s.leaveGroup(group);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
}
I try something similar in a Java application and it work just fine, so I am assuming this is something wrong with android. Do you guy have any idea ?
Thank you

Android : Type mismatch: cannot convert from EditText to boolean [duplicate]

This question already has answers here:
How to use this boolean in an if statement?
(8 answers)
Closed 6 years ago.
here is my code
i try his solution but it didnt work
package com.FF_studio.psp_rd_lite_1;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends Activity {
EditText urn,pwd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
public void login(View v) {
urn = (EditText)findViewById(R.id.username);
pwd = (EditText)findViewById(R.id.password);
String site = "";
String error = "用戶名稱或密碼錯誤,請重新輸入";
String url = "";
String ans = "admin";
String ans1 = "rico1010";
urn.getText().toString();
pwd.getText().toString();
if(urn = ans) //error occur here
url = "";
else
Toast.makeText(this, error, Toast.LENGTH_SHORT).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.login, 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);
}
}
Several problems here.
urn.getText().toString();
doesn't really do anything. You need to assign a variable to it to make use of it.
String urnString = urn.getText().toString();
Second, = is an assignment operator and not a comparison operator. You would want == to compare.
Third == is not the right way to compare Strings in Java you want .equals()

i am making a note app i want to make id´s in an loop and then i want to check the id with a onclicklistener

i am trying to make a note app.in an array i want to make id´s.
i want to check the id with an onclicklistener.
in the onclicklistener i make an Intent and an ExtraString
in this Extrastring i want to write the content from the note file i created
this is the code :
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import java.util.ArrayList;
import java.util.List;
public class NotizOeffnungsMenue extends Activity implements View.OnClickListener {
Button[] NoteListBtn ;
String[] NoteList ;
int [] e;
int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notiz_oeffnungs_menue);
LinearLayout l1 = (LinearLayout)findViewById(R.id.layout1);
NoteListBtn = new Button[fileList().length];
NoteList = fileList();
i = 0;
while (i < fileList().length)
{
NoteListBtn[i] = new Button(this);
NoteListBtn[i].setText(NoteList[i]);
NoteListBtn[i].setOnClickListener(this);
l1.addView(NoteListBtn[i]);
NoteListBtn[i].setId(i);
e [i] =i;
i++;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.notiz_oeffnungs_menue, 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);
}
#Override
public void onClick(View view)
{
if(e[] == view.getId())
{
Intent switchintent = new Intent(this,NotizActivity.class);
String EXTRA_INHALT;
startActivity(switchintent);
}
}
}
In onClick() I would recommend u to use switch case statement
switch(v.getId()){
case R.id.butnid:
//do something here
break;
case R.id.butnid2:
//do something here
break;
}
Make as many cases as u want.
And remember that the buttons u use should do this
butnid.setOnClickListener(this);
butnid2.setOnClickListener(this);
//And so on for ever id u use in on click
You can use like this:
#Override
public void onClick(View view)
{
Intent switchintent = new Intent(this,NotizActivity.class);
switchintent.putExtra("EXTRA_INHALT", e[view.getId()]);
switchintent.putExtra("EXTRA_INHALT2", NoteList[view.getId()]);
startActivity(switchintent);
}
Instead of comparing id, you can use that as a position. Because you are already setting that position as Id.
Hope this helps.

split and replace

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

Don't know why condition in the for statement executing in android

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]))

Categories

Resources