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());
}
}
Related
Hello I tried to make an app for displaying quote in Android Studio.
But I got stuck when reading.
I created an "ArrayList" with my custom class Quotes.
I seems to work ok when writing the ArrayList to the file, but when reading from it the size of ArrayList is 0.
public class SaveQuote extends AppCompatActivity {
EditText editTextQuote;
EditText editTextAuthor;
Button btnSave;
ArrayList<Quote> arrQuo = new ArrayList<>();
public static ArrayList<Quote> arrayListQuotesSave;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_save_quote);
init();
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String quote = editTextQuote.getText().toString();
String author =editTextAuthor.getText().toString();
addQuote(quote,author);
}
});
}
private void init(){
editTextQuote = findViewById(R.id.editTextQuote);
editTextAuthor = findViewById(R.id.editTextAuthor);
btnSave = findViewById(R.id.buttonSave);
arrayListQuotesSave = new ArrayList<>();
}
private void addQuote(String quote, String author){
Quote q = new Quote(quote, author);
arrQuo.add(q);
String path = this.getFilesDir().toString();
try {
FileOutputStream fos = openFileOutput("Quotes.txt",MODE_APPEND);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(arrQuo);// when I write size = 1
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileInputStream fis = openFileInput("Quotes.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
arrQuo =(ArrayList<Quote>) ois.readObject();
ois.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
I tried to passe a context and call the method openFileOutput on the context
so like this:
enter code here
FileOutputStream fs = context.openFileOutput("Quotes.txt", Context.MODE_PRIVATE);
enter code here
public class SaveQuote extends AppCompatActivity {
EditText editTextQuote;
EditText editTextAuthor;
Button btnSave;
ArrayList<Quote> arrQuo = new ArrayList<>();
public static ArrayList<Quote> arrayListQuotesSave;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_save_quote);
init();
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String quote = editTextQuote.getText().toString();
String author =editTextAuthor.getText().toString();
if(quote.isEmpty() || author.isEmpty()){
Toast.makeText(SaveQuote.this,"Fill all fields",Toast.LENGTH_SHORT).show();
}else {
writeToFile(SaveQuote.this, quote, author);
Toast.makeText(SaveQuote.this,"The quote was saved",Toast.LENGTH_SHORT).show();
}
}
});
}
private void init(){
editTextQuote = findViewById(R.id.editTextQuote);
editTextAuthor = findViewById(R.id.editTextAuthor);
btnSave = findViewById(R.id.buttonSave);
arrayListQuotesSave = new ArrayList<>();
}
private void writeToFile(Context context,String quote,String author) {
Quote q = new Quote(quote,author);
MainActivity.arrayListQuotesMain.add(q);
Integer size = MainActivity.arrayListQuotesMain.size();
Log.v("Added","arrayListQuotesMain size is = "+size.toString());
try {
FileOutputStream fs = context.openFileOutput("Quotes.txt", Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fs);
oos.writeObject(MainActivity.arrayListQuotesMain);
oos.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
editTextQuote.setText("");
editTextAuthor.setText("");
}
}
Server side code
public class MainActivity extends AppCompatActivity {
TextView infoIp, infoPort;
static final int SocketServerPORT = 8080;
ServerSocket serverSocket;
ServerSocketThread serverSocketThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
infoIp = (TextView) findViewById(R.id.infoip);
infoPort = (TextView) findViewById(R.id.infoport);
infoIp.setText(getIpAddress());
serverSocketThread = new ServerSocketThread();
serverSocketThread.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private String getIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces
.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface
.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip += "SiteLocalAddress: "
+ inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
public class ServerSocketThread extends Thread {
#Override
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SocketServerPORT);
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
infoPort.setText("I'm waiting here: "
+ serverSocket.getLocalPort());
}});
while (true) {
socket = serverSocket.accept();
FileTxThread fileTxThread = new FileTxThread(socket);
fileTxThread.start();
}
} 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();
}
}
}
}
}
public class FileTxThread extends Thread {
Socket socket;
FileTxThread(Socket socket){
this.socket= socket;
}
#Override
public void run() {
File file = new File(
Environment.getExternalStorageDirectory(),
"graphs.txt");
byte[] bytes = new byte[(int) file.length()];
BufferedInputStream bis;
try {
bis = new BufferedInputStream(new FileInputStream(file));
bis.read(bytes, 0, bytes.length);
OutputStream os = socket.getOutputStream();
os.write(bytes, 0, bytes.length);
os.flush();
socket.close();
final String sentMsg = "File sent to: " + socket.getInetAddress();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this,
sentMsg,
Toast.LENGTH_LONG).show();
}});
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
Client Side Code :
public class MainActivity extends AppCompatActivity {
EditText editTextAddress;
Button buttonConnect;
TextView textPort;
static final int SocketServerPORT = 8080;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextAddress = (EditText) findViewById(R.id.address);
textPort = (TextView) findViewById(R.id.port);
textPort.setText("port: " + SocketServerPORT);
buttonConnect = (Button) findViewById(R.id.connect);
buttonConnect.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
ClientRxThread clientRxThread =new ClientRxThread(editTextAddress.getText().toString(),SocketServerPORT);
clientRxThread.start();
}});
}
private class ClientRxThread extends Thread {
String dstAddress;
int dstPort;
ClientRxThread(String address, int port) {
dstAddress = address;
dstPort = port;
}
#Override
public void run() {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
File file = new File(Environment.getExternalStorageDirectory(),"graphs.txt");
byte[] bytes = new byte[8192];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead = is.read(bytes, 0, bytes.length);
bos.write(bytes, 0, bytesRead);
bos.close();
socket.close();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this,
"Finished",
Toast.LENGTH_LONG).show();
}});
} catch (IOException e) {
e.printStackTrace();
final String eMsg = "Something wrong: " + e.getMessage();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this,
eMsg,
Toast.LENGTH_LONG).show();
}});
} finally {
if(socket != null){
try {
System.out.println("socket not null "+socket);
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
Error shoews in client side :
E/AndroidRuntime: FATAL EXCEPTION: Thread-2648
Process: com.example.moraya.socketfileserverside1, PID: 30793
java.lang.ArrayIndexOutOfBoundsException: length=8192; regionStart=0; regionLength=-1
at java.util.Arrays.checkOffsetAndCount(Arrays.java:1719)
at java.io.BufferedOutputStream.write(BufferedOutputStream.java:135)
hi sir, i am trying to transfer file client to server by using socket, but after click on connect button client side application says unfortunately application has stopped and also the empty text file send into the sdcard.
please help me what is the error and how to solve it.
Background:
I am using three fragments and one activity in my application. Two fragments use recyclerViews and the other uses an expandableListView.
Problem:
I am trying to properly program the onPause(), onResume(), onStop(), and onRestart() methods to save the state of my application when the home, back, or switch views buttons are pressed.
To save the state of the program and load it when it comes back I have created the save() and load() methods in my one and only activity.
//from the end of onCreate
load();
}
#Override
protected void onStart() {
super.onStart();
mRef = new Firebase("https://sure-7856d.firebaseio.com/");
}
#Override
protected void onStop(){
super.onStop();
save();
}
#Override
protected void onPause(){
super.onPause();
save();
}
#Override
protected void onResume(){
super.onResume();
load();
}
#Override
protected void onRestart(){
super.onRestart();
load();
}
In the save method I get the adapters from my 2 recyclerViews and my expandableListView`s ArrayList that keeps track of which checkboxes are checked.
After that I put them each into a temporary Arraylist then I add each of those ArrayLists to a single arraylist that will be saved to the file.
private void save(){
//saved_data = new File("saved_data");
/*try {
if(saved_data.exists()==false){
//saved_data.createNewFile();
saved_data.setWritable(true);
}
} catch (IOException e) {
e.printStackTrace();
}*/
File myFile;
try{
myFile = new File(getFilesDir().getAbsolutePath(), "dir/save_data.bin");
myFile.mkdirs();
myFile.createNewFile();
FILENAME = myFile.getName();
}catch (IOException e){
e.printStackTrace();
}
OneFragment f20 = (OneFragment) frags.get(0);
TwoFragment f21 = (TwoFragment) frags.get(1);
ThreeFragment f22 = (ThreeFragment) frags.get(2);
ArrayList saveTasks = f20.adapter.getList();
ArrayList saveReqs = f21.adapter.getList();
ArrayList saveMap = new ArrayList<String>();
if(f22.listAdapter!=null) {
if (f22.listAdapter.getExport() != null) {
saveMap = f22.listAdapter.getExport();
}
}
ArrayList results = new ArrayList();
results.add(saveTasks);
results.add(saveReqs);
results.add(saveMap);
ObjectOutputStream oos1 = null;
FileOutputStream fos1 = null;
try {
fos1 = openFileOutput(FILENAME, Context.MODE_PRIVATE);
oos1 = new ObjectOutputStream(fos1);
oos1.writeObject(results);
oos1.close();
fos1.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(oos1 != null){
try {
oos1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
In the load code I get the object from the file and update the adapters to their previous state.
private void load(){
//saved_data = new File("saved_data");
ArrayList results = new ArrayList();
FileInputStream fis = null;
ObjectInputStream ois = null;
if(FILENAME==null){
return;
}
try {
fis = new FileInputStream(FILENAME);
ois = new ObjectInputStream(fis);
}catch (FileNotFoundException e) {
e.printStackTrace();
return;
}catch (IOException e) {
e.printStackTrace();
}
try {
while (true) {
results = (ArrayList)(ois.readObject());
}
} catch (OptionalDataException e) {
if (!e.eof) try {
throw e;
} catch (OptionalDataException e1) {
e1.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ois.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
for(int i = 0; i < results.size();i++){
if(i == 0){
frags.set(0,results.get(i));
}
else if(i == 1){
frags.set(1,results.get(i));
}
else if(i == 2){
frags.set(2,results.get(i));
}
else{
}
}
}
When I press the square button at the bottom of the emulator and go back to it one of a few things happen
It crashes saying the file could not be found
W/System.err: Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
And this error points to the load method as the point of failure specifically
FileInputStream fis = null;
When I hit the triangle button nothing happens in logcat, everything is gone upon returning, and the app loses its functions of adding strings to lists on both recyclerViews and displaying both lists in the expandableListView.
Hitting the center circle button and going back to the app is fine nothing breaks.
Since Im getting a file not found error I think that the file isnt getting written
I have searched Stack for a solution and I am new to File IO and fragments, so I have no idea where to go from here.
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'm trying to send an Object from my phone to my PC(Windows) using a TCP socket via WiFi. When I try the same code between two PCs, it works without any error. But when I put the client code to the android device, it fails to send date using writeObject method. But writeUTF command works. It gives the "Software caused connection abort: recv failed" error. Below is the Code. Please help..
Server(in PC):
public class Test {
public static void main(String arg[]) {
ServerSocket serverSocket = null;
Socket socket = null;
ObjectInputStream in = null;
ObjectOutputStream out = null;
try {
serverSocket = new ServerSocket(8888);
System.out.println("Listening :8888");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (true) {
try {
socket = serverSocket.accept();
in = new ObjectInputStream(socket.getInputStream());
out = new ObjectOutputStream(socket.getOutputStream());
out.flush();
System.out.println("ip: " + socket.getInetAddress());
Message msg = (Message) in.readObject(); //Message captured from chat client.
System.out.println(msg.type + " message received from " + msg.sender + " Containing " + msg.content);
out.writeObject(new Message("Ack", "Server", "Message Received", "Client"));
out.flush();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
Client (in Android Device):
public class MainActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bb=(Button)findViewById(R.id.button1);
bb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new Send().execute();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class Send extends AsyncTask<Void, Void, Void> {
Socket socket = null;
ObjectOutputStream out = null;
ObjectInputStream in = null;
protected Void doInBackground(Void... arg0) {
try {
socket = new Socket("192.168.43.92", 8888); //use the IP address of the server
out = new ObjectOutputStream(socket.getOutputStream());
out.flush();
out.writeObject(new Message("Chat", "Server", "Hello World", "Server")); //This method is used to write something to the server.
out.flush();
Message msg = (Message) in.readObject();
System.out.println(msg.type + " message received from " + msg.sender + " Containing " + msg.content);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException 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 (out != null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
//setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
//showDialog("Downloaded " + result + " bytes");
}
}
}
Message(in Both Sides):
public class Message implements Serializable{
private static final long serialVersionUID = 1L;
public String type, sender, content, recipient;
public Message(String type, String sender, String content, String recipient){
this.type = type; this.sender = sender; this.content = content; this.recipient = recipient;
}
#Override
public String toString(){
return "{type='"+type+"', sender='"+sender+"', content='"+content+"', recipient='"+recipient+"'}";
}
}
Is the network between the client and server setup properly via your WiFi? Download one of those ping & telnet test apps and use it to test your network connection.
Telnet is a useful TCP debugging app. If you have a server listening on 11.22.33.44 port 1234, you should be able to telnet 11.22.33.44 1234
Maybe, you need to add this functions into Message class:
private void writeObject(java.io.ObjectOutputStream stream)
throws IOException {
stream.writeObject(type);
stream.writeObject(sender);
stream.writeObject(content);
stream.writeObject(recipient);
}
private void readObject(java.io.ObjectInputStream stream)
throws IOException, ClassNotFoundException {
type = (String) stream.readObject();
sender = (String) stream.readObject();
content = (String) stream.readObject();
recipient = (String) stream.readObject();
}
http://developer.android.com/reference/java/io/Serializable.html