here is my entire code (ps Im a noobie);
package xom.aaa.aaa;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class FilewritertestActivity extends Activity {
TextView textout1, textout2, textout3;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b1 = (Button) findViewById(R.id.button1);
textout1 = (TextView) findViewById(R.id.textView1);
textout2 = (TextView) findViewById(R.id.textView2);
textout3 = (TextView) findViewById(R.id.textView3);
b1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//--------- OutputStreamWriter ------------
try {
FileOutputStreamfOut=openFileOutput("settings1.dat", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write( "using fileoutput stream to write this to a file");
osw.flush();
osw.close();
}catch(Exception e){
e.printStackTrace(System.err);
}
String datax = "";
StringBuffer buffer = new StringBuffer();
//--------- InputStreamReader -------------------
try {
FileInputStream fIn = openFileInput("settings1.dat");
Reader reader = new InputStreamReader(fIn);
int data = reader.read(); // reads the next char
while(data != -1){
buffer.append((char)data);
data = reader.read();
}
reader.close();
} catch ( Exception e) {
e.printStackTrace();
}
textout1.setText( buffer.toString());
//--------------- FileWriter ---------------
try {
FileWriter fw = new FileWriter("settings1.dat");
BufferedWriter out = new BufferedWriter(fw);
//BufferedWriter out = new BufferedWriter(new FileWriter("settings1.dat"));
out.write("a String");
out.close();
} catch (Exception e){
e.printStackTrace();
textout2.setText(e.toString());
}
}
});
}
}
Problem is FileWriter Not working ( for file "settings1.dat")
but OutputStreamWriter and InputStreamReader does work ( for file "settings1.dat")
the code shows writing then reading to file "settings1.dat" Is ok with Stream Witer/Reader...
But FileWriter code get error message Filenotfoundexception "read-only file system"
So why does one technique work on the same File and the other doesn´t
Can you please tell what Iam missing -- thanks Trevor
I'm guessing your problem is you just aren't getting an IOException. You could try changing
catch(IOException e)
to
catch(Exception e)
This will then catch all exceptions which extend the Exception object (it will not catch Errors though). However, I don't have the tools to test out your code so you will have to try it out yourself and post the results.
Best of luck.
Related
How to transfer a file(unknown extension ie maybe a pdf/word/jpeg) from PC to Android Phone using Socket Programming. The Android Phone should be able to detect the type of file transfer and should be able to open it thereafter. Also the file should go into a specific folder named after app name in External storage.
I have tried following solution. However in this case, when I select the file to be transferred, the file transferred at Android side is of arbitrary size and not of the same size as of file selected, it is of some random size. Also the file transferred cannot be opened as it does not have a fixed extension.
Any help would be appreciated.
Android code(To receive file)
package minor.subham.com.pccontrol;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import java.net.*;
import java.io.*;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class getFile extends ActionBarActivity {
ImageView getFile;
public final static int SOCKET_PORT = Constants.SERVER_PORT; // you may change this
public final static String SERVER = Constants.SERVER_IP; // localhost
public final static int FILE_SIZE = 6022386; // file size temporary hard coded
// should bigger than the file to be downloaded
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_file);
getFile = (ImageView) findViewById(R.id.getFile);
getFile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Thread thread = new Thread() {
#Override
public void run() {
while(true) {
int bytesRead;
int current = 0;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
Socket sock = null;
final File file;
file = new File(Environment.getExternalStorageDirectory(), "PcControl");
try {
sock = new Socket(SERVER, SOCKET_PORT);
System.out.println("Connecting...");
// receive file
byte [] mybytearray = new byte [FILE_SIZE];
InputStream is = sock.getInputStream();
// fos = new FileOutputStream(FILE_TO_RECEIVED);
try {
fos = new FileOutputStream(file);
} catch (IOException e) {
e.printStackTrace();
}
bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray, 0 , current);
bos.flush();
fos.write(mybytearray);
fos.close();
System.out.println("File "
+ " downloaded (" + current + " bytes read)");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
if (bos != null) try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
if (sock != null) try {
sock.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
};
thread.start();
}
});
}
}
And Her is the Java Code to send file. Suppose I want to send file temp.jpg
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class send {
public final static int SOCKET_PORT = 8991; // you may change this
public final static String FILE_TO_SEND = "temp.jpg"; // you may change this
public static void main (String [] args ) throws IOException {
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
ServerSocket servsock = null;
Socket sock = null;
try {
servsock = new ServerSocket(SOCKET_PORT);
// while (true) {
System.out.println("Waiting...");
try {
sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
// send file
File myFile = new File (FILE_TO_SEND);
byte [] mybytearray = new byte [(int)myFile.length()];
fis = new FileInputStream(myFile);
bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
os = sock.getOutputStream();
System.out.println("Sending " + FILE_TO_SEND + "(" + mybytearray.length + " bytes)");
os.write(mybytearray,0,mybytearray.length);
os.flush();
System.out.println("Done.");
}
finally {
if (bis != null) bis.close();
if (os != null) os.close();
if (sock!=null) sock.close();
}
// }
}
finally {
if (servsock != null) servsock.close();
}
}
}
So I'm trying to make a todo list on Android where I can add items which then dynamically show in the list. So when I enter text in a text field and then press the add button, the list is expanded with the item I just created. This all goes well, but not if I completely get the application out of my memory stack and then restart it. When I reopen the application the list only consists of one item, the last item I added to the list before I closed the app. This is my code:
package be.oefeningen.filestorage;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.view.View.OnClickListener;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.io.InputStreamReader;
public class FileStorageActivity extends ListActivity implements OnClickListener {
private ArrayList<String> values=new ArrayList<String>();
InputStream inputStream;
String line;
#Override
public void onClick(View v) {
EditText editText=(EditText) findViewById(R.id.editText);
String tekst=editText.getText().toString()+"\n";
FileOutputStream outputStream;
try {
outputStream=openFileOutput("todoitems",MODE_PRIVATE);
outputStream.write(tekst.getBytes());
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream = openFileInput("todoitems");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
line = reader.readLine();
if (line != null){
values.add(line);
} else {
inputStream.close();
}
}catch (Exception e)
{
e.printStackTrace();
}
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,values);
setListAdapter(adapter);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
inputStream = openFileInput("todoitems");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
line = reader.readLine();
while (line != null){
values.add(line);
line = reader.readLine();
}
inputStream.close();
}catch (Exception e)
{
e.printStackTrace();
}
setContentView(R.layout.activity_file_storage);
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,values);
setListAdapter(adapter);
}
}
Probable reason is, everytime you write to the file, you are losing the old data.
Replace this line
outputStream=openFileOutput("todoitems",MODE_PRIVATE);
with this line
outputStream=openFileOutput("todoitems", MODE_PRIVATE | MODE_APPEND);
I want to connect to my server building in Android, but I can't, I don't know how to connect it. I think my code is fine. I changed Manifest with Permission INTERNET.
package com.android.server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener{
/** Called when the activity is first created. */
private static String TAG = "ServerSocketTest";
EditText edittext1;
private ServerSocket server;
Runnable conn = new Runnable() {
public void run() {
try {
edittext1.setText("Esperando0");
server = new ServerSocket(9999);
edittext1.setText("Esperando1");
while (true) {
edittext1.setText("Esperando2");
Socket socket = server.accept();
if(socket.isConnected() == true){
edittext1.setText("socket is connected: " + socket.getRemoteSocketAddress().toString());
}
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str = in.readLine();
Toast.makeText(getApplicationContext(), "BufferedReader ready", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
Log.i("received response from server", str);
edittext1.setText("Conectado");
PrintWriter salida = new PrintWriter(new OutputStreamWriter( socket.getOutputStream() ),true );
salida.println("Conexion establecida");
in.close();
socket.close();
}
} catch (IOException e) {
Log.e(TAG, e.getMessage());
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
};
#SuppressLint({ "NewApi", "NewApi", "NewApi", "NewApi" })
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
edittext1 = (EditText)findViewById(R.id.editText1);
Button boton1 = (Button)findViewById(R.id.button1);
boton1.setOnClickListener(this);
new Thread(conn).start();
}
#Override
protected void onPause() {
super.onPause();
if (server != null) {
try {
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void onClick(View v) {
}
}
My client, it work very well.:
package com.clientesocketandroid;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class ClienteSocketAndroid extends Activity implements OnClickListener{
String IP,mensaje, MensajeEntrada;
int Port;
Socket socket;
ServerSocket SSocket;
PrintWriter out;
Button boton1, boton2,boton3;
EditText edittext1,edittext2,edittext3,edittext4;
TextView textview5;
String mClientMsg = "";
Thread myCommsThread = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cliente_socket_android);
boton1 = (Button)findViewById(R.id.button1);
boton1.setOnClickListener(this);
boton2 = (Button)findViewById(R.id.button2);
boton2.setOnClickListener(this);
boton3 = (Button)findViewById(R.id.button3);
boton3.setOnClickListener(this);
edittext1 = (EditText)findViewById(R.id.editText1);
edittext2 = (EditText)findViewById(R.id.editText2);
edittext3 = (EditText)findViewById(R.id.editText3);
edittext4 = (EditText)findViewById(R.id.editText4);
Port = Integer.parseInt(edittext3.getText().toString());
try {
SSocket = new ServerSocket(Port);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
socket = SSocket.accept();
Toast.makeText(getApplicationContext(), "Listo", Toast.LENGTH_SHORT).show();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
MensajeEntrada = in.readLine();
edittext4.setText(MensajeEntrada);
} catch (Exception e) {
e.printStackTrace();
}
}
#SuppressLint({ "NewApi", "NewApi", "NewApi" })
public void onClick(View arg0) {
if(arg0.getId() == R.id.button1){
try {
IP = edittext2.getText().toString();
Port = Integer.parseInt(edittext3.getText().toString());
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
socket = new Socket(IP, Port); //Abre un socket con el número de IP y de puerto.
if(socket.isConnected() == true){
Toast.makeText(getApplicationContext(), "Conectado", Toast.LENGTH_SHORT).show();
}
} catch (UnknownHostException e) {
e.printStackTrace();
edittext1.setText(e.getMessage() + ": " + e.getCause());
} catch (IOException e) {
e.printStackTrace();
edittext1.setText(e.getMessage() + ": " + e.getCause());
}
}
if(arg0.getId() == R.id.button3){
try {
mensaje = edittext1.getText().toString();
PrintWriter salida = new PrintWriter(new OutputStreamWriter( socket.getOutputStream() ),true );
salida.println(mensaje);
edittext1.setText("");
//hace falta concatenacion
edittext4.setText("" + "\n" + mensaje + "");
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Mensaje NO enviado", Toast.LENGTH_SHORT).show();
}
}
if(arg0.getId() == R.id.button2){
try {
PrintWriter salida = new PrintWriter(new OutputStreamWriter( socket.getOutputStream() ),true );
salida.println("bye");
Toast.makeText(getApplicationContext(), "Conexión cerrada", Toast.LENGTH_SHORT).show();
socket.close();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Error al cerrar sesion", Toast.LENGTH_SHORT).show();
}
}
}
}
I thank your Help!!
The algorithm shows that whenever your socket is connected or not, you always create a buffered i/O stream and sending the data
The following is my suggested pseudo code for server
try(socket successfully connected) {
try( server is synchronized with the client) socket.accept();
// create the Object I/O stream
} show error
for Client
//Create a new socket with IP address and port number
try
client connect to server with aforementioned parameters with timeout
create a Object I/O stream
catch (IOException)
One problem that I see with your code is, you cannot update Ui elements from Non Ui thread, that is why it is raising exception, but you have caught all the exceptions.
So remove all setText calls from the runnable.
edittext1.setText("Conectado");
Use runonUithread or any other methods to update UI elements, and do not catch all exceptions like you have done. It is quite difficult to debug.
Can I change the contrast of an image from the byte stream of the Image? I have done necessary to do copying the image and I need to add the change contrast part to the code.
Any idea how to do this? Or is it even possible?
package make.image.bw;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
public class MakeImageBWActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); // set screen view
String imageInSD = Environment.getExternalStorageDirectory().getAbsolutePath() +"/earthglobe.jpg";
RandomAccessFile file = null;
try {
file = new RandomAccessFile(imageInSD, "r");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
File myFile = new File(Environment.getExternalStorageDirectory(), "latestearth.jpg");
byte[] buffer = new byte[1024];
try {
FileOutputStream out = new FileOutputStream(myFile);
while(file.read(buffer)!=-1){
out.write(buffer,0,1024);
}
out.close();
} catch (IOException e) {
e.printStackTrace();
}
Log.d("tag", "finished");
finish();
}
}
Thanking You in advance for your valuable suggestions.
You should try to look at that Google IO 2012 session : Doing More With Less: Being a Good Android Citizen
There is a good demo of image manipulation with RenderScript at 22min30.
The code of the presentation can be found here
i tried to upload the image to the server for two days but i could not post the image .the coding is compiled and run sucessfully but the imag is not write into the server.
this is my coding:
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.Toast;
public class sde extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
loadtoUrl("http://
");
}
private void loadtoUrl(String string) {
// TODO Auto-generated method stub
try {
String pathToOurFile = "/sdcard/tamil.PNG";
FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) );
BufferedInputStream bis = new BufferedInputStream(fileInputStream,3000);
byte[] bt=new byte[bis.available()];
HttpURLConnection connection = (HttpURLConnection)new URL(string).openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.connect();
FileOutputStream input = (FileOutputStream) connection.getOutputStream();
input.write(bt);
} catch (MalformedURLException e) {
Context context = null;
int duration = 0;
Toast.makeText(context, "erro in writing", duration);
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
here is a nice article, http://blog.sptechnolab.com/2011/03/09/android/android-upload-image-to-server/. It contains an example that will upload an image and write it at server side. It works.
public boolean fileUpload(Map<String , String> params, ByteArrayOutputStream file, String link) throws Throwable{
Account user = Util.getAccount(getApplicationContext());
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(link);
MultipartEntity multipartContent = new MultipartEntity();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String , String> entry : params.entrySet()) {
multipartContent.addPart(entry.getKey(),new StringBody(entry.getValue(),Charset.forName(HTTP.UTF_8)));
}
}
byte[] data = file.toByteArray();
ByteArrayBody img = new ByteArrayBody(data, "capture.jpg");
multipartContent.addPart("image",img);
postRequest.setEntity(multipartContent);
HttpResponse res = httpClient.execute(postRequest);
res.getEntity().getContent().close();
return true;
}catch(Throwable e){
throw e;
}
}