I am developing a bluetooth file transfer application. In this application, I want to connect two android devices via bluetooth and transfer files. However, I am able to show all nearest device, Paired devices and able to connect with them but when I transfer images, bluetoothSocket.write() throws pipe broken exception. I have searched for solutions and refer all answers from stackoverflow and after that what I understood is that when the receiver bluetooth server socket is closed, this exception is raised but I can't get how to solve this problem. Below is my code for connecting to device and transferring images. Thanks in advance
package com.example.jayesh.bluetoothusagedemo.ConnectAsyncTask;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Parcelable;
import android.util.Log;
import android.widget.Toast;
import com.example.jayesh.bluetoothusagedemo.R;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.SocketTimeoutException;
import java.util.UUID;
/**
* Created by Jayesh on 26-01-2017.
*/
public class ConnectDevice extends AsyncTask<BluetoothDevice, Void, String> {
BluetoothSocket bluetoothSocket;
Context context;
String uuid;
OutputStream outputStream;
byte[] bytes;
public ConnectDevice(Context context,String uuid)
{
this.context = context;
this.uuid = uuid;
}
#Override
protected String doInBackground(BluetoothDevice... bluetoothDevices) {
try {
bluetoothSocket = bluetoothDevices[0].createRfcommSocketToServiceRecord(UUID.fromString(uuid));
if (bluetoothSocket != null) {
bluetoothSocket.connect();
}
} catch (SocketTimeoutException e) {
//e.printStackTrace();
Log.d("socket=======","socket timeout");
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
if(bluetoothSocket.isConnected()){
convertImageToByteArray();
try {
//Log.d("bytessize========", String.valueOf(bytes.length));
for(Byte b:bytes){
if(bluetoothSocket.isConnected()){
outputStream.write(b);
//Thread.sleep(500);
}
else{
Log.d("closed=============","true");
break;
}
//outputStream.flush();
}
//outputStream.write(bytes);
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
} //catch (InterruptedException e) {
//e.printStackTrace();
//}
}
return "completed...";
}
#Override
protected void onPostExecute(String s) {
//super.onPostExecute(s);
Toast.makeText(context, s, Toast.LENGTH_SHORT).show();
}
void convertImageToByteArray(){
try {
outputStream = bluetoothSocket.getOutputStream();
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(),R.drawable.pic1);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,100,stream);
bytes = stream.toByteArray();
Log.d("bytessize========", String.valueOf(bytes.length));
} catch (IOException e) {
e.printStackTrace();
}
}
}
Related
I am creating a little remote controller for my Android tablet. Basically I have a server that sends json containing a Youtube video ID.
In my android app I have a working background service, and I keep checking the id in a loop and whenever I get a new video id I try to pass it to the ACTION_VIEW intent. It only works once the app is launched. but whenever I send a new value, the service detects it and outputs it as log but the Youtube app doesn't get the new video.
Here is my code..
What am I missing exactly?
package com.example.testytbot;
import android.app.Activity;
import android.app.Application;
import android.app.IntentService;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.net.Uri;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.Provider;
import java.util.Timer;
import java.util.TimerTask;
import javax.net.ssl.HttpsURLConnection;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;
public class YT extends Service {
private static final String DEFAULT_EXTRA = "";
private final IBinder mBinder = new LocalBinder();
public class LocalBinder extends Binder {
YT getService() {
return YT.this;
}
}
public String oldvidID = "";
public int onStartCommand(Intent intent, int flags, int startId) {
new Timer().scheduleAtFixedRate(new TimerTask() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void run() {
String url = "https://mywebsite.com/tv/vid";
JSONObject jObject = null;
try {
jObject = new JSONObject(getJSON(url));
try {
String theId = jObject.getString("id");
//System.out.println("THE ID IIIIIIIIIIIIIIIS:::: " + theId);
if (!theId.equals("") && !oldvidID.equals(theId)) {
System.out.println("Server ID :::: " + theId);
System.out.println("\nAPP ID :::: " + theId);
Intent intent;
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube://" + theId));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
try {
getBaseContext().startActivity(intent);
} catch(ActivityNotFoundException e) {
System.out.println(e);
}
oldvidID = theId;
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, 0, 4000);
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public static String getJSON(String url) {
HttpsURLConnection con = null;
try {
URL u = new URL(url);
con = (HttpsURLConnection) u.openConnection();
con.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
return sb.toString();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (con != null) {
try {
con.disconnect();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
return null;
}
}
Thank you!
Currently, I have a server(python) and client(android). I am trying to send data from an android to server to another Android using socket. The problem is data looks fine in the server, but garbage value is included when an Android get the Data from server. If I varied the size of string, then it sometimes did not receive the data and after additional sendings, the weird garbage value was received. I think it was some kind of buffer related problem, but I could not figure out the exact problem.
This is output from server : outputFromServer
This is output from android : outputFromAndroid
This is server.py. I am getting data from a client and send it to other clients.
import socket
import time
import select
host = 'myIP' # Symbolic name meaning all available interfaces
port = myPortNumber # Arbitrary non-privileged port
server_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)#socket.SOCK_STREAM
server_sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)#assure reconnect
server_sock.bind((host, port))
server_sock.listen(5)
print(server_sock)
sockets_list = [server_sock]#socket list... multiple clients
clients = {}#socket is the key, user Data will be value
print("Waiting")
def receive_message(client_socket):
try:
data = client_socket.recv(1024)
print("receive Message : " +data.decode('utf-8'))
#return data.decode('utf-8')
return {"data" : data}
except:
return False
while True:
read_sockets, _, exception_sockets = select.select(sockets_list, [], sockets_list)#read, write ,air on
for notified_socket in read_sockets:
if notified_socket == server_sock: #someone just connected
client_socket, client_address = server_sock.accept()
print(client_socket)
print(client_address)
user = receive_message(client_socket)
if user is False:
print("USER FALSE")
continue
sockets_list.append(client_socket)
clients[client_socket] = user
print("ACCEPTED connection")
else:
message = receive_message(notified_socket)
print("IN ELSE : " + message['data'].decode('utf-8'))
if message is False :
sockets_list.remove(notified_socket)
del clients[notified_socket]
continue
user = clients[notified_socket]
#share this message with everyBody
for client_socket in clients:
print("for loop")
if client_socket != notified_socket:
message_to_send = message['data']
client_socket.send(len(message_to_send).to_bytes(2, byteorder='big'))
client_socket.send(message_to_send)
for notified_socket in exception_sockets:
sockets_list.remove(notified_socket)
del clients[notified_socket]
Here is my Android(java) code for client
package com.example.testing;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class ConnectTcp {
private String TAG = "tcp";
private DataOutputStream dos;
private DataInputStream dis;
private Socket socket;
private Thread socketThread;
public ConnectTcp() {
}//connectTcp
void sendMessage(final String message){
socketThread = new Thread() {
public void run(){
try {
if (Thread.interrupted()) { throw new InterruptedException();}
while(!Thread.currentThread().isInterrupted()) {
// ...
try {
socket = new Socket(remoteIP, port);
Log.e(TAG, "success");
}catch (IOException ioe) {
Log.e(TAG,"ERROR");
try {
dos = new DataOutputStream(socket.getOutputStream()); // output
dis = new DataInputStream(socket.getInputStream()); // inpu
dos.writeUTF("CONNECT TO SERVER : "+ message);
} catch (IOException e) {
e.printStackTrace();
}
while(true) {
try {
while (true) {
line = (String) dis.readUTF();
Log.w("------서버에서 받아온 값", "" + line);
}
} catch (Exception e) {
}
}
}
} catch (InterruptedException consumed){
/* Allow thread to exit */
}
}//run
};//Thread
socketThread.start();
}
void sendAdditionalMessage(final String data) throws IOException {
Thread sendMessageThread = new Thread() {
#Override
public void run() {
super.run();
try {
dos = new DataOutputStream(socket.getOutputStream());
dos.writeUTF(data);
} catch (IOException e) {
e.printStackTrace();
}
}
};
sendMessageThread.start();
}
void closeSocket() throws IOException {
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
socketThread.interrupt();
}
}//class
This is MainActivity.java
package com.example.testing;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Handler;
import okhttp3.FormBody;
import okhttp3.RequestBody;
public class MainActivity extends AppCompatActivity {
String getData;
TextView textView;
Button bt_connect;
Button bt_disConnect;
TextView tv_hanium;
int data = 10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt_connect = findViewById(R.id.bt_connect);
bt_disConnect = findViewById(R.id.bt_cancel);
Button bt_goToLogin = findViewById(R.id.bt_goToLogin);
final Button bt_send = findViewById(R.id.bt_send);
final ConnectTcp connectTcp = new ConnectTcp();
bt_connect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
connectTcp.sendMessage("hello world");//connect to server
}
});
bt_disConnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
connectTcp.closeSocket();//close socket
} catch (IOException e) {
Log.d("tcp", "fail to close ");
e.printStackTrace();
}
}
});//데이터 전송 중단
bt_send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
connectTcp.sendAdditionalMessage("150");// send data
} catch (IOException e) {
e.printStackTrace();
}
}
});
bt_goToLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent goToLogin = new Intent(MainActivity.this, LoginActivity.class);
MainActivity.this.startActivity(goToLogin);
}
});
}
}
The Java DataOutput.writeUTF method sends the length of the string it writes. If you don't want to modify the Java side, you have to modify your receive_message Python function to read the length field. Here's a start:
def receive_message(client_socket):
try:
data = client_socket.recv(2)
# TODO: ensure 2 bytes were returned
expected_length = int.from_bytes(data, byteorder="big")
data = client_socket.recv(expected_length)
if len(data) < expected_length:
# TODO: add a loop to read more data from the socket
pass
# TODO: write your own "modified utf-8" decoder - see
# https://docs.oracle.com/javase/8/docs/api/java/io/DataInput.html
print("receive Message : " + data.decode('utf-8'))
Java's DataOutput and DataInput are not really designed for general input/output, and they make integrating with other programming languages difficult as you've discovered. If I were you I would consider migrating to a different protocol, for example one that is based on reading and writing lines of text.
package com.example.webcontentdownload;
import androidx.appcompat.app.AppCompatActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity {
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... strings) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(strings[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while(data != -1) {
char current = (char) data;
result += result;
data = reader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
return "Failed Malformed";
} catch (IOException e) {
e.printStackTrace();
return "Failed IOException";
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadTask task = new DownloadTask();
String result = null;
try {
result = task.execute("https://www.google.com/").get();
Log.i("Contents of URL" , result);
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
**This is my code, I am trying to get the html code of any URL.
I have tried the url connection method. I tried to re-install the avd also, sometimes i get
Emulator: socketTcpLoopbackClientFor: error: fd 35124 above FD_SETSIZE (32768)
Emulator: emulator: ERROR: AdbHostServer.cpp:102: Unable to connect to adb daemon on port: 5037.
This is displayed in my EVENT LOG.
I would very much like your help **
The log I am getting is here.
Hi I want to control alarmManager time by json file
I copied this code from a blog but it did not work
and i wish someone help me to solve this problem i was tired of the many attempts and did not find the solution even if i add permission INTERNET and READ PHONE STATES Here is my code :
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mypro.json/com.mypro.json.MainActivity}: java.lang.NumberFormatException: Invalid long: ""
brodreviv.java
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.concurrent.ExecutionException;
public class brodreviv extends BroadcastReceiver {
public brodreviv() {
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_BOOT_COMPLETED.equals(action)) {
startServiceByAlarm(context);
}
}
public static void startServiceByAlarm(Context context) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, Sherlocs.class);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
long startTime = System.currentTimeMillis();
assert alarmManager != null;
final ParseJson parsejsons = new ParseJson();
try {
parsejsons.execute().get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, startTime, Long.parseLong(parsejsons.getTimer1()), pendingIntent);
}
}
Sherlocs.java
import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
public class Sherlocs extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
scheduleAlarm();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#SuppressLint("NewApi")
public void scheduleAlarm() {
final ParseJson parsejsons = new ParseJson();
try {
parsejsons.execute().get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (isAlarmWorking()) {
return;
}
((AlarmManager) Objects.requireNonNull(getSystemService(ALARM_SERVICE))).setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), Long.parseLong(parsejsons.getTimer2()), PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(getApplicationContext(), AlarmReciever.class), 0));
}
private boolean isAlarmWorking() {
boolean isWorking = false;
if (PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(getApplicationContext(), AlarmReciever.class), PendingIntent.FLAG_UPDATE_CURRENT) == null) {
isWorking = true;
}
return isWorking;
}
}
ParseJson.java
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
public class ParseJson extends AsyncTask {
private String timer1 = "";
private String timer2 = "";
#Override
protected Object doInBackground(Object... params) {
this.parse();
return this;
}
private void parse()
{
Gethttp sh = new Gethttp();
String url = "https://api.myjson.com/bins/14z1pr";
String jsonStr = sh.makeServiceCall(url);
try {
JSONObject jsonRoot = new JSONObject(jsonStr);
timer1 = jsonRoot.getString("FirstAlarm");
timer2 = jsonRoot.getString("SecondAlarm");
}
catch(Exception e)
{
Log.d("FirstAlarm : ", "exception");
Log.d("SecondAlarm : ", "exception");
}
}
public String getTimer1()
{
return timer1;
}
public String getTimer2()
{
return timer2;
}
public class Gethttp {
private final String TAG = Gethttp.class.getSimpleName();
public Gethttp() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}}
myjson.json
{
"FirstAlarm": "20000",
"SecondAlarm": "50000"
}
I am creating an android app and am trying to create a program that involves creating a folder file inside my app and being able to save it to any directory.
I would want it to be created inside my app and it should allow for as many files as the user wants to be created. How do I do that?
Here is my code:
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class Create extends Activity {
EditText textmsg;
static final int READ_BLOCK_SIZE = 100;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
textmsg=(EditText)findViewById(R.id.editText1);
}
// write text to file
public void WriteBtn(View v) {
// add-write text into file
try {
FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_PRIVATE);
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(textmsg.getText().toString());
outputWriter.close();
//display file saved message
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
// Read text from file
public void ReadBtn(View v) {
//reading text from file
try {
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[READ_BLOCK_SIZE];
String s="";
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
// char to string conversion
String readstring=String.copyValueOf(inputBuffer,0,charRead);
s +=readstring;
}
InputRead.close();
Toast.makeText(getBaseContext(), s,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Write:
// write text to file
public void WriteBtn(View v) {
// add-write text into file
try {
FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_PRIVATE);
fileout.write((textmsg.getText()).getByte())
fileout.close();
//display file saved message
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
Read:
// Read text from file
public void ReadBtn(View v) {
//reading text from file
try {
FileInputStream fileIn = openFileInput("mytextfile.txt");
byte[] reader = new byte[fileIn.available()];
if(fileIn.read(reader) != -1){
String contentFile = new String[reader];
Toast.makeText(getBaseContext(), contentFile,Toast.LENGTH_SHORT).show();
}
fileIn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
It will help you.