Was trying to make a simple application that receives text from speech API and send it over to a java server.Tried debugging from traces. The code does not go beyond TRY block where i opened my socket.
Code Updated : Now the application is not crashing.But no message flow.
package info.androidhive.speechtotext;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Locale;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import static java.sql.DriverManager.println;
public class MainActivity extends Activity {
/**
* Declarations
*/
private TextView txtSpeechInput;
private ImageButton btnSpeak;
String str;
private final int REQ_CODE_SPEECH_INPUT = 100;
private String serverIpAddress = "";
private boolean connected = false;
TextView textIn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtSpeechInput = (TextView) findViewById(R.id.txtSpeechInput);
btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
// hide the action bar
getActionBar().hide();
btnSpeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
promptSpeechInput();
}
});
}
/**
* Showing google speech input dialog
*/
private void promptSpeechInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
getString(R.string.speech_prompt));
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
getString(R.string.speech_not_supported),
Toast.LENGTH_SHORT).show();
}
}
/**
* Receiving speech input
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtSpeechInput.setText(result.get(0));
str = result.get(0);
setContentView(R.layout.activity_main);
Log.d("1- naval", " client oncreate");
Button button = (Button) findViewById(R.id.send);
textIn = (TextView) findViewById(R.id.textin);
/**
* Setting the text box with default value
*/
textIn.setText(str);
Log.d("settext", " 2-naval");
/**
* Here we need to fill in textin from MainActivity,
* where we received the speech API text
*/
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (!connected) {
serverIpAddress = "192.168.0.4";
if (!serverIpAddress.equals("")) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
}
}
);
}
}
}
}
public class ClientThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connecting...");
Socket socket = new Socket(serverAddr, 8888);
PrintWriter out = null;
out.println(str);
connected = true;
while (connected) {
try {
Log.d("ClientActivity", "C: Sending command.");
out = new PrintWriter(
new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream())), true);
// WHERE YOU ISSUE THE COMMANDS
// out.println("Hey Server!");
Log.d("ClientActivity", "C: Sent.");
} catch (Exception e) {
Log.e("ClientActivity", "S: Error", e);
}
}
socket.close();
Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
}
}
Since, at the time of writing this answer, the author has yet to add a stacktrace I'll go over some basic solutions:
Make sure you've added INTERNET permission to your android manifest, otherwise your socket wont open <uses-permission android:name="android.permission.INTERNET" />
Open your socket on a background thread. Networking on the UI thread (eg. inside the onClick method) is prohibited on android
Add a stack trace if the above didn't solve your problem
Related
My android app was supposed to send an image to a local java server via sockets and after processing the image the result has to be sent to the app again and i am supposed to display it in the text view.I have successfully received the result but while i am trying to display the result in the text view the app crashes showing the following error.
Error: java.lang.NullPointerException: Attempt to invoke virtual method 'void java.text.BreakIterator.setText(java.lang.String)' on a null object reference
I am new to Android programming.I have tried many things but couldnt solve it.Please help me!
Thanks in advance!
Code: Main Activity
package com.example.image1;
import android.app.Activity;
import android.app.MediaRouteButton;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.Nullable;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.BreakIterator;
import java.util.Objects;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
private static final int SELECT_PICTURE = 1;
private static final int GET_PICTURE =1 ;
private PrintWriter printwriter;
public static String selectedImagePath;
public static String selectedImageUri;
private ImageView img;
public static String st;
TextView status1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
System.out.println("34");
img = (ImageView) findViewById(R.id.ivPic);
System.out.println("36");
Button send = (Button) findViewById(R.id.bSend);
//status = (TextView) findViewById(R.id.tvStatus);
status1 = (TextView) findViewById(R.id.result);
((Button) findViewById(R.id.bBrowse))
.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
System.out.println("40");
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select Picture"),
SELECT_PICTURE);
System.out.println("47");
}
});
;
System.out.println("51");
//status1.setText("fjfjf");
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
//status1.setText("fjfjf");
new SendImageTask().execute();
//final TextView status1 = (TextView) findViewById(R.id.result);
//status1.setText(s);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
TextView path = (TextView) findViewById(R.id.tvPath);
path.setText("Image Path : " + selectedImagePath);
img.setImageURI(selectedImageUri);
}
}
}
public String getPath(Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(projection[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
return filePath;
}
}
SendImageTask code
package com.example.image1;
import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Base64;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.BreakIterator;
class SendImageTask extends AsyncTask<Void, Void, String> {
private PrintWriter printwriter;
private Bitmap IOUtils;
private BreakIterator status1;
private static String st;
#SuppressLint("WrongThread")
#Override
protected String doInBackground(Void... voids) {
Socket sock;
try {
sock = new Socket("192.168.43.120", 8000);
System.out.println("Connecting...");
System.out.println("Sending...");
String s = getFileToByte(MainActivity.selectedImagePath);
System.out.println(s);
printwriter = new PrintWriter(sock.getOutputStream(), true);
printwriter.write(String.valueOf(s)); // write the message to output stream
printwriter.flush();
printwriter.close();
sock.close();
try {
System.out.println("Another socket");
Socket sock1 = new Socket("192.168.43.120", 6000);
System.out.println("Connecting1...");
InputStreamReader streamReader = new InputStreamReader(sock1.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
st = reader.readLine();
System.out.println(st);
System.out.println("ascscasc");
sock1.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return st;
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return st;
}
protected void onPostExecute(String st){
System.out.println("asasdcwdcwdc");
System.out.println(st);
status1.setText(String.valueOf(st));
}
public static String getFileToByte(String filePath){
Bitmap bmp = null;
ByteArrayOutputStream bos = null;
byte[] bt = null;
String encodeString = null;
try{
bmp = BitmapFactory.decodeFile(filePath);
bos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, bos);
bt = bos.toByteArray();
encodeString = Base64.encodeToString(bt, Base64.DEFAULT);
}
catch (Exception e){
e.printStackTrace();
}
String str1=encodeString.replaceAll("[\r\n]+", " ");
str1 = str1.replaceAll("\\s+","");
return "data:image/jpeg;base64,"+str1+"/n";
}
}
First my app was crashing because i was doing the textView operation in the doInBackground method and then after only i learnt that ui operations cant be done there. So then i executed those commands in onPostExecute method.But still my app is crashing saying NullPointerException.I will also include the logcat here.Thanks in advance.
Logcat:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.image1, PID: 20241
java.lang.NullPointerException: Attempt to invoke virtual method 'void java.text.BreakIterator.setText(java.lang.String)' on a null object reference
at com.example.image1.SendImageTask.onPostExecute(SendImageTask.java:147)
at com.example.image1.SendImageTask.onPostExecute(SendImageTask.java:19)
at android.os.AsyncTask.finish(AsyncTask.java:667)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:684)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:186)
at android.app.ActivityThread.main(ActivityThread.java:6509)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:914)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:804)
I/Process: Sending signal. PID: 20241 SIG: 9
You need to initialize your BreakIterator object status1 otherwise it would be null.
I've not used BreakIterator, but a quick look at the docs shows that this is how you get an instance.
BreakIterator status1 = BreakIterator.getWordInstance();
Bottom line is to initialize it before using it.
I'm trying to develop my first app in Android Studio and connect it to a server in python. I wrote a Client class and MainActivity with java in Android Studio and I wrote the Server in Pycharm. When I create a client object in different class, the connection between the client and the server works fine. However, when i do the same thing in the MainActivity it doesnt work and i get this error:
" E/m.example.mage: Unknown bits set in runtime_flags: 0x8000 ".
Do i need to do something else or is there a way to fix it?
package com.example.magen;
import android.widget.TextView;
import java.util.*;
import java.net.*;
import java.io.*;
public class Client {
private Socket clientSocket;
private PrintWriter out;
private BufferedReader in;
public void startConnection(String ip, int port) {
try {
clientSocket = new Socket(ip, port);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("connected to server");
}
catch(Exception e){
System.out.println("error 1 " + e.getMessage());
}
}
public String sendMessage(String msg) {
String resp="";
try {
out.println(msg);
System.out.println("client: "+msg);
resp = in.readLine();
}
catch(Exception e){
System.out.println("error 2 " + e.getMessage());
}
return resp;
}
public void stopConnection() {
try {
in.close();
out.close();
clientSocket.close();
}
catch(Exception e){
System.out.println("error 3 " + e.getMessage());
}
}
}
import socket
import select
import datetime
server_socket = socket.socket()
server_socket.bind(('0.0.0.0', 6969))
server_socket.listen(10)
open_client_sockets = []
def main():
while True:
rlist, wlist, xlist = select.select([server_socket]+open_client_sockets, open_client_sockets, [])
for current_socket in rlist:
if current_socket is server_socket:
(new_socket, address) = server_socket.accept()
open_client_sockets.append(new_socket)
else:
full_msg = current_socket.recv(1024).decode()
print(full_msg)
current_socket.send("hi".encode())
...
...
...
...
...
if __name__ == '__main__':
main()
package com.example.magen;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private EditText username;
private EditText password;
private Button loginButton;
private Button registerButton;
private TextView tvInfo;
private Client client = new Client();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText)findViewById(R.id.etUsername);
password = (EditText)findViewById(R.id.etPassword);
loginButton = (Button)findViewById(R.id.loginButton);
registerButton = (Button)findViewById(R.id.registerButton);
tvInfo = (TextView)findViewById(R.id.tvInfo);
connectToServer(client);
registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, ThirdActivity.class);
startActivity(intent);
}
});
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validate(username.getText().toString(), password.getText().toString(),tvInfo);
}
});
}
private void connectToServer(Client client){
client.startConnection("127.0.0.1", 6969);
String resp = client.sendMessage("hello");
tvInfo.setText(resp);
}
private void validate(String name, String password, TextView tvInfo){
if(name.equals("king_mageni") && password.equals("123456789")){
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("username",name);
startActivity(intent);
}
else{
String errorMassage = "Incorrect username or password!";
tvInfo.setText(errorMassage);
}
}
}
I am currently trying to send a message from my app to my internal SQL server. Currently, I get an IOException through the connection.getOutputStream () statement. I have used the same code for a hosting service and everything works fine.
I've already made my SQL server externally accessible using DNS and port forwarding, but I still get an IOException. Maybe someone can help me out. The internal server is a Raspberry Pi that was set up using Apache2.
package com.example.myapplication;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
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;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import static android.widget.Toast.*;
public class MainActivity extends AppCompatActivity {
EditText et;
Button btn;
TextView tv;
final String scripturlstring = "hostingservice.net";
//final String scripturlstring = "192.168.178.97:80/index.php"; // Ip adress raspberry pi
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.editText);
tv = (TextView) findViewById(R.id.textView);
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(internetAvailable()){
sendToServer(et.getText().toString());
}else{
makeText(getApplicationContext(), "Internet ist nicht Verfügbar", LENGTH_SHORT).show();
}
}
});
}
public void sendToServer(final String text){
new Thread(new Runnable() {
#Override
public void run() {
try {
String textparam = "text1=" + URLEncoder.encode(text, "UTF-8");
tv.setText(textparam);
URL scripturl = new URL(scripturlstring);
HttpURLConnection connection = (HttpURLConnection) scripturl.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setFixedLengthStreamingMode(textparam.getBytes().length);
// Problem entsteht beim connection.getOutputStream
OutputStreamWriter contentWriter;
contentWriter = new OutputStreamWriter(connection.getOutputStream());
contentWriter.write(textparam);
contentWriter.flush();
contentWriter.close();
InputStream answerInputStream = connection.getInputStream();
final String answer = getTextFromInputStream(answerInputStream);
runOnUiThread(new Runnable() {
#Override
public void run() {
//Toast.makeText(getApplicationContext(), "noThread", Toast.LENGTH_SHORT).show();
tv.setText(answer);
}
});
answerInputStream.close();
connection.disconnect();
connection.close();
}catch (MalformedURLException e){
e.printStackTrace();
tv.setText("Pi hat probleme mit dem MalformedUrlException");
}catch(IOException e){
tv.setText("Pi hat probleme mit dem IOexception");
//System.err.println("Error creating HTTP connection");
e.printStackTrace();
}
}
}).start();
}
public String getTextFromInputStream (InputStream is){
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder stringBuilder = new StringBuilder();
try {
String aktuellZeile;
while((aktuellZeile = reader.readLine()) != null){
stringBuilder.append(aktuellZeile);
stringBuilder.append("\n");
}
}catch (IOException e){
e.printStackTrace();
}
return stringBuilder.toString().trim();
}
public boolean internetAvailable(){
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
}
Surely you havent added this :-
P.S :- Most of the timeI0Exception is for internet connectivity.
Please do add
<uses-permission android:name="android.permission.INTERNET" />
in AndroidManifest.xml
I see no other reason for I0Exception .
Also , in onDestory(...) stop the thread .. else you will get another exception. ( if the thread is still running )
import android.annotation.TargetApi;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
#TargetApi(18)
public class MainActivity extends AppCompatActivity{
`int b = 0;
BluetoothAdapter BA = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device;
BluetoothSocket BS;
BluetoothServerSocket server;
UUID uuid = UUID.fromString("f63b93f5-56e0-47bb-8972-996e34cfb9a8");`
`#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);`
`Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(i);`
`Accept accept = new Accept();
accept.start();`
Set<BluetoothDevice> devices = BA.getBondedDevices();
for(BluetoothDevice bt : devices) {
try {
if (bt.getName().equals("Overlord")) {
device = BA.getRemoteDevice(bt.getAddress());
BS = device.createRfcommSocketToServiceRecord(uuid);
} else if (bt.getName().equals("Huawei Y5")) {
device = BA.getRemoteDevice(bt.getAddress());
BS = device.createRfcommSocketToServiceRecord(uuid);
}
}catch(IOException IOE){}
}
}
public interface MessageContents{
int MSG_MESSAGE = 0;
}
Handler handler = new Handler(){
public void handleMessage(Message msg) {
TextView tx = (TextView)findViewById(R.id.textView2);
switch(msg.what){
case MessageContents.MSG_MESSAGE:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
Log.d("TAG", readMessage);
tx.setText(readMessage);
break;
default:
tx.setText("No text");
}
}
};
class Connect extends Thread{
public void run(){
try {
try {
BS.connect();
Log.d("LOG", " e");
Log.d("LOG", "r" + BS.isConnected());
DataTransfer dataTransfer = new DataTransfer();
dataTransfer.start();
}catch(NullPointerException e){
Log.d("LOG", " meezaan");
}
}catch(IOException e){
Log.d("LOG", "t");
}
}
}
class Accept extends Thread{
public void run() {
try {
while (true) {
server = BA.listenUsingRfcommWithServiceRecord("Secure Connection", uuid);
server.accept();
Log.d("LOG", "accept");
}
}catch(IOException E) {
}
}
}
class DataTransfer extends Thread{
#Override
public void run() {
int d = 1;
InputStream receive = null;
Log.d("LOG", "On");
int numBytes;
byte[] buffer = new byte[1024];
try {
receive = BS.getInputStream();
Log.d("LOG", "pn");
while (BS.isConnected()) {
try {
if (d <= 5) {
Log.d("LOG", "did");
++d;
}
numBytes = receive.read(buffer);
handler.obtainMessage(MessageContents.MSG_MESSAGE, numBytes, -1, buffer).sendToTarget();
} catch (NullPointerException e) {
Log.d("LOG", "error read(null)");
}
}
Log.d("LOG", "pnA");
} catch (IOException IOE) {
Log.d("LOG", "error read(IOE)");
}
}
}
public void onOne(View view){
write("1".getBytes());
}
public void onClick(View view){
Button b1 = (Button) findViewById(R.id.button);
EditText pin = (EditText) findViewById(R.id.editText);
pin.setRawInputType(Configuration.KEYBOARD_QWERTY);
pin.setVisibility(View.VISIBLE);
b1.setVisibility(View.VISIBLE);
}
public void pin (View view) {
Button b1 = (Button)findViewById(R.id.button);
EditText pin = (EditText)findViewById(R.id.editText);
String pin1 = pin.getText().toString();
if (pin1.equals("")) {
Connect connect = new Connect();
connect.run();
pin.setVisibility(View.INVISIBLE);
b1.setVisibility(View.INVISIBLE);
} else {
Toast.makeText(getApplicationContext(), "Wrong Pin!"+pin1, Toast.LENGTH_SHORT).show();
pin.setVisibility(View.INVISIBLE);
b1.setVisibility(View.INVISIBLE);
}
}
public void onTwo(View v){
Toast.makeText(getApplicationContext(), "" + handler.hasMessages(MessageContents.MSG_MESSAGE) + " " + BS.isConnected(), Toast.LENGTH_SHORT).show();
}
public void write(byte[] Byte){
try {
OutputStream transfer = BS.getOutputStream();
try {
transfer.write(Byte);
}catch(NullPointerException e){
Log.d("LOG", "error write(null) " + BS.isConnected());}
}catch (IOException IOE){ Log.d("LOG", "b");
Log.d("LOG", "error write(IOE) " + BS.isConnected());}
}
}`
Hi, this is my code. After writing Bytes[] I don't receive anything on second device. When I remove 'numBytes = receive.read(buffer)' handler would work or display
'no text'
I think receive.read(buffer) waits for an input which means write is a problem or receive.read(buffer) is the problem. Please ignore names, logs with random letters in or device names or unnecessary imports or variables. Thank You :) Sorry I did not have time to indent everything. If you are viewing please put something like don't know.Thank you.
Hello I am new to Android. I want to communicate android with pc to send a text file.
I am trying to communicate using following code.
I am using bluetooth dongle to pc.
When i run application it get crashed without any error. Please help me in communication.
enter code here
package com.exam.bluetooth2;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
import android.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
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;
#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.activity_list_item);
mScan = (Button) findViewById(R.id.button1);
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();
Toast.makeText(getBaseContext(), mBluetoothDevice.getAddress(), 10000).show();
//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());
}
}
// Object device = null;
// String dv = device.toString();
// if(dv.contains("00:1B:EE:82:31:1E"))
// {
// mBluetoothDevice = (BluetoothDevice) device;
// }
}
public void run()
{
try
{
mBluetoothSocket = mBluetoothDevice.createRfcommSocketToServiceRecord(applicationUUID);
mBluetoothAdapter.cancelDiscovery();
mBluetoothSocket.connect();
mHandler.sendEmptyMessage(0);
String messsage = "Welcome to SmarTec";
byte[] tosend=messsage.getBytes();
OutputStream out=mBluetoothSocket.getOutputStream();
out.write(tosend);
}
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);
}
};
/* public void sendtext(View v) {//button click
Set<BluetoothDevice> bd = mBluetoothAdapter.getBondedDevices();
sendDataToPairedDevice("message1");
}
private void sendDataToPairedDevice(String message ){
byte[] toSend = message.getBytes();
try {
UUID applicationUUID = UUID.fromString("8ce255c0-200a-11e0-ac64- 0800200c9a66");
BluetoothSocket socket = mBluetoothDevice.createInsecureRfcommSocketToServiceRecord(applicationUUID);
OutputStream mmOutStream = socket.getOutputStream();
mmOutStream.write(toSend);
} catch (IOException e) {
Log.e( "Exception during write", e.toString());
}
}
*/
}
enter code here
package com.exam.bluetooth2;
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class DeviceListActivity extends Activity
{
protected static final String TAG = "TAG";
private BluetoothAdapter mBluetoothAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
#Override
protected void onCreate(Bundle mSavedInstanceState)
{
super.onCreate(mSavedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.device_list);
setResult(Activity.RESULT_CANCELED);
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
ListView mPairedListView = (ListView) findViewById(R.id.paired_devices);
mPairedListView.setAdapter(mPairedDevicesArrayAdapter);
mPairedListView.setOnItemClickListener(mDeviceClickListener);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter.getBondedDevices();
if (mPairedDevices.size() > 0)
{
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice mDevice : mPairedDevices)
{
mPairedDevicesArrayAdapter.add(mDevice.getName() + "\n" + mDevice.getAddress());
}
}
else
{
String mNoDevices = getResources().getText(R.string.none_paired).toString();
mPairedDevicesArrayAdapter.add(mNoDevices);
}
}
#Override
protected void onDestroy()
{
super.onDestroy();
if (mBluetoothAdapter != null)
{
mBluetoothAdapter.cancelDiscovery();
}
}
private OnItemClickListener mDeviceClickListener = new OnItemClickListener()
{
public void onItemClick(AdapterView<?> mAdapterView, View mView, int mPosition, long mLong)
{
mBluetoothAdapter.cancelDiscovery();
String mDeviceInfo = ((TextView) mView).getText().toString();
String mDeviceAddress = mDeviceInfo.substring(mDeviceInfo.length() - 17);
Log.v(TAG, "Device_Address " + mDeviceAddress);
Bundle mBundle = new Bundle();
mBundle.putString("DeviceAddress", mDeviceAddress);
Intent mBackIntent = new Intent();
mBackIntent.putExtras(mBundle);
setResult(Activity.RESULT_OK, mBackIntent);
finish();
}
};
}
Vijay,
You need to check few thinks below:
Add bluetooth permission in manifest file.
If device is not supporting bluetooth, then you get bluetooth adapter value null. So need to check that also.
Also its better to create broadcast receiver with bluetooth actions.