I'm tryin to do Socket program between Java(pc) and Android.APP selects a image from gallery.Displays the image which i selected.And send to Java pc with socket.I want change this code to AsyncTask but i couldnt do it.i read about example about AsyncTask but how can i turn this code.Can anyone help me to solve this problem?
public class SendfileActivity extends Activity {
/** Called when the activity is first created. */
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
private ImageView img;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
System.out.println("34");
img = (ImageView) findViewById(R.id.ivPic);
System.out.println("36");
((Button) findViewById(R.id.bBrowse))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
System.out.println("40");
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Select Picture"),
SELECT_PICTURE);
System.out.println("47");
}
});
;
System.out.println("51");
Button send = (Button) findViewById(R.id.bSend);
final TextView status = (TextView) findViewById(R.id.tvStatus);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Socket sock;
try {
sock = new Socket("192.168.0.3", 27015);
System.out.println("Connecting...");
// sendfile
File myFile = new File (selectedImagePath);
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
sock.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
TextView path = (TextView) findViewById(R.id.tvPath);
path.setText("Image Path : " + selectedImagePath);
img.setImageURI(selectedImageUri);
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
AsyncTask is not required for socket communication in here as there is no UI element is touched. Instead you can use Thread and Runnable.
If there is constant message passing between Client and Server then one can use combination of HandlerThread and Handlerto make it happen.
For simple Thread usage in here you can :
class SocketThread implements Runnable {
#Override
public void run() {
Socket sock;
try {
sock = new Socket("192.168.0.3", 27015);
System.out.println("Connecting...");
// sendfile
File myFile = new File(selectedImagePath);
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray, 0, mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray, 0, mybytearray.length);
os.flush();
sock.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
and can start this runnable on onClick of send button
new Thread(new SocketThread()).start();
I hope this helps
If you do want to use an AsyncTask:
public class ImagePicker extends AsyncTask<String, String, String> {
protected String doInBackground(String imgPath) {
//Your socket code here from the onclick
}
protected void onProgressUpdate(String progressString) {
System.out.println("Sending...");
}
protected void onPostExecute(String result) {
// print result
sock.close();
}
}
And then you can execute the task in your onclick:
send.setOnClickListener{
new ImagePicker().execute(imgPathString);
}
Related
I am making server-client program, the server is Java on the computer and the client is android app (android studio) and I try to send image from the server to the client, and to show this image on the client's screen by ImageView. The problem is that sometimes its work and sometimes it doesn't work. Looks like there are times that ByteArrayOutputStream.size() return negative value in the client side in the variable len (that keep the length). When the return value is positive it works. Why am I getting negative values (sometimes)?
Server code:
public class Server extends JFrame {
BufferedImage bi,inputImage;
JButton btn;
ServerSocket serverSocket;
Socket socket;
private Scanner in;
private PrintWriter out;
public Server(){
File imageFile = new File("ssss.PNG");
try {
bi = ImageIO.read(imageFile);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
this.add(btn = new JButton("Send"), BorderLayout.NORTH);
this.add(new JLabel(new ImageIcon(bi)), BorderLayout.CENTER);
this.setSize(200, 180);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
try{
serverSocket = new ServerSocket(8000);
socket = serverSocket.accept();
in = new Scanner(socket.getInputStream());
out = new PrintWriter(socket.getOutputStream(), true);
}
catch(IOException ex){
System.err.println(ex);
}
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
out.println("IMAGE");
sendImage(new File("ssss.PNG"));
// try {
// ImageIO.write(bi, "PNG", socket.getOutputStream());
//} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
// }
}
});
}
public static void main(String[] args) {
new Server();
}
public void sendImage(File file){
try {
DataOutputStream out = new DataOutputStream(
socket.getOutputStream());
DataInputStream dis = new DataInputStream(new FileInputStream(file));
ByteArrayOutputStream ao = new ByteArrayOutputStream();
int read = 0;
byte[] buf = new byte[dis.available()];
while ((read = dis.read(buf)) > -1) {
ao.write(buf, 0, read);
}
System.out.println("ao.size(): "+ao.size());
out.writeInt(ao.size());
out.write(ao.toByteArray());
out.flush();
// out.close();
// dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client code(android):
public class MainActivity extends AppCompatActivity {
public Socket socket;
public PrintWriter out;
public Scanner in;
public TextView textView;
public DataOutputStream dos=null;
public DataInputStream dis=null;
public ImageView imageView;
public Bitmap bitmap;
private static final int SERVERPORT = 8000;
private static final String SERVER_IP = "192.168.5.59";
public static final String TAG="TAG";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=(TextView)findViewById(R.id.text);
imageView=(ImageView)findViewById(R.id.imageView);
imageView.setImageResource(R.drawable.ic_launcher_background);
new Thread(new ClientThread()).start();
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
Log.d(TAG, "try to connect...");
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
in = new Scanner(socket.getInputStream());
out = new PrintWriter(socket.getOutputStream(), true);
Log.d(TAG, "connected1234");
while (in.hasNextLine()) {
String response = in.nextLine();
if (response.startsWith("IMAGE")) {
InputStream in = socket.getInputStream();
Log.d(TAG, "in: "+in);
DataInputStream input = new DataInputStream(in);
Log.d(TAG, "input: "+input);
byte[] data;
int len= input.readInt();
Log.d(TAG, "len: "+len);
data = new byte[len];
Log.d(TAG, "data: "+data);
if (len > 0) {
input.readFully(data,0,data.length);
}
final Bitmap bitmap = BitmapFactory.decodeByteArray(data , 0, data .length);
Log.d(TAG, "Bitmap: "+bitmap);
runOnUiThread(new Runnable() {
#Override
public void run() {
imageView.setImageBitmap(bitmap);
}
});
}
}
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
The error:
len: -298696669
E/AndroidRuntime: FATAL EXCEPTION: Thread-5
Process: com.example.sendimageexample, PID: 17224
java.lang.NegativeArraySizeException: -298696669
at com.example.sendimageexample.MainActivity$ClientThread.run(MainActivity.java:80)
at java.lang.Thread.run(Thread.java:784)`
I solved it!
client code:
public class MainActivity extends AppCompatActivity {
public Socket socket;
public ImageView imageView;
private static final int SERVERPORT = 8000;
private static final String SERVER_IP = "192.168.5.59";
public static final String TAG="TAG";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView=(ImageView)findViewById(R.id.imageView);
imageView.setImageResource(R.drawable.ic_launcher_background);
new Thread(new ClientThread()).start();
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
Log.d(TAG, "try to connect...");
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
Log.d(TAG, "Adder: "+serverAddr);
socket = new Socket(serverAddr, SERVERPORT);
InputStream in = socket.getInputStream();
Log.d(TAG, "in: "+in);
DataInputStream input = new DataInputStream(in);
Log.d(TAG, "input: "+input);
Log.d(TAG, "connected1234");
byte[] data;
int len= input.readInt();//-298696669//17976
Log.d(TAG, "len: "+len);
data = new byte[len];
Log.d(TAG, "data: "+data);
if (len > 0) {
input.readFully(data,0,data.length);
}
final Bitmap bitmap = BitmapFactory.decodeByteArray(data , 0, data
.length);
Log.d(TAG, "Bitmap: "+bitmap);
runOnUiThread(new Runnable() {
#Override
public void run() {
imageView.setImageBitmap(bitmap);
}
});
ByteArrayOutputStream bos =new ByteArrayOutputStream();
Bitmap bitmap1=BitmapFactory.decodeResource(getResources(),R.drawable.image22);
Log.d(TAG, "bitmap1: "+bitmap1);
bitmap1.compress(Bitmap.CompressFormat.PNG,0,bos);
byte []array=bos.toByteArray();
OutputStream outputStream=socket.getOutputStream();
DataOutputStream dos=new DataOutputStream(outputStream);
dos.writeInt(bos.size());
dos.write(array,0,array.length);
Log.d(TAG, "bos.size: "+bos.size());
Log.d(TAG, "bos.array: "+bos.toByteArray());
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
server code:
public class Server extends JFrame {
BufferedImage bi,inputImage;
JButton btn;
ServerSocket serverSocket;
Socket socket;
private Scanner in;
private PrintWriter out;
Server jframe=this;
public Server(){
File imageFile = new File("ssss.PNG");
try {
bi = ImageIO.read(imageFile);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
this.add(btn = new JButton("Send"), BorderLayout.NORTH);
//this.add(new JLabel(new ImageIcon(bi)), BorderLayout.CENTER);
this.setSize(200, 180);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
try{
serverSocket = new ServerSocket(8000);
socket = serverSocket.accept();
in = new Scanner(socket.getInputStream());
out = new PrintWriter(socket.getOutputStream(), true);
}
catch(IOException ex){
System.err.println(ex);
}
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
sendImage(new File("ssss.PNG"));
InputStream inputStream;
try {
inputStream = socket.getInputStream();
DataInputStream dis=new DataInputStream(inputStream);
int size = dis.readInt();
System.out.println("size: "+size);
byte[] imageAr = new byte[size];
dis.readFully(imageAr);
System.out.println("imageAr: "+imageAr);
System.out.println("dis: "+dis);
BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageAr));
jframe.add(new JLabel(new ImageIcon(image)), BorderLayout.CENTER);
revalidate();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// try {
// ImageIO.write(bi, "PNG", socket.getOutputStream());
//} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
// }
}
});
}
public static void main(String[] args) {
new Server();
}
public void sendImage(File file){
try {
DataOutputStream out = new DataOutputStream(
socket.getOutputStream());
DataInputStream dis = new DataInputStream(new FileInputStream(file));
ByteArrayOutputStream ao = new ByteArrayOutputStream();
int read = 0;
byte[] buf = new byte[dis.available()];
while ((read = dis.read(buf)) > -1) {
ao.write(buf, 0, read);
System.out.println("read: "+read);
System.out.println("buf: "+buf);
}
System.out.println("ao.size(): "+ao.size());
out.writeInt(ao.size());
System.out.println("ao.toByteArray(): "+ao.toByteArray());
out.write(ao.toByteArray());
out.flush();
// out.close();
// dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I want to send the data(picture taken to wampserver). How does it work?
public class MainActivity extends Activity {
ImageView picture;
Button button;
static final int CAM_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button takePicture = (Button) findViewById(R.id.button);
ImageView picture = (ImageView) findViewById(R.id.imageView);
takePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = getfile();
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
//startActivityForResult(intent, 0);
startActivityForResult(intent, CAM_REQUEST);
}
});
}
private File getfile()
{
File folder = new File ("localhost:8080/sampleTest.php");
if (!folder.exists())
{
folder.mkdir();
}
File image_file = new File(folder, "cam_image.jpg");
return image_file;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
//super.onActivityResult(requestCode, resultCode, data);
//Bitmap bitmap = (Bitmap)data.getExtras().get("data");
//picture.setImageBitmap(bitmap);
String path = "localhost:8080/sampleTest.php/cam_image.jpg";
picture.setImageDrawable(Drawable.createFromPath(path));
}
}
I expect the output to take a picture. After taking a picture, send the picture to "localhost:8080/sampleTest.php". However, what i am getting is that i am only able to take a picture, I could not send the picture to wampserver.
Call camera app with intent:
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);
Get the thumbnail returned from the camera:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0 && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(imageBitmap);
}}
If you want to get an image with better quality, you need to provide an image saving path to the camera app.
Therefore, add the permissions to AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Improve the intent:
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
Intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(intent, 0);
Decode the image file when the result is returned:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0 && resultCode == Activity.RESULT_OK) {
setPic();
}}
private void setPic() {
// Get the dimensions of the View
int targetW = mImageView.getWidth();
int targetH = mImageView.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
mImageView.setImageBitmap(bitmap);}
Image Transmission from Android Client to Server
Now, we can combine the two functionalities to enhance the Android application.
To access the Internet, add the following permission to AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
Refer to this blog, create a class MultipartEntity:
public class MultipartEntity implements HttpEntity {
private String boundary = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
boolean isSetLast = false;
boolean isSetFirst = false;
public MultipartEntity() {
this.boundary = System.currentTimeMillis() + "";
}
public void writeFirstBoundaryIfNeeds(){
if(!isSetFirst){
try {
out.write(("--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
}
}
isSetFirst = true;
}
public void writeLastBoundaryIfNeeds() {
if(isSetLast){
return ;
}
try {
out.write(("\r\n--" + boundary + "--\r\n").getBytes());
} catch (final IOException e) {
}
isSetLast = true;
}
public void addPart(final String key, final String value) {
writeFirstBoundaryIfNeeds();
try {
out.write(("Content-Disposition: form-data; name=\"" +key+"\"\r\n").getBytes());
out.write("Content-Type: text/plain; charset=UTF-8\r\n".getBytes());
out.write("Content-Transfer-Encoding: 8bit\r\n\r\n".getBytes());
out.write(value.getBytes());
out.write(("\r\n--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
}
}
public void addPart(final String key, final String fileName, final InputStream fin){
addPart(key, fileName, fin, "application/octet-stream");
}
public void addPart(final String key, final String fileName, final InputStream fin, String type){
writeFirstBoundaryIfNeeds();
try {
type = "Content-Type: "+type+"\r\n";
out.write(("Content-Disposition: form-data; name=\""+ key+"\"; filename=\"" + fileName + "\"\r\n").getBytes());
out.write(type.getBytes());
out.write("Content-Transfer-Encoding: binary\r\n\r\n".getBytes());
final byte[] tmp = new byte[4096];
int l = 0;
while ((l = fin.read(tmp)) != -1) {
out.write(tmp, 0, l);
}
out.flush();
} catch (final IOException e) {
} finally {
try {
fin.close();
} catch (final IOException e) {
}
}
}
public void addPart(final String key, final File value) {
try {
addPart(key, value.getName(), new FileInputStream(value));
} catch (final FileNotFoundException e) {
}
}
#Override
public long getContentLength() {
writeLastBoundaryIfNeeds();
return out.toByteArray().length;
}
#Override
public Header getContentType() {
return new BasicHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
}
#Override
public boolean isChunked() {
return false;
}
#Override
public boolean isRepeatable() {
return false;
}
#Override
public boolean isStreaming() {
return false;
}
#Override
public void writeTo(final OutputStream outstream) throws IOException {
outstream.write(out.toByteArray());
}
#Override
public Header getContentEncoding() {
return null;
}
#Override
public void consumeContent() throws IOException,
UnsupportedOperationException {
if (isStreaming()) {
throw new UnsupportedOperationException(
"Streaming entity does not implement #consumeContent()");
}
}
#Override
public InputStream getContent() throws IOException,
UnsupportedOperationException {
return new ByteArrayInputStream(out.toByteArray());
}}
Use AsyncTask to process the uploading work:
private class UploadTask extends AsyncTask<Bitmap, Void, Void> {
protected Void doInBackground(Bitmap... bitmaps) {
if (bitmaps[0] == null)
return null;
Bitmap bitmap = bitmaps[0];
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); // convert Bitmap to ByteArrayOutputStream
InputStream in = new ByteArrayInputStream(stream.toByteArray()); // convert ByteArrayOutputStream to ByteArrayInputStream
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost(
"http://192.168.8.84:8003/savetofile.php"); // server
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("myFile",
System.currentTimeMillis() + ".jpg", in);
httppost.setEntity(reqEntity);
Log.i(TAG, "request " + httppost.getRequestLine());
HttpResponse response = null;
try {
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (response != null)
Log.i(TAG, "response " + response.getStatusLine().toString());
} finally {
}
} finally {
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast.makeText(MainActivity.this, R.string.uploaded, Toast.LENGTH_LONG).show();
}
}
I am getting image from server and display it in my application,and I download that image and downloading is working fine,but when I check my gallery image is not showing there,then in dev tools-Media Scanner I scan my SD card and again check my gallery and then image is showing..so how can I solve it..even I tried it Samsung phone,but with device i need to reboot my device...following is my snippet code...
public class bBusinessCardDL extends Activity{
String[] NAMES = new String[1];
String[] CurID = new String[1];
String[] Detail = new String[1];
String[] Photo = new String[1];
ListView listview;
String BCard;
ImageView image;
Button btnDownload;
ProgressDialog mProgressDialog;
private String Id;
private ImageView bcks;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_bu_dl);
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + "/mnt/sdcard/")));
bcks=(ImageView)findViewById(R.id.bck_from_bcard);
bcks.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intss=new Intent(bBusinessCardDL.this,FirstPage.class);
startActivity(intss);
}
});
Id=this.getIntent().getStringExtra("userids");
System.out.println("checkd advertisement "+Id);
FillData();
btnDownload = (Button) findViewById(R.id.btnDownload);
btnDownload.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mDownloadAndSave();
Toast msgd = Toast.makeText(getBaseContext(),
"Business card Downloaded..!", Toast.LENGTH_LONG);
msgd.show();
}
});
}
public void mDownloadAndSave() {
File f = new File("/mnt/sdcard/" + Id
+ ".jpg");
//"/mnt/sdcard/"
InputStream is;
try {
is = new URL(BCard).openStream();
// Set up OutputStream to write data into image file.
OutputStream os = new FileOutputStream(f);
CopyStream(is, os);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MediaScannerConnection.scanFile(this, new String[] { "ur_file_path" },
null,
new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
}
});
}
public static void CopyStream(InputStream is, OutputStream os) {
final int buffer_size = 2048;
try {
byte[] bytes = new byte[buffer_size];
for (;;) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
}
} catch (Exception ex) {
}
}
public static String getJsonFromServer(String url) throws IOException {
BufferedReader inputStream = null;
URL jsonUrl = new URL(url);
URLConnection dc = jsonUrl.openConnection();
dc.setConnectTimeout(5000);
dc.setReadTimeout(5000);
inputStream = new BufferedReader(new InputStreamReader(
dc.getInputStream()));
// read the JSON results into a string
String jsonResult = inputStream.readLine();
return jsonResult;
}
static class ViewHolder {
TextView VHName;
ImageView VHPhoto;
int position;
}
public void FillData() {
String url = "";
url = "http://www.asdffsfd.com/web-service/b_card.php?user_id="
+ Id;
String jsonString;
jsonString = "";
try {
jsonString = getJsonFromServer(url);
} catch (IOException e) {
}
BCard = "";
try {
JSONArray earthquakes = new JSONArray(jsonString);
NAMES = new String[earthquakes.length()];
Photo = new String[earthquakes.length()];
for (int i = 0; i < earthquakes.length(); i++) {
JSONObject e = earthquakes.getJSONObject(i);
NAMES[i] = e.getString("b_card");
BCard = "http://" + e.getString("b_card");
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
BCard = BCard.replace("\\", "");
BCard = BCard.replace(" ", "%20");
ImageView i = (ImageView) findViewById(R.id.BUCARD);
Log.d("Bcard", BCard);
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(
BCard).getContent());
i.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
after save the image, use below code for scanning file:
MediaScannerConnection.scanFile(this, new String[] { f.getAbsolutePath()},
null,
new MediaScannerConnection.OnScanCompletedListener() {
#Override
public void onScanCompleted(String path, Uri uri) {
}
});
Am developing one android application which requires print option. I used the following code to do this in wifi printer, but it giving Networkonmainthread exception
try {
Socket sock = new Socket("192.168.199.245", 9100); // ip and port of printer
PrintWriter oStream = new PrintWriter(sock.getOutputStream());
oStream.println("\t\t Text to The Printer");
oStream.println("\n\n\n");
oStream.close();
sock.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Has anyone know how do this? i need a sample code for print in wifi printer.....thanks
My code is working:
WifiPrint.java
public class WifiPrint extends Activity { TextView printer_name,
gate_way, printer_port; int port = 9100; WifiManager wifi = null;
android.net.DhcpInfo d; String gateway_ip = "";
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wifi_print); wifi = (WifiManager)
getSystemService(Context.WIFI_SERVICE); printer_name = (TextView)
findViewById(R.id.textView1); gate_way = (TextView)
findViewById(R.id.textView2); printer_port = (TextView)
findViewById(R.id.textView3);
/* de.lohndirekt.print.IppPrintService svc = new IppPrintService(printerURI); InputStream stream = new
BufferedInputStream(new FileInputStream("image.epl")); DocFlavor
flavor = DocFlavor.INPUT_STREAM.AUTOSENSE; Doc myDoc = new
SimpleDoc(stream, flavor, null); DocPrintJob job =
svc.createPrintJob(); job.print(myDoc, null);*/
}
#Override public boolean onCreateOptionsMenu(Menu menu) { //
Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.wifi_print, menu); return true;
}
public void wifisettings(View v) { startActivityForResult(new
Intent(
android.provider.Settings.ACTION_WIFI_SETTINGS), 0); }
public void connectSocket(View v) {
/*Uri filepath=Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.pdfsample); Toast.makeText(this, filepath.getPath(), Toast.LENGTH_LONG).show(); */ ClientThread clientThread = new
ClientThread(""); Thread clientstartThread = new
Thread(clientThread); clientstartThread.start(); }
public String intToIp(int i) { return ((i & 0xFF) + "." + ((i >> 8)
& 0xFF) + "." + ((i >> 16) & 0xFF)
+ "." + ((i >> 24) & 0xFF)); }
#Override protected void onActivityResult(int requestCode, int
resultCode, Intent data) { // TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data); if
(requestCode == 0) { WifiInfo wifiinfo = wifi.getConnectionInfo();
d = wifi.getDhcpInfo();
printer_name.setText("Name:" + wifiinfo.getSSID()); gateway_ip =
intToIp(d.gateway); gate_way.setText("Printer Ip:" + gateway_ip);
printer_port.setText("Port:" + port);
} }
public File createFileFromInputStream(InputStream inputStream) {
try{
File f = new File("/sdcard/testpdf.pdf");
OutputStream outputStream = new FileOutputStream(f);
byte buffer[] = new byte[1024];
int length = 0;
while((length=inputStream.read(buffer)) > 0) {
outputStream.write(buffer,0,length);
}
outputStream.close();
inputStream.close();
return f;
}catch (IOException e) {
//Logging exception
}
return null; }
class ClientThread implements Runnable { String filepath = "";
BufferedInputStream bis = null; FileInputStream fis;
Socket socket;
public ClientThread(String filename) { filepath = filename; }
#Override public void run() { // TODO Auto-generated method
stub try {
InputStream in = getResources().openRawResource(R.raw.pdfsample);
createFileFromInputStream(in);
File pdfFile = new File("/sdcard/testpdf.pdf");
byte[] mybytearray = new byte[(int) pdfFile.length()];
socket = new Socket(gateway_ip, port);
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if(socket.isConnected()){
Toast.makeText(WifiPrint.this,
"Socket Connected",
Toast.LENGTH_LONG).show();
}
}
});
fis = new FileInputStream(pdfFile);
bis = new BufferedInputStream(fis);
bis.read(mybytearray, 0, mybytearray.length);
OutputStream os = socket.getOutputStream();
os.write(mybytearray, 0, mybytearray.length);
os.flush();
if (bis != null) {
bis.close();
os.close();
socket.close();
fis.close();
}
} catch (final UnknownHostException e) {
// TODO Auto-generated catch block
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(WifiPrint.this,
"UnHost Exceptions" + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}); } catch (final IOException e) {
// TODO Auto-generated catch block
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(WifiPrint.this,
"Io Exceptions" + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}); } finally {
try {
if (bis != null) {
bis.close();
socket.close();
fis.close();
}
} catch (final IOException e) {
// TODO Auto-generated catch block
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(
WifiPrint.this,
"Io Exeption in Closing Socket"
+ e.getMessage(), Toast.LENGTH_LONG)
.show();
}
});
} } }
}
}
And Add certain permssions in manifest file:
<uses-feature android:name="android.hardware.wifi" />
Just paste this code in your main activity..
StrictMode.setThreadPolicy(new Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
StrictMode.setVmPolicy(new VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());
I want to create file in internal memory of android.
then i have to attach it to email.
please help me.
I dont know where this file is stored.???
Read through http://developer.android.com/guide/topics/data/data-storage.html and if you still have questions, post something more specific.
Its easy and try / follow this, i hope it will help you
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonSend = (Button) findViewById(R.id.buttonSend);
textTo = (EditText) findViewById(R.id.editTextTo);
textSubject = (EditText) findViewById(R.id.editTextSubject);
textMessage = (EditText) findViewById(R.id.editTextMessage);
buttonSend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String to = textTo.getText().toString();
String subject = textSubject.getText().toString();
String message = textMessage.getText().toString();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("plain/text");
File data = null;
try {
Date dateVal = new Date();
String filename = dateVal.toString();
data = File.createTempFile("Report", ".csv");
FileWriter out = (FileWriter) GenerateCsv.generateCsvFile(
data, "Name,Data1");
i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(data));
i.putExtra(Intent.EXTRA_EMAIL, new String[] { to });
i.putExtra(Intent.EXTRA_SUBJECT, subject);
i.putExtra(Intent.EXTRA_TEXT, message);
startActivity(Intent.createChooser(i, "E-mail"));
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public class GenerateCsv {
public static FileWriter generateCsvFile(File sFileName,String fileContent) {
FileWriter writer = null;
try {
writer = new FileWriter(sFileName);
writer.append(fileContent);
writer.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally
{
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return writer;
}
}
Add this line in AndroidManifest.xml file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-
permission>
Here is the code for Create and Read a file,
public class ReadNWriteFile extends Activity {
final String TEST_STRING = new String("Hello Android");
final String FILE_NAME = "SAMPLEFILE.txt";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
fileCreate();
tv.setText(readFile());
setContentView(tv);
}
private void fileCreate() {
try {
OutputStream os = openFileOutput(FILE_NAME, MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(os);
osw.write(TEST_STRING);
osw.close();
} catch (Exception e) {
Log.i("ReadNWrite, fileCreate()", "Exception e = " + e);
}
}
private String readFile() {
try {
FileInputStream fin = openFileInput(FILE_NAME);
InputStreamReader isReader = new InputStreamReader(fin);
char[] buffer = new char[TEST_STRING.length()];
// Fill the buffer with data from file
isReader.read(buffer);
return new String(buffer);
} catch (Exception e) {
Log.i("ReadNWrite, readFile()", "Exception e = " + e);
return null;
}
}
}
To get path, /data/data/package_name/yourFile_Name