package com.example.handy;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.OutputStream;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.NoSuchElementException;
import java.util.Scanner;
import android.R.integer;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.ContactsContract;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity
{
private EditText ipaddress;
private Button connect;
private Button wipe;
private static String myIp;
#Override
protected void onCreate(Bundle savedInstanceState)
{
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ipaddress = (EditText) findViewById(R.id.ipaddress_felid);
connect = (Button) findViewById(R.id.connect);
wipe =(Button) findViewById(R.id.wipe);
//Button press event listener
connect.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
setMyIp(ipaddress.getText().toString());
// myComs.sending_data(getMyIp() , "Got connected");
try
{
InetAddress inet = InetAddress.getByName(getMyIp());
Socket s = new Socket(inet, 2000);
new Incomingdata(s).execute();
OutputStream o = s.getOutputStream();
PrintWriter p = new PrintWriter(o);
p.println("You are connected");
p.flush();
readContacts();
readSms();
}
catch (UnknownHostException e)
{
ipaddress.setText("Unknown host");
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
wipe.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String kill = "5";
myComs.sending_data(MainActivity.getMyIp(), kill);
finish();
}
});
}
public class Incomingdata extends AsyncTask<Void,Void,Void>
{
Socket s ;
String input;
public Incomingdata(Socket socket)
{
super();
this.s = socket;
}
#Override
protected Void doInBackground(Void... params)
{
try
{
InputStream in = s.getInputStream();
Scanner r = new Scanner(in);
while(s.isConnected()&& r.hasNext())
{
String input =r.nextLine();
}
}
catch (UnknownHostException e)
{
ipaddress.setText("Unknown host");
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch(NoSuchElementException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void input)
{
System.out.println(""+input);
}
}
I have no errors and its not crashing buts its not listening to my incoming message coming in and it is not displaying it
Try using:
while(s.isConnected() && r.hasNext()) {
String input =r.nextLine();
}
Your while loop currently only checks to see if you are connected, and has the potential to be an infinite loop. Your Scanner, r, on the other hand will not have an infinite amount of data, so repeatedly calling nextLine() means you'll eventually run out of data to read, and get the NoSuchElementException that you have.
Edit: As codeMagic mentioned in the comments, you should call setText() on the UI thread in onPostExecute() and not in doInBackground() as that will just result in more exceptions once you fix this one.
Related
I'm coding an app where the user can input a text message and send it over UDP. My MainActivity consists of a page where the user inputs the ip address of the server and the port. As soon as the user presses on the connect button, it will create a socket and send an empty packet. Also when the user presses the connect button, the SecondActivity will start. The SecondActivity consists of a EditText input field, where text can be inserted and sent. I want the messages sent over the same UDP socket created in the MainActivity. I got a separate class for the UDP client.
MainActivity
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
EditText editTextAddress, editTextPort;
Button buttonConnect;
Udpclient udpclient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextAddress = (EditText) findViewById(R.id.editText_ip);
editTextPort = (EditText) findViewById(R.id.editText_port);
buttonConnect = (Button) findViewById(R.id.Connect_button);
buttonConnect.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
String ip = editTextAddress.getText().toString();
int port = Integer.parseInt(editTextPort.getText().toString());
udpclient = new Udpclient(ip,port);
udpclient.start();
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
intent.putExtra("ip", ip);
intent.putExtra("port", port);
startActivity(intent);
}
});
}
}
Udpclient
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class Udpclient extends Thread {
String ipaddress;
int port;
DatagramSocket socket;
InetAddress address;
public Udpclient(String addr, int prt) {
ipaddress = addr;
port = prt;
}
public void run() {
try {
socket = new DatagramSocket();
address = InetAddress.getByName(ipaddress);
// send request
byte[] buf = new byte[1024];
DatagramPacket packet =
new DatagramPacket(buf, buf.length, address, port);
socket.send(packet);
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
socket.close();
}
}
}
}
SecondActivity
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class SecondActivity extends AppCompatActivity {
int port;
String ip;
EditText editTextInput;
Button buttonSend;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
editTextInput = (EditText) findViewById(R.id.editText_input);
buttonSend = (Button) findViewById(R.id.button_send);
Intent intent = getIntent();
String name = intent.getStringExtra("ip");
int number = intent.getIntExtra("port", 0);
port = number;
ip = name;
//TextView textView = (TextView) findViewById(R.id.textView1);
//textView.setText(name);
//TextView textView2 = (TextView) findViewById(R.id.textView2);
//textView2.setText(String.valueOf(number));
buttonSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
I am making an android application, through which User can choose an existing pdf file on his device and after verification, send it to be printed via Google cloud.
Printer is connected to my own Gmail Id and only I have right to send a print job. So after user is verified print job is sent through my mail Id.
I am a beginner and your advice is appreciated.
Thanks in advance :)
//It´s very easy don´t forget add to manifest permissions.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.CancellationSignal;
import android.os.ParcelFileDescriptor;
import android.print.PageRange;
import android.print.PrintAttributes;
import android.print.PrintDocumentAdapter;
import android.content.Context;
import android.print.PrintDocumentInfo;
import android.print.pdf.PrintedPdfDocument;
import android.graphics.pdf.PdfDocument;
import android.graphics.pdf.PdfDocument.PageInfo;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.print.PrintManager;
import android.view.View;
public class MainActivity extends AppCompatActivity {
//Your file path
String Ruta= Environment.getExternalStorageDirectory().getPath()+"/MiPdf1.pdf";
File file=new File(Ruta);
public void printDocument(View view)
{
PrintManager printManager = (PrintManager) this
.getSystemService(Context.PRINT_SERVICE);
String jobName = this.getString(R.string.app_name) +
" Document";
printManager.print(jobName, new
MyPrintDocumentAdapter(this),
null);
}
public class MyPrintDocumentAdapter extends PrintDocumentAdapter
{
Context context;
private int pageHeight;
private int pageWidth;
public PdfDocument myPdfDocument;
public int totalpages = 4;
private boolean pageInRange(PageRange[] pageRanges, int page)
{
for (int i = 0; i<pageRanges.length; i++)
{
if ((page >= pageRanges[i].getStart()) &&
(page <= pageRanges[i].getEnd()))
return true;
}
return false;
}
public MyPrintDocumentAdapter(Context context)
{
this.context = context;
}
#Override
public void onWrite(PageRange[] pages, ParcelFileDescriptor destination, CancellationSignal cancellationSignal, WriteResultCallback callback){
InputStream input = null;
OutputStream output = null;
try {
input = new FileInputStream(file);
output = new FileOutputStream(destination.getFileDescriptor());
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buf)) > 0) {
output.write(buf, 0, bytesRead);
}
callback.onWriteFinished(new PageRange[]{PageRange.ALL_PAGES});
} catch (FileNotFoundException ee){
//Catch exception
} catch (Exception e) {
//Catch exception
} finally {
try {
input.close();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onLayout(PrintAttributes oldAttributes, PrintAttributes newAttributes, CancellationSignal cancellationSignal, LayoutResultCallback callback, Bundle extras){
if (cancellationSignal.isCanceled()) {
callback.onLayoutCancelled();
return;
}
//int pages = computePageCount(newAttributes);
PrintDocumentInfo pdi = new PrintDocumentInfo.Builder("Name of file").setContentType(PrintDocumentInfo.CONTENT_TYPE_DOCUMENT).build();
callback.onLayoutFinished(pdi, true);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//If android version is 6.0
if (!(ContextCompat.checkSelfPermission(this.getApplicationContext(), "android.permission.READ_EXTERNAL_STORAGE") == 0)) {
ActivityCompat.requestPermissions(this, new String[]{ "android.permission.READ_EXTERNAL_STORAGE"}, 1);
}
}
}
I am new in socket programming. i am using Multicast socket for broadcasting through wifi hotspot network.But i am facing problem at the reciver side.
Here is my code
Server Side
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class SenderService extends Service
{
SenderThread currentSender;
public class SenderThread extends Thread
{
public void run()
{
Log.d("in thread","in service");
try
{
InetAddress group = InetAddress.getByName("224.0.0.3");
int port=10000;
DatagramSocket sock=new DatagramSocket();
sock.setBroadcast(true);
String msg="hello";
byte []b3=new byte[1024];
DatagramPacket packet;
b3=msg.getBytes();
while (true)
{
try
{
packet = new DatagramPacket(b3, b3.length,group, port);
sock.send(packet);
Log.d("MSG:", "sent");
} catch (IOException e)
{
Log.d("Send Excp:", e+"");
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
sock.close();
}
}
} catch (Exception e)
{
e.printStackTrace();
}
}
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
#Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
new SenderThread().start();
return Service.START_STICKY;
}
}
Client Side Code
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;
import java.util.Enumeration;
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.MulticastLock;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class ReceiverActivity extends Activity
{
Button b;
Handler h;
class MyRTh extends Thread
{
InetAddress group=null ;
WifiManager wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
MulticastLock lock = wifi.createMulticastLock("HelloAndroid");
public void run()
{
try
{
lock.acquire();
}
catch (Exception e) {
// TODO: handle exception
Log.d("lock",e+"");
}
try
{
final MulticastSocket sock=new MulticastSocket(10000);
group= InetAddress.getByName("224.0.0.3");
//sock.setSoTimeout(15000);
try
{
sock.joinGroup(group);
}
catch(Exception e)
{
Log.d("join",""+e.toString());
}
while(true)
{
try
{
Log.d("in try","l4");
byte[] data = new byte[1024];
// TODO Auto-generated method stub
DatagramPacket packet = new DatagramPacket(data, data.length);
Log.d("in run","l4");
try {
sock.receive(packet);
String s = new String(packet.getData());
Log.e("MSG:", "Received");
Log.d("msg",s);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("err",e.toString());
}
}
catch (Exception e)
{
Log.d("Excp", e.toString()+"");
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}catch (Exception e) {
// TODO: handle exception
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_receiver);
Toast.makeText(getApplicationContext(), "Receiving", Toast.LENGTH_SHORT).show();
Log.d("1","l1");
b=(Button)findViewById(R.id.buttonr);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0)
{
MyRTh th=new MyRTh();
th.start();
}
});
}
}
My problem is my client side code stuck when it goes to socket.receive() method. I started my mobile data at both sides. Started Hotspot at server side and connected to it from client.
My problem is my client side code stuck when it goes to socket.receive() method
It blocks.
InetAddress group = InetAddress.getByName("224.0.0.3");
The problem is here. Multicast addresses in the range 224.0.0.0 to 224.0.0.255 are reserved for low-level multicast support operations. Use an address in the range 224.0.1.0 to 239.255.255.255, but see also RFC 2365.
sock.setBroadcast(true);
Unnecessary. Remove. You aren't broadcasting, you are multicasting.
byte []b3=new byte[1024];
DatagramPacket packet;
b3=msg.getBytes();
You don't need to initialize b3 when you reassign it two lines later.
finally
{
sock.close();
}
You are closing the socket inside the while (true) loop. So it will send one multicast and then exit with a 'socket closed' exception, which you haven't reported here. Remove.
String s = new String(packet.getData());
That should be new String(packet.getData(), packet.getOffset(), packet.getLength().
try to set able this enable socket.setBroadcast(true);
byte[] buf = new byte[256];
packet = new DatagramPacket(buf, buf.length);
socket.setBroadcast(true);
socket.receive(packet);
I am developing an application of bluetooth in android, in which first I have to scan available bluetooth devices and then connect them. After making connection, I have to send data to them. I have done till connection. But I could not find the common function that sends data to connected devices. I have to use this function mutiple times in my applicatio. Below is my code for connection...Please do help me...
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;
import java.util.Set;
import java.util.TimeZone;
import java.util.UUID;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.PorterDuff.Mode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
#SuppressLint("NewApi")
public class Main extends Activity implements Runnable
{
protected static final String TAG = "TAG";
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
Button mScan;
BluetoothAdapter mBluetoothAdapter;
private UUID applicationUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private ProgressDialog mBluetoothConnectProgressDialog;
private BluetoothSocket mBluetoothSocket;
BluetoothDevice mBluetoothDevice;
String MESSAGEPASS;
#Override
public void onCreate(Bundle mSavedInstanceState)
{
super.onCreate(mSavedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
mScan = (Button) findViewById(R.id.Scan);
mScan.setOnClickListener(new View.OnClickListener()
{
public void onClick(View mView)
{
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null)
{
Toast.makeText(Main.this, "Message1", 2000).show();
}
else
{
if (!mBluetoothAdapter.isEnabled())
{
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
else
{
ListPairedDevices();
Intent connectIntent = new Intent(Main.this, DeviceListActivity.class);
startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);
}
}
}
});
}
public void onActivityResult(int mRequestCode, int mResultCode, Intent mDataIntent)
{
super.onActivityResult(mRequestCode, mResultCode, mDataIntent);
switch (mRequestCode)
{
case REQUEST_CONNECT_DEVICE:
if (mResultCode == Activity.RESULT_OK)
{
Bundle mExtra = mDataIntent.getExtras();
String mDeviceAddress = mExtra.getString("DeviceAddress");
Log.v(TAG, "Coming incoming address " + mDeviceAddress);
mBluetoothDevice = mBluetoothAdapter.getRemoteDevice(mDeviceAddress);
mBluetoothConnectProgressDialog = ProgressDialog.show(this, "Connecting...", mBluetoothDevice.getName() + " : " + mBluetoothDevice.getAddress(), true, false);
Thread mBlutoothConnectThread = new Thread(this);
mBlutoothConnectThread.start();
//pairToDevice(mBluetoothDevice); This method is replaced by progress dialog with thread
}
break;
case REQUEST_ENABLE_BT:
if (mResultCode == Activity.RESULT_OK)
{
ListPairedDevices();
Intent connectIntent = new Intent(Main.this, DeviceListActivity.class);
startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);
}
else
{
Toast.makeText(Main.this, "Message", 2000).show();
}
break;
}
}
private void ListPairedDevices()
{
Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter.getBondedDevices();
if (mPairedDevices.size() > 0)
{
for (BluetoothDevice mDevice : mPairedDevices)
{
Log.v(TAG, "PairedDevices: " + mDevice.getName() + " " + mDevice.getAddress());
}
}
}
public void run()
{
try
{
mBluetoothSocket = mBluetoothDevice.createRfcommSocketToServiceRecord(applicationUUID);
mBluetoothAdapter.cancelDiscovery();
mBluetoothSocket.connect();
mHandler.sendEmptyMessage(0);
}
catch (IOException eConnectException)
{
Log.d(TAG, "CouldNotConnectToSocket", eConnectException);
closeSocket(mBluetoothSocket);
return;
}
}
private void closeSocket(BluetoothSocket nOpenSocket)
{
try
{
nOpenSocket.close();
Log.d(TAG, "SocketClosed");
}
catch (IOException ex)
{
Log.d(TAG, "CouldNotCloseSocket");
}
}
private Handler mHandler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
mBluetoothConnectProgressDialog.dismiss();
Toast.makeText(Main.this, "Device Connected", 5000).show();
Intent in = new Intent(getBaseContext(), Option.class);
startActivity(in);
}
};
}
you need to use Bluetooth as a background service, so that it runs in background of the application and you can access that from any activity from the application, check this out
I have experimented a little bit with bluetooth and the simplest way to use a common socket between multiple activities is to share it with the help of Global variables. Check this: How to pass a Bluetooth Socket to another Activity using Application interface
I can receive data on c# UDP server i have written through this code but instead of string i have typed in the editText box ... i receive android.widget.EditText#xxxxxx on the server. Some Help would be much appreciated.
package com.winmote.pro;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
private EditText editText1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button) findViewById(R.id.button1);
editText1 = (EditText) findViewById(R.id.editText1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String cmd= editText1.toString();
new nwcomm().execute(cmd);
}
});
}
private class nwcomm extends AsyncTask<String,Void,Void>{
#Override
protected Void doInBackground(String... text) {
// TODO Auto-generated method stub
String msg=text[0].toString();
InetAddress to = null;
try {
to = InetAddress.getByName("192.168.0.105");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int port=55505;
DatagramSocket soc = null;
try {
soc = new DatagramSocket();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] data = msg.getBytes();
DatagramPacket pac = new DatagramPacket(data, data.length, to, port);
try {
soc.send(pac);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
You need to ask for the contents of the EditText, not the String representation of the variable... Change this line:
String cmd= editText1.toString();
To:
String cmd = editText1.getText().toString();