I am a beginner in android development and I get an error that I can not solve a few days ago with the doInBackground() method.
My error is at the end of my code, at
e2 = e11;
createInsecureRfcommSocketToServiceRecord = null;
this.sender = e2.getMessage();
createInsecureRfcommSocketToServiceRecord.close();
The error is
Unhandled exception:java.io.IO.EXCEPTION
If you have solutions , thank you in advance!
My code :
protected Object doInBackground(Object[] objArr) {
BluetoothSocket createInsecureRfcommSocketToServiceRecord;
IOException e;
Throwable th;
IButton a;
Boolean valueOf;
boolean z = true;
this.jobType = (JobType) objArr[0];
this.sender = (MainActivity) objArr[1];
this.device = (BluetoothDevice) objArr[2];
try {
createInsecureRfcommSocketToServiceRecord =
device.createInsecureRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
try {
createInsecureRfcommSocketToServiceRecord.connect();
} catch (IOException e2) {
Log.e("Bluetooth", e2.getMessage());
Log.e("Bluetooth", "trying fallback");
try {
createInsecureRfcommSocketToServiceRecord = (BluetoothSocket)
this.device.getClass().getMethod("createInsecureRfcommSocket", new Class[]{Integer.TYPE}).invoke(this.device, new Object[]{Integer.valueOf(1)});
} catch (Exception e3) {
Log.e("Bluetooth", e3.getMessage());
}
try {
createInsecureRfcommSocketToServiceRecord.connect();
} catch (IOException e4) {
e2 = e4;
try {
this.error = e2.getMessage();
try {
createInsecureRfcommSocketToServiceRecord.close();
} catch (IOException e5) {
}
return null;
} catch (Throwable th2) {
th = th2;
try {
createInsecureRfcommSocketToServiceRecord.close();
} catch (IOException e6) {
}
throw th;
}
}
}
if (this.jobType == JobType.read) {
a = readDevice(createInsecureRfcommSocketToServiceRecord);
try {
createInsecureRfcommSocketToServiceRecord.close();
return a;
} catch (IOException e7) {
return a;
}
} else
if (this.jobType == JobType.stopMission) {
a = (IButton) objArr[3];
if (!(stopMission(createInsecureRfcommSocketToServiceRecord) &&
writeDevice(createInsecureRfcommSocketToServiceRecord, a))) {
z = false;
}
valueOf = Boolean.valueOf(z);
try {
createInsecureRfcommSocketToServiceRecord.close();
return valueOf;
} catch (IOException e8) {
return valueOf;
}
} else
if (this.jobType == JobType.startMission) {
boolean z2 = writeDevice(createInsecureRfcommSocketToServiceRecord, (IButton) objArr[3]) &&
startMission(createInsecureRfcommSocketToServiceRecord);
valueOf = Boolean.valueOf(z2);
try {
createInsecureRfcommSocketToServiceRecord.close();
return valueOf;
} catch (IOException e9) {
return valueOf;
}
} else {
try {
createInsecureRfcommSocketToServiceRecord.close();
} catch (IOException e10) {
}
return null;
}
} catch (IOException e11) {
e2 = e11;
createInsecureRfcommSocketToServiceRecord = null;
this.sender = e2.getMessage();
createInsecureRfcommSocketToServiceRecord.close();
return null;
} catch (Throwable th3) {
th = th3;
createInsecureRfcommSocketToServiceRecord = null;
createInsecureRfcommSocketToServiceRecord.close();
throw th;
}
return null;
}
close() also throws an IOException exception you need to handle. Additionally you should use a finally block for cleaning up and be careful not to provoke NullPointerExeptions by setting the variable to null before closing it.
You could improve your code like
try {
....
} catch (Exception e) {
....
} finally {
try {
createInsecureRfcommSocketToServiceRecord.close();
createInsecureRfcommSocketToServiceRecord = null;
} catch (IOException e) {
}
}
I'm modify my code with this but i'm a java.lang.NullPointerException...
The fonction doInBackground() is very difficult...
Thank's for your help !
My code modify
protected Object doInBackground(Object[] objArr) {
BluetoothSocket createInsecureRfcommSocketToServiceRecord = null;
IOException e;
Throwable th;
IButton a;
Boolean valueOf;
boolean z = true;
this.jobType = (JobType) objArr[0];
this.sender = (MainActivity) objArr[1];
this.device = (BluetoothDevice) objArr[2];
try {
createInsecureRfcommSocketToServiceRecord =
device.createInsecureRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));
try {
createInsecureRfcommSocketToServiceRecord.connect();
} catch (IOException e2) {
Log.e("Bluetooth", e2.getMessage());
Log.e("Bluetooth", "trying fallback");
try {
createInsecureRfcommSocketToServiceRecord = (BluetoothSocket)
this.device.getClass().getMethod("createInsecureRfcommSocket", new Class[]{Integer.TYPE}).invoke(this.device, new Object[]{Integer.valueOf(1)});
} catch (Exception e3) {
Log.e("Bluetooth", e3.getMessage());
}
try {
createInsecureRfcommSocketToServiceRecord.connect();
} catch (IOException e4) {
e2 = e4;
try {
this.error = e2.getMessage();
try {
createInsecureRfcommSocketToServiceRecord.close();
} catch (IOException e5) {
}
return null;
} catch (Throwable th2) {
th = th2;
try {
createInsecureRfcommSocketToServiceRecord.close();
} catch (IOException e6) {
}
throw th;
}
}
}
if (this.jobType == JobType.read) {
a = readDevice(createInsecureRfcommSocketToServiceRecord);
try {
createInsecureRfcommSocketToServiceRecord.close();
return a;
} catch (IOException e7) {
return a;
}
} else if (this.jobType == JobType.stopMission) {
a = (IButton) objArr[3];
if (!(stopMission(createInsecureRfcommSocketToServiceRecord) &&
writeDevice(createInsecureRfcommSocketToServiceRecord, a))) {
z = false;
}
valueOf = Boolean.valueOf(z);
try {
createInsecureRfcommSocketToServiceRecord.close();
return valueOf;
} catch (IOException e8) {
return valueOf;
}
} else if (this.jobType == JobType.startMission) {
boolean z2 = writeDevice(createInsecureRfcommSocketToServiceRecord, (IButton) objArr[3]) &&
startMission(createInsecureRfcommSocketToServiceRecord);
valueOf = Boolean.valueOf(z2);
try {
createInsecureRfcommSocketToServiceRecord.close();
return valueOf;
} catch (IOException e9) {
return valueOf;
}
} else {
try {
createInsecureRfcommSocketToServiceRecord.close();
} catch (IOException e10) {
}
return null;
}
} catch (IOException e11) {
try {
createInsecureRfcommSocketToServiceRecord.close();
} catch (IOException e1) {
e1.printStackTrace();
}
createInsecureRfcommSocketToServiceRecord = null;
return null;
} catch (Throwable th3) {
th = th3;
} finally {
try {
createInsecureRfcommSocketToServiceRecord.close();
createInsecureRfcommSocketToServiceRecord = null;
} catch (IOException e2) {
}
}
return null;
}
Related
My problem is I have implemented a TCP socket client in android which sends continuously "Hello" messages to the server to maintain a client-server connection and receives messages from the server.
In Android, I have initialized a boolean variable that is controlling the thread if my app is in the background I make the "AppConfig.finished" variable true inactivity on pause and on stop method to stop the socket thread and make it false when in on resume state.
But my app is consuming high CPU usage which is making my app slow, I have checked it in android's profiler. Please help me to optimize it.
The code is given below.
public class MyTcp extends Thread{
private BufferedInputStream inputStream;
private BufferedOutputStream outputStream;
private Socket MySock;
private static SocketStatus SS;
private int ConnectAttemptCount = 0;
private CheckConnectionStatus CheckStatus = null;
public boolean FirstAttempt = true;
public boolean Continue = true;
private boolean isDirectChecked = false;
String tempData = "";
private final ArrayBlockingQueue<String> Queue = new ArrayBlockingQueue<>(100);
public MyTcp(SocketStatus SS) {
MyTcp.SS = SS;
MyTcp.SS.isConnected = false;
setDaemon(true);
Thread t = new Thread(new DequeueMessageThread());
t.setName(SS.SocketName + " DequeqeMessageThread");
t.start();
setName(SS.SocketName);
}
public void Dispose() {
try {
Continue = false;
SS.isConnected = false;
if(inputStream != null) {
inputStream.close();
}
if(outputStream !=null) {
outputStream.close();
}
if(MySock != null) {
MySock.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void run() {
if(!Logs.isFinished) {
try {
while (Continue) {
if (SS.isConnected) {
String fromServer = ReceiveMsg();
if (fromServer.compareTo("") != 0) {
Queue.put(fromServer);
}
ConnectAttemptCount = 0;
} else {
if (ConnectAttemptCount < SS.ConnectAttempt) {
println("run>>" + "Connection Attempt" + ConnectAttemptCount);
ConnectAttemptCount++;
Connect();
} else {
println("run>>" + "Unable To Connect to server");
break;
}
}
}
} catch (Exception e) {
println("run Exception>>" + e);
}
}
}
public void Connect() {
if(!Logs.isFinished) {
try {
if (SS.isDoQueueEmptyOnConnect) {
Queue.clear();
tempData = "";
}
if (FirstAttempt) {
FirstAttempt = false;
} else {
Utilities.println("Trying to connect with " + SS.ServerIP + " on Port " + SS.Port);
_fireStatsEvent(Status.Reconnecting, "Trying to connect with " + SS.ServerIP);
Random generator = new Random();
long wait = (long) generator.nextInt(3000) + 500;
Thread.sleep(wait);
}
MySock = (Socket) AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
// Start Secure Code
return (new Socket(SS.ServerIP, SS.Port));
// End Secure Code
} catch (Exception e) {
println("Connect Exception>>" + e.toString());
}
return null;
}
});
if (MySock != null) {
SS.isConnected = true;
SocketStatus.MySock = MySock;
inputStream = new BufferedInputStream(MySock.getInputStream());
outputStream = new BufferedOutputStream(MySock.getOutputStream());
Utilities.println("Connection established with " + SS.ServerIP + " on Port " + SS.Port);
if (SocketStatus.EnablePingPong) {
if (CheckStatus != null) {
CheckStatus.Dispose();
}
SS.LastMsgTime = new Date();
CheckStatus = new CheckConnectionStatus(SS, this);
CheckStatus.setName(SS.SocketName + "Connection Status Thread");
CheckStatus.start();
}
}
} catch (Exception e) {
println("Connect>>" + e);
}
int ConnectToIPCount = 0;
if (!SS.isConnected) {
while (!SS.isConnected && ConnectToIPCount < SS.ServerIPList.size()) {
final String IP_ = SS.ServerIPList.get(ConnectToIPCount).toString();
final int Port_ = SS.Port;
println("Connect>>" + "Trying to connect with " + IP_ + " on Port " + Port_);
ConnectToIPCount++;
try {
Thread.sleep(5000);
MySock = (Socket) AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
// Start Secure Code
if (!isDirectChecked) {
isDirectChecked = true;
Socket tempSock = new Socket(Proxy.NO_PROXY);
tempSock.connect(new InetSocketAddress(IP_, Port_));
return tempSock;
} else {
return (new Socket(IP_, Port_));
}
// End Secure Code
} catch (Exception e) {
println("Connect Exception>>" + e.toString());
}
return null;
}
});
if (MySock != null) {
SocketStatus.MySock = MySock;
SS.isConnected = true;
inputStream = new BufferedInputStream(MySock.getInputStream());
outputStream = new BufferedOutputStream(MySock.getOutputStream());
Utilities.println("Connection established with " + IP_ + " on port " + Port_);
if (SocketStatus.EnablePingPong) {
if (CheckStatus != null) {
CheckStatus.Dispose();
}
SS.LastMsgTime = new Date();
CheckStatus = new CheckConnectionStatus(SS, this);
CheckStatus.setName(SS.SocketName + "Connection Status Thread");
CheckStatus.start();
}
}
} catch (UnknownHostException e) {
println("Connect UnknownHostException>>" + e.toString());
} catch (IOException e) {
println("Connect IOException>>" + e.toString());
} catch (Exception e) {
println("Connect Exception>>" + e.toString());
}
}
}
}
}
public void SendMsg(String sendMsg) {
if(!Logs.isFinished) {
try {
println("SendMsg>>" + sendMsg);
if (MySock != null && MySock.isConnected()) {
try {
byte[] b = null;
b = sendMsg.getBytes();
outputStream.write(b, 0, b.length);
outputStream.flush();
} catch (SocketException | SocketTimeoutException e) {
if (MySock != null) {
MySock.close();
}
SS.isConnected = false;
} catch (Exception e) {
println("SendMsg Exception>>" + e.toString());
}
}
} catch (Exception e) {
Log.d("TCP Client SendMsg >>", "Unable To Connect to server");
}
}
}
public String ReceiveMsg() {
String recvMsg = "";
if(!Logs.isFinished) {
try {
byte[] b = new byte[8092 * 6];
int recvsz = 0;
if (MySock != null && MySock.isConnected()) {
recvsz = inputStream.read(b, 0, b.length);
if (recvsz > 0) {
try {
byte[] b2 = new byte[recvsz];
System.arraycopy(b, 0, b2, 0, b2.length);
recvMsg = (new String(b2));
if (recvMsg.length() > 0) {
SS.LastMsgTime = new Date();
}
} catch (Exception e) {
println("ReceiveMsg Exception>>" + e.toString());
}
}
}
} catch (Exception e) {
if (SS.isConnected) {
Utilities.handleException(e);
}
SS.isConnected = false;
println("ReceiveMsg Exception>>>" + e.toString());
Log.d("RESPONSE FROM SERVER", "S: Received Message: '" + e.toString() + "'");
}
}
return recvMsg;
}
public void println(String msg) {
if (SS.Debug) {
String strDateFormat1 = "HH:mm:ss";
SimpleDateFormat sdf1 = new SimpleDateFormat(strDateFormat1);
Utilities.println(SS.SocketName + " (" + sdf1.format(new Date()) + ") " + msg);
}
}
private final List<MessageRecieveListner> _listeners = new ArrayList<>();
private final List<MessageRecieveListner> _listenersStrength = new ArrayList<>();
public synchronized void addListener(MessageRecieveListner l) {
_listeners.add(l);
_listenersStrength.add(l);
}
private synchronized void _fireMessageEvent(String msg) {
MessageRecieveEvent MsgEvent = new MessageRecieveEvent(this, msg);
for (MessageRecieveListner listener : _listeners) {
listener.MessageRecieved(MsgEvent);
}
}
public synchronized void _fireStatsEvent(Status status, String msg) {
MessageRecieveEvent MsgEvent = new MessageRecieveEvent(this, status, msg);
for (MessageRecieveListner listener : _listeners) {
listener.ConnectionStatus(MsgEvent);
}
}
private class DequeueMessageThread implements Runnable {
public DequeueMessageThread() {
}
#Override
public void run() {
if(!Logs.isFinished) {
while (Continue) {
if (!Queue.isEmpty()) {
try {
String data = Queue.take().trim();
if (SS.MessageParser.length() > 0) {
if (data.lastIndexOf(SS.MessageParser) == data.length() - 1) {
_fireMessageEvent(tempData + data);
tempData = "";
} else {
if (data.indexOf(SS.MessageParser) > 0) {
String particalCompleteData = tempData + data.substring(0, data.lastIndexOf(SS.MessageParser));
tempData = data.substring(data.lastIndexOf(SS.MessageParser) + 1);
_fireMessageEvent(particalCompleteData);
Utilities.println("incomplete data");
}
}
} else {
_fireMessageEvent(data);
}
} catch (Exception ex) {
ex.printStackTrace();
Continue = false;
}
}
}
}
}
}
I'm trying to get the location with the google-location services for android.
I've tried to fiddle with some methods from the google api from the tasks package, but all seem to fail. More exactly, my application starts to hang.
public class LocationTask extends AsyncTask<FusedLocationProviderClient, Void, JSONObject> {
#SuppressLint("MissingPermission")
#Override
protected JSONObject doInBackground(FusedLocationProviderClient... locationProviderClients) {
WeatherApiCall weatherApiCall = new WeatherApiCall();
Task<Location> locationTask = locationProviderClients[0].getLastLocation();
Location location = null ;
try {
location = Tasks.await(locationTask);
weatherApiCall.execute("weather", String.format(Locale.getDefault(), "%.2f", location.getLatitude()),
String.format(Locale.getDefault(), "%.2f", location.getLongitude()), "metric");
return new JSONObject(weatherApiCall.get());
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
I've also tried to use the addOnSuccessListener, but to no avail.
try {
locationProviderClients[0].getLastLocation()
.addOnSuccessListener(location -> {
if (location != null) {
Log.d("LOCATION", location.toString());
weatherApiCall.execute("weather", String.format(Locale.getDefault(), "%.2f", location.getLatitude()),
String.format(Locale.getDefault(), "%.2f", location.getLongitude()), "metric");
}
});
return new JSONObject(weatherApiCall.get());
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
I know that the success listener does the action after the task locationProviderClients[0].getLastLocation() is successfully completed, but I fail to get the result from the task.
I am trying to use sockets in Android to connect over wifi to some UDP port (some_port) on a machine in my local network whose ip is some_ip.
When I run
socket = new Socket(some_ip, some_port);
I get no message error but the program does not seem to read this line and I can't log the error when surrounding with try/catch.
How can I debug that ?
Edit 1 : here's my try/catch
try{
socket = new Socket(some_ip, some_port);
}
catch(ConnectException e) {
e.printStackTrace();
}
Edit 2 : here's the entire code
private void getUDPData() throws IOException {
class ProcessUPDTask extends AsyncTask<String, Void, Socket> {
private Exception exception;
private Socket socket;
public ProcessUPDTask() throws IOException {
}
private void runThread(){
new Thread() {
public void run() {
Toast.makeText(activity, "Own Message", Toast.LENGTH_LONG).show();
}
}.start();
}
protected Socket doInBackground(String... urls) {
try {
try{
socket = new Socket(some_ip, some_port);
socket.setSoTimeout(1500);
}
catch(IOException e) {
e.printStackTrace();
}
Log.d("TAG","this line is reached");
while(true){
try {
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
System.out.println("ip: " + socket.getInetAddress());
System.out.println("message: " + dataInputStream.readUTF());
dataOutputStream.writeUTF("Hello!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if( socket!= null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if( dataInputStream!= null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if( dataOutputStream!= null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
} catch (Exception e) {
this.exception = e;
e.printStackTrace();
return null;
}
}
protected void onPostExecute(Socket socket) {
// TODO: check this.exception
// TODO: do something with the feed
}
}
new ProcessUPDTask().execute();
}
Try this
try {
Socket socket = new Socket(IP_ADDRESS, PORT);
socket.setSoTimeout(1500);
} catch (IOException ex) {
Log.e("Connection Error",String.valueOf(ex));
}
Replace your code with this and wait some seconds(60 sec for now) you can see the error toast..
private void getUDPData() throws IOException {
class ProcessUPDTask extends AsyncTask<String, Void, Socket> {
private Exception exception;
private Socket socket;
public ProcessUPDTask() throws IOException {
}
protected Socket doInBackground(String... urls) {
try {
try {
socket = new Socket("192.168.1.101", 1234);
socket.setSoTimeout(1500);
} catch (IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show();
}
});
}
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "Reached", Toast.LENGTH_LONG).show();
}
});
while (true) {
try {
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
System.out.println("ip: " + socket.getInetAddress());
System.out.println("message: " + dataInputStream.readUTF());
dataOutputStream.writeUTF("Hello!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
} catch (Exception e) {
this.exception = e;
e.printStackTrace();
return null;
}
}
protected void onPostExecute(Socket socket) {
// TODO: check this.exception
// TODO: do something with the feed
}
}
new ProcessUPDTask().execute();
}
You can configure this and use transData() between connectivity.
private void transData(int sending_msg_int) throws IOException {
String sending_msg = Integer.toString(sending_msg_int);
SocketAddress socketAddress = new InetSocketAddress(ip, Data.Port);
DatagramSocket ds = new DatagramSocket();
byte[] buffer = sending_msg.getBytes();
DatagramPacket dp = new DatagramPacket(buffer, buffer.length,
socketAddress);
ds.send(dp);
ds.close();
}
I am using an activity to display the contact list, and inside this activity I have a button to add another contact. I can add a new contact and display it in the listview. But all the contacts will be gone if I exit the app or press the BACK button.
I think I am having a problem while trying to get data from an Internal Storage. I can save the data and I can see the CONTACT_LISTs file in the Emulator. But I am not able to read the data from it. I put the "SavingFuction" in "OnPause" and "ReadingFunction" in "OnResume". I am using below code snippet for saving data:
For Internal storage:
onPause, onResume
#Override
protected void onPause()
{
super.onPause();
SavePreferences(arrContacts);
}
#Override
protected void onResume()
{
super.onResume();
getContact(arrContacts);
}
-Saving:
public void SavePreferences(ArrayList<Contacts> ct)
{
try
{
FileOutputStream fOS = openFileOutput("CONTACT_LISTs", MODE_PRIVATE);
ObjectOutputStream oOS = new ObjectOutputStream(fOS);
oOS.writeObject(ct);
oOS.flush();
oOS.close();
fOS.close();
}
catch(Exception e)
{
Log.e("InternalStorage", e.getMessage());
}
}
-Reading
public void getContact(ArrayList<Contacts> ct)
{
try
{
FileInputStream fIS = openFileInput("CONTACT_LISTs");
ObjectInputStream oi = new ObjectInputStream(fIS);
ct = (ArrayList<Contacts>) oi.readObject();
oi.close();
fIS.close();
} catch (FileNotFoundException e) {
Log.e("InternalStorage", e.getMessage());
} catch (IOException e) {
Log.e("InternalStorage", e.getMessage());
} catch (ClassNotFoundException e) {
Log.e("InternalStorage", e.getMessage());
}
}
How can I make it right?. Everything's just gone after I closed the app and reopened it.
this is my Contacts.java
public class Contacts implements Serializable
{
private static final long serialVersionUID = 1L;
private ArrayList<Contacts>contactList=new ArrayList<Contacts>();
String name;
String number;
String address;
public Contacts(String name, String num, String add)
{
this.name = name;
this.number = num;
this.address = add;
}
public Contacts() {
}
public void addContact(Contacts ct)
{
int i=0;
for(; i < contactList.size(); i++)
{
Contacts nvOld=contactList.get(i);
if(nvOld.getNum().trim().equalsIgnoreCase(ct.getNum().trim()))
{
break;
}
}
if(i < contactList.size())
contactList.set(i, ct);
else
contactList.add(ct);
}
String getName()
{
return name;
}
public void setName(String na)
{
this.name = na;
}
String getNum()
{
return number;
}
public void setNum(String nu)
{
this.number = nu;
}
String getAdd()
{
return address;
}
public void setAdd(String ad)
{
this.address = ad;
}
}
1.make sure you data object is implements Serializable;
2.make sure data is save OK(you can find this file in explore,Note the file size and time);
3.make sure read data is ok;
At last:
i check this source code,Contacts is not implements Serializable.
this is the reason you are looking for;
you can implement custom class to storage data.
Working with streams it's not only about catching exceptions but also closing streams. It is a good practice to use following construction:
try {
//read from stream
} catch (Exception e) {
//work with Exceptions
} finally {
//close all streams even when exception was called
}
Why don't you close fIS in Reading block?
public ArrayList<Contacts> getContact()
{
ArrayList<Contacts> ct = null;
try
{
FileInputStream fIS = openFileInput("CONTACT_LISTs");
ObjectInputStream oi = new ObjectInputStream(fIS);
ct = (ArrayList<Contacts>) oi.readObject();
oi.close();
fIS.close();
} catch (FileNotFoundException e) {
Log.e("InternalStorage", e.getMessage());
} catch (IOException e) {
Log.e("InternalStorage", e.getMessage());
} catch (ClassNotFoundException e) {
Log.e("InternalStorage", e.getMessage());
}
return ct;
}
i test it, it's work ok.
as i thought change that
#Override
protected void onPause()
{
super.onPause();
SavePreferences(arrContacts);
}
#Override
protected void onResume()
{
super.onResume();
getContact(arrContacts);
}
public void getContact(ArrayList<Contacts> ct)
{
try
{
FileInputStream fIS = openFileInput("CONTACT_LISTs");
ObjectInputStream oi = new ObjectInputStream(fIS);
ct = (ArrayList<Contacts>) oi.readObject();
oi.close();
fIS.close();
} catch (FileNotFoundException e) {
Log.e("InternalStorage", e.getMessage());
} catch (IOException e) {
Log.e("InternalStorage", e.getMessage());
} catch (ClassNotFoundException e) {
Log.e("InternalStorage", e.getMessage());
}
}
to that
#Override
protected void onPause()
{
SavePreferences(arrContacts);
super.onPause();
}
#Override
protected void onResume()
{
super.onResume();
arrContacts = getContact();
}
public ArrayList<Contacts> getContact()
{
ArrayList<Contacts> ct = new ArrayList<Contacts>();
try
{
FileInputStream fIS = openFileInput("CONTACT_LISTs");
ObjectInputStream oi = new ObjectInputStream(fIS);
ct = (ArrayList<Contacts>) oi.readObject();
oi.close();
fIS.close();
} catch (FileNotFoundException e) {
Log.e("InternalStorage", e.getMessage());
} catch (IOException e) {
Log.e("InternalStorage", e.getMessage());
} catch (ClassNotFoundException e) {
Log.e("InternalStorage", e.getMessage());
}
return ct;
}
another one update
public void getContact()
{
try
{
FileInputStream fIS = openFileInput("CONTACT_LISTs");
ObjectInputStream oi = new ObjectInputStream(fIS);
arrContacts.clear();
arrContacts = (ArrayList<Contacts>) oi.readObject();
contactsAdapter.notifyDataSetChanged();
oi.close();
fIS.close();
} catch (FileNotFoundException e) {
Log.e("InternalStorage", e.getMessage());
} catch (IOException e) {
Log.e("InternalStorage", e.getMessage());
} catch (ClassNotFoundException e) {
Log.e("InternalStorage", e.getMessage());
}
}
I have a problem in using of long touch and multi thread programming.
I have 2 button: up and down. Each of these buttons have OnTouchListener event habdler . When I touch down in each of them, a thread will run inside them in the while(HelperClass.Universal_IsTouch == true) and in every 1000 milisec run again until tuouch up raised and "HelperClass.Universal_IsTouch" make false in touch up and it exit from the while .
in the while loop a thrad run and call another class method for sending data via run another thread via socket programming . So then when up button (or down) touched down long time , data should be send to server until touched up raised.
Its working but after many sending up and down when I touch long up (or down) its sended data related to other routin instead main routin ?
this is my UP routin code :
//////////// up
btn_UP_var.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
IntruptedAllThread();
// TODO Auto-generated method s tub
if (arg1.getAction() == MotionEvent.ACTION_DOWN)
{
HelperClass.Universal_IsTouch = true;
} else if (arg1.getAction() == MotionEvent.ACTION_UP) {
HelperClass.Universal_IsTouch = false;
}
//Send a simple Move (once)
if (chkbx_AutoMove_var.isChecked()) {
Img_Stop_var.setImageResource(R.drawable.arrow_stop_play);
Is_UP_buttonTouched = 1;
HelperClass.Is_Stop_Button_Disable = false;
} else {
HelperClass.Is_Stop_Button_Disable = true;
thread_UP = new Thread(new Runnable() {
#Override
public void run() {
while (HelperClass.Universal_IsTouch == true) {
Cursor ListHoist = mDbHelper.GetallSelectedHoistData();
//mDbHelper.close();
for (ListHoist.moveToFirst(); !ListHoist.isAfterLast(); ListHoist.moveToNext()) {
String IP = ListHoist.getString(ListHoist.getColumnIndex("HoistIP"));
int PK_hoist = ListHoist.getInt(ListHoist.getColumnIndex("PK_hoist"));
HelperClass.SendDataToMICRO(mDbHelper, PK_hoist, IP, HelperClass.Selector_Move_Stop,
HelperClass.MoveDesition_Up, HelperClass.inutile, HelperClass.inutile,
HelperClass.inutile);
}
ListHoist.close();
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
IntruptedAllThread();
}
}
// thread_UP.interrupt();
IntruptedAllThread();
}
});
thread_UP.start();
}
return true;
}
});
and this is my Down Code :
//////////// Down
btn_Down_var.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
IntruptedAllThread();
if (arg1.getAction() == MotionEvent.ACTION_DOWN)
{
HelperClass.Universal_IsTouch = true;
//txt_MovementValue_var.setText("1");
} else if (arg1.getAction() == MotionEvent.ACTION_UP)
{
HelperClass.Universal_IsTouch = false;
//txt_MovementValue_var.setText("0");
}
//Send a simple Move (once)
if (chkbx_AutoMove_var.isChecked()) {
Img_Stop_var.setImageResource(R.drawable.arrow_stop_play);
Is_UP_buttonTouched = 0;
HelperClass.Is_Stop_Button_Disable = false;
} else {
HelperClass.Is_Stop_Button_Disable = true;
thread_Down = new Thread(new Runnable() {
#Override
public void run() {
while (HelperClass.Universal_IsTouch == true) {
Cursor ListHoist = mDbHelper.GetallSelectedHoistData();
for (ListHoist.moveToFirst(); !ListHoist.isAfterLast(); ListHoist.moveToNext()) {
String IP = ListHoist.getString(ListHoist.getColumnIndex("HoistIP"));
int PK_hoist = ListHoist.getInt(ListHoist.getColumnIndex("PK_hoist"));
HelperClass.SendDataToMICRO(mDbHelper, PK_hoist, IP, HelperClass.Selector_Move_Stop,
HelperClass.MoveDesition_Down, HelperClass.inutile, HelperClass.inutile,
HelperClass.inutile);
}
ListHoist.close();
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
IntruptedAllThread();
}
}
//thread_Down.interrupt();
IntruptedAllThread();
}
});
thread_Down.start();
}
return true;
}
});
this is IntruptedAllThread()
public void IntruptedAllThread() {
if (thread_UP != null) {
thread_UP.interrupt();
thread_UP = null;
}
if (thread_Down != null) {
thread_Down.interrupt();
thread_Down = null;
}
}
and this is my thread to send data socket :
//This get each hoist data and change it to
//Int array to send to micro
public static void SendDataToMICRO(dbAdapter mDbHelper, int HoistID, final String Server_IP, int firstByte_KindType, int secoundByte_KindofMove,
int ValueOfMove, int valueOfsetting, int MaxOrMinValue) {
// mDbHelper = new dbAdapter(G.context);
// mDbHelper.createDatabase();
// mDbHelper.open();
Server_Port = mDbHelper.GetPortNumber();
//mDbHelper.close();
final String Concatinate_values = firstByte_KindType + Spliter + secoundByte_KindofMove +
Spliter + ValueOfMove + Spliter + valueOfsetting + Spliter + MaxOrMinValue;
//Sent Routin
////Connect To server
Thread thread = null;
thread = new Thread(new Runnable() {
#Override
public void run() {
DataOutputStream outputStream = null;
BufferedReader inputStream = null;
Socket socket;
socket = new Socket();
try {
socket.connect(new InetSocketAddress(Server_IP, Server_Port), 10);
}
catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
Thread.currentThread().interrupt();
}
////Make Read Line
try {
outputStream = new DataOutputStream(socket.getOutputStream());
inputStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
catch (IOException e1) {
//Finished Socket
ShutDown(socket);
}
if (outputStream == null) {
//
ShutDown(socket);
Thread.currentThread().interrupt();
return;
}
//Write Message
try {
String message = Concatinate_values + "\n";
outputStream.write(message.getBytes());
outputStream.flush();
ShutDown(socket);
Thread.currentThread().interrupt();
return;
}
catch (IOException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
try {
if (socket != null) {
socket.close();
}
}
catch (IOException e) {
e.printStackTrace();
ShutDown(socket);
Thread.currentThread().interrupt();
return;
}
Thread.currentThread().interrupt();
}
});
thread.start();
}
result