showing image in imageview using thread - android

hi every body im aymen and im student
im creating an application who shows the image downloaded from ftp server which was token by the webcam
i wanna refresh the pic every 2 seconds but i didnt succeed even with one time plz help this is my code until now
**mainActivity**
package com.pfe.ftpstreamer;
import java.io.FileOutputStream;
import com.pfe.ftpstreamer.R;
import com.pfe.ftpstreamer.MyFTPClient;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
public class MainActivity extends Activity implements OnClickListener {
private static final String TAG = "MainActivity";
private static final String TEMP_FILENAME = "test.txt";
private static final String TEMP_FILENAME1 = "cam.jpg";
private Context cntx = null;
MyFTPClient ftpclient = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cntx = this.getBaseContext();
View startButton = findViewById(R.id.button1);
startButton.setOnClickListener(this);
View stopButton = findViewById(R.id.button2);
stopButton.setOnClickListener(this);
View exitButton = findViewById(R.id.button3);
exitButton.setOnClickListener(this);
// Create a temporary file. You can use this to upload
createDummyFile();
ftpclient = new MyFTPClient();
}
public void onClick(View v) {
switch(v.getId()) {
case R.id.button1:
new Thread(new Runnable() {
public void run(){
boolean status = false;
// Replace your UID & PW here
status = ftpclient.ftpConnect("192.168.1.1", "Administrator", "12345", 21);
if (status == true) {
Log.d(TAG, "Connection Success");
status = ftpclient.ftpUpload(TEMP_FILENAME, TEMP_FILENAME, "/", cntx);
//downloading file
ftpclient.ftpDownload(TEMP_FILENAME1,getFilesDir() + "/" +TEMP_FILENAME1);
//removing the file from server
ftpclient.ftpRemoveFile(TEMP_FILENAME1);
//showing the file in the ImageView
new Thread(new Runnable() {
public void run(){
ImageView imgView = (ImageView) findViewById(R.id.imageView1);
imgView.setImageBitmap(BitmapFactory.decodeFile(getFilesDir() + "/" +TEMP_FILENAME1));
}
}).start();
} else {
//Toast.makeText(getApplicationContext(), "Connection failed", 2000).show();
Log.d(TAG, "Connection failed");
}
}
}).start();
break;
case R.id.button2:
new Thread(new Runnable() {
public void run(){
ftpclient.ftpDisconnect();
}
}).start();
break;
case R.id.button3:
this.finish();
break;
}
}
public void createDummyFile() {
try {
FileOutputStream fos;
String file_content = "Hi this is a sample file to upload for android FTP client example";
fos = openFileOutput(TEMP_FILENAME, MODE_PRIVATE);
fos.write(file_content.getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
#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;
}}
*myftpclient**
package com.pfe.ftpstreamer;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.commons.net.ftp.*;
import android.content.Context;
import android.util.Log;
public class MyFTPClient {
//Now, declare a public FTP client object.
private static final String TAG = "MyFTPClient";
public FTPClient mFTPClient = null;
//Method to connect to FTP server:
public boolean ftpConnect(String host, String username ,
String password, int port)
{
try {
mFTPClient = new FTPClient();
// connecting to the host
mFTPClient.connect(host, port);
// now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// login using username & password
boolean status = mFTPClient.login(username, password);
/* Set File Transfer Mode
*
* To avoid corruption issue you must specified a correct
* transfer mode, such as ASCII_FILE_TYPE, BINARY_FILE_TYPE,
* EBCDIC_FILE_TYPE .etc. Here, I use BINARY_FILE_TYPE
* for transferring text, image, and compressed files.
*/
mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
mFTPClient.enterLocalPassiveMode();
return status;
}
} catch(Exception e) {
Log.d(TAG, "Error: could not connect to host " + host );
}
return false;
}
//Method to disconnect from FTP server:
public boolean ftpDisconnect()
{
try {
mFTPClient.logout();
mFTPClient.disconnect();
return true;
} catch (Exception e) {
Log.d(TAG, "Error occurred while disconnecting from ftp server.");
}
return false;
}
//Method to get current working directory:
//Method to change working directory:
//Method to list all files in a directory:
//Method to create new directory:
//Method to delete/remove a directory:
//Method to delete a file:
public boolean ftpRemoveFile(String filePath)
{
try {
boolean status = mFTPClient.deleteFile(filePath);
return status;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
//Method to rename a file:
//Method to download a file from FTP server:
/**
* mFTPClient: FTP client connection object (see FTP connection example)
* srcFilePath: path to the source file in FTP server
* desFilePath: path to the destination file to be saved in sdcard
*/
public boolean ftpDownload(String srcFilePath, String desFilePath)
{
boolean status = false;
try {
FileOutputStream desFileStream = new FileOutputStream(desFilePath);;
status = mFTPClient.retrieveFile(srcFilePath, desFileStream);
desFileStream.close();
return status;
} catch (Exception e) {
Log.d(TAG, "download failed");
}
return status;
}
//Method to upload a file to FTP server:
/**
* mFTPClient: FTP client connection object (see FTP connection example)
* srcFilePath: source file path in sdcard
* desFileName: file name to be stored in FTP server
* desDirectory: directory path where the file should be upload to
*/
public boolean ftpUpload(String srcFilePath, String desFileName,
String desDirectory, Context context)
{
boolean status = false;
try {
// FileInputStream srcFileStream = new FileInputStream(srcFilePath);
FileInputStream srcFileStream = context.openFileInput(srcFilePath);
// change working directory to the destination directory
//if (ftpChangeDirectory(desDirectory)) {
status = mFTPClient.storeFile(desFileName, srcFileStream);
//}
srcFileStream.close();
return status;
}
catch (Exception e) {
Log.d(TAG, "upload failed: " + e);
}
return status;
}
}

You should check that image is downloaded or not, if its downloaded then you can update your UI in ui thread i.e.
mainActivity.this.runOnUiThread(new Runnable() {
public void run() {
ImageView imgView = (ImageView) findViewById(R.id.imageView1);
imgView.setImageBitmap(BitmapFactory.decodeFile(getFilesDir() + "/" +TEMP_FILENAME1));
}
}

Ok, your problem is, that you are not in the UI-Thread.
You could use a AsyncTask or a Handler, which updates your view or layout.
Check this out: update-ui-from-thread

You can't update Your Ui direct from your thread use handler for that purpose
check this link

Related

Creating a vpn profile and connencting (PPTP) with username and password in android programmatically

I want to build an app that can connect with a single click of button which will create a vpn profile and connect to the vpn profile by parsig the username and password of the vpn server.
The code that is developed and modified is good to create and connect vpn but my vpn requires username and password to be entered so i want to do that programatically.
Here is my project
VpnClient.java
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.VpnService;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class VpnClient extends AppCompatActivity{
public interface Prefs {
String NAME = "connection";
String SERVER_ADDRESS = "server.address";
String SERVER_PORT = "server.port";
String SHARED_SECRET = "shared.secret";
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button disconnect = (Button) findViewById(R.id.disconnect);
Button connect = (Button) findViewById(R.id.connect);
// final TextView serverAddress = (TextView) findViewById(R.id.address);
//final TextView serverPort = (TextView) findViewById(R.id.port);
// final TextView sharedSecret = (TextView) findViewById(R.id.secret);
final SharedPreferences prefs = getSharedPreferences(Prefs.NAME, MODE_PRIVATE);
final String serverAddress = ""; !!I insert my vpnserver address in here which is my.vpnserver.com
final String serverPort = ""; !!As server port i am using 1723 for PPTP connection
connect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
prefs.edit()
.putString(Prefs.SERVER_ADDRESS,"")
.putString(Prefs.SERVER_PORT, "")
.putString(Prefs.SHARED_SECRET, "")
.commit();
Intent intent = VpnService.prepare(VpnClient.this);
if (intent != null) {
startActivityForResult(intent, 0);
} else {
onActivityResult(0, RESULT_OK, null);
}
}
});
disconnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startService(getServiceIntent().setAction(MyVpnService.ACTION_DISCONNECT));
}
});
}
#Override
protected void onActivityResult(int request, int result, Intent data) {
if (result == RESULT_OK) {
startService(getServiceIntent().setAction(MyVpnService.ACTION_CONNECT));
}
}
private Intent getServiceIntent() {
return new Intent(this, MyVpnService.class);
}
}
MyVpnService.java
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelFileDescriptor;
import android.support.annotation.RequiresApi;
import android.support.v4.util.Pair;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.LogRecord;
public class MyVpnService extends andenter code hereroid.net.VpnService implements android.os.Handler.Callback {
private static final String TAG = MyVpnService.class.getSimpleName();
public static final String ACTION_CONNECT = "com.yaksh.vpn.START";
public static final String ACTION_DISCONNECT = "com.yaksh.vpn.STOP";
private Handler mHandler;
private static class Connection extends Pair<Thread, ParcelFileDescriptor> {
public Connection(Thread thread, ParcelFileDescriptor pfd) {
super(thread, pfd);
}
}
private final AtomicReference<Thread> mConnectingThread = new AtomicReference<>();
private final AtomicReference<Connection> mConnection = new AtomicReference<>();
private AtomicInteger mNextConnectionId = new AtomicInteger(1);
private PendingIntent mConfigureIntent;
#Override
public void onCreate() {
// The handler is only used to show messages.
if (mHandler == null) {
mHandler = new Handler(this);
}
// Create the intent to "configure" the connection (just start ToyVpnClient).
mConfigureIntent = PendingIntent.getActivity(this, 0, new Intent(this, VpnClient.class),
PendingIntent.FLAG_UPDATE_CURRENT);
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null && ACTION_DISCONNECT.equals(intent.getAction())) {
disconnect();
return START_NOT_STICKY;
} else {
connect();
return START_STICKY;
}
}
#Override
public void onDestroy() {
disconnect();
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public boolean handleMessage(Message message) {
Toast.makeText(this, message.what, Toast.LENGTH_SHORT).show();
if (message.what != R.string.disconnected) {
updateForegroundNotification(message.what);
}
return true;
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
private void connect() {
// Become a foreground service. Background services can be VPN services too, but they can
// be killed by background check before getting a chance to receive onRevoke().
updateForegroundNotification(R.string.connecting);
mHandler.sendEmptyMessage(R.string.connecting);
// Extract information from the shared preferences.
final SharedPreferences prefs = getSharedPreferences(VpnClient.Prefs.NAME, MODE_PRIVATE);
final String server = prefs.getString(VpnClient.Prefs.SERVER_ADDRESS, "");
final byte[] secret = prefs.getString(VpnClient.Prefs.SHARED_SECRET, "").getBytes();
final int port;
try {
port = Integer.parseInt(prefs.getString(VpnClient.Prefs.SERVER_PORT, ""));
} catch (NumberFormatException e) {
Log.e(TAG, "Bad port: " + prefs.getString(VpnClient.Prefs.SERVER_PORT, null), e);
return;
}
// Kick off a connection.
startConnection(new VpnConnection(
this, mNextConnectionId.getAndIncrement(), server, port, secret));
}
private void startConnection(final VpnConnection connection) {
// Replace any existing connecting thread with the new one.
final Thread thread = new Thread(connection, "ToyVpnThread");
setConnectingThread(thread);
// Handler to mark as connected once onEstablish is called.
connection.setConfigureIntent(mConfigureIntent);
connection.setOnEstablishListener(new VpnConnection.OnEstablishListener() {
public void onEstablish(ParcelFileDescriptor tunInterface) {
mHandler.sendEmptyMessage(R.string.connected);
mConnectingThread.compareAndSet(thread, null);
setConnection(new Connection(thread, tunInterface));
}
});
thread.start();
}
private void setConnectingThread(final Thread thread) {
final Thread oldThread = mConnectingThread.getAndSet(thread);
if (oldThread != null) {
oldThread.interrupt();
}
}
private void setConnection(final Connection connection) {
final Connection oldConnection = mConnection.getAndSet(connection);
if (oldConnection != null) {
try {
oldConnection.first.interrupt();
oldConnection.second.close();
} catch (IOException e) {
Log.e(TAG, "Closing VPN interface", e);
}
}
}
private void disconnect() {
mHandler.sendEmptyMessage(R.string.disconnected);
setConnectingThread(null);
setConnection(null);
stopForeground(true);
}
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
private void updateForegroundNotification(final int message) {
startForeground(1, new Notification.Builder(this)
.setSmallIcon(R.drawable.ic_vpn)
.setContentText(getString(message))
.setContentIntent(mConfigureIntent)
.build());
}
}
VpnConnection.java
import android.app.PendingIntent;
import android.os.Build;
import android.os.ParcelFileDescriptor;
import android.support.annotation.RequiresApi;
import android.util.Log;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.util.concurrent.TimeUnit;
/**
* Created by Yaksh on 11/3/2017.
*/
public class VpnConnection implements Runnable{
/**
* Callback interface to let the {#link MyVpnService} know about new connections
* and update the foreground notification with connection status.
*/
public interface OnEstablishListener {
void onEstablish(ParcelFileDescriptor tunInterface);
}
/** Maximum packet size is constrained by the MTU, which is given as a signed short. */
private static final int MAX_PACKET_SIZE = Short.MAX_VALUE;
/** Time to wait in between losing the connection and retrying. */
private static final long RECONNECT_WAIT_MS = TimeUnit.SECONDS.toMillis(3);
/** Time between keepalives if there is no traffic at the moment.
*
* TODO: don't do this; it's much better to let the connection die and then reconnect when
* necessary instead of keeping the network hardware up for hours on end in between.
**/
private static final long KEEPALIVE_INTERVAL_MS = TimeUnit.SECONDS.toMillis(15);
/** Time to wait without receiving any response before assuming the server is gone. */
private static final long RECEIVE_TIMEOUT_MS = TimeUnit.SECONDS.toMillis(20);
/**
* Time between polling the VPN interface for new traffic, since it's non-blocking.
*
* TODO: really don't do this; a blocking read on another thread is much cleaner.
*/
private static final long IDLE_INTERVAL_MS = TimeUnit.MILLISECONDS.toMillis(100);
/**
* Number of periods of length {#IDLE_INTERVAL_MS} to wait before declaring the handshake a
* complete and abject failure.
*
* TODO: use a higher-level protocol; hand-rolling is a fun but pointless exercise.
*/
private static final int MAX_HANDSHAKE_ATTEMPTS = 50;
private final MyVpnService mService;
private final int mConnectionId;
private final String mServerName;
private final int mServerPort;
private final byte[] mSharedSecret;
private PendingIntent mConfigureIntent;
private OnEstablishListener mOnEstablishListener;
public VpnConnection(final MyVpnService service, final int connectionId,
final String serverName, final int serverPort, final byte[] sharedSecret) {
mService = service;
mConnectionId = connectionId;
mServerName = serverName;
mServerPort= serverPort;
mSharedSecret = sharedSecret;
}
/**
* Optionally, set an intent to configure the VPN. This is {#code null} by default.
*/
public void setConfigureIntent(PendingIntent intent) {
mConfigureIntent = intent;
}
public void setOnEstablishListener(OnEstablishListener listener) {
mOnEstablishListener = listener;
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void run() {
try {
Log.i(getTag(), "Starting");
// If anything needs to be obtained using the network, get it now.
// This greatly reduces the complexity of seamless handover, which
// tries to recreate the tunnel without shutting down everything.
// In this demo, all we need to know is the server address.
final SocketAddress serverAddress = new InetSocketAddress(mServerName, mServerPort);
// We try to create the tunnel several times.
// network is available.
// Here we just use a counter to keep things simple.
for (int attempt = 0; attempt < 10; ++attempt) {
// Reset the counter if we were connected.
if (run(serverAddress)) {
attempt = 0;
}
// Sleep for a while. This also checks if we got interrupted.
Thread.sleep(3000);
}
Log.i(getTag(), "Giving up");
} catch (IOException | InterruptedException | IllegalArgumentException e) {
Log.e(getTag(), "Connection failed, exiting", e);
}
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
private boolean run(SocketAddress server)
throws IOException, InterruptedException, IllegalArgumentException {
ParcelFileDescriptor iface = null;
boolean connected = false;
// Create a DatagramChannel as the VPN tunnel.
try (DatagramChannel tunnel = DatagramChannel.open()) {
// Protect the tunnel before connecting to avoid loopback.
if (!mService.protect(tunnel.socket())) {
throw new IllegalStateException("Cannot protect the tunnel");
}
// Connect to the server.
tunnel.connect(server);
// For simplicity, we use the same thread for both reading and
// writing. Here we put the tunnel into non-blocking mode.
tunnel.configureBlocking(false);
// Authenticate and configure the virtual network interface.
iface = handshake(tunnel);
// Now we are connected. Set the flag.
connected = true;
// Packets to be sent are queued in this input stream.
FileInputStream in = new FileInputStream(iface.getFileDescriptor());
// Packets received need to be written to this output stream.
FileOutputStream out = new FileOutputStream(iface.getFileDescriptor());
// Allocate the buffer for a single packet.
ByteBuffer packet = ByteBuffer.allocate(MAX_PACKET_SIZE);
// Timeouts:
// - when data has not been sent in a while, send empty keepalive messages.
// - when data has not been received in a while, assume the connection is broken.
long lastSendTime = System.currentTimeMillis();
long lastReceiveTime = System.currentTimeMillis();
// We keep forwarding packets till something goes wrong.
while (true) {
// Assume that we did not make any progress in this iteration.
boolean idle = true;
// Read the outgoing packet from the input stream.
int length = in.read(packet.array());
if (length > 0) {
// Write the outgoing packet to the tunnel.
packet.limit(length);
tunnel.write(packet);
packet.clear();
// There might be more outgoing packets.
idle = false;
lastReceiveTime = System.currentTimeMillis();
}
// Read the incoming packet from the tunnel.
length = tunnel.read(packet);
if (length > 0) {
// Ignore control messages, which start with zero.
if (packet.get(0) != 0) {
// Write the incoming packet to the output stream.
out.write(packet.array(), 0, length);
}
packet.clear();
// There might be more incoming packets.
idle = false;
lastSendTime = System.currentTimeMillis();
}
// If we are idle or waiting for the network, sleep for a
// fraction of time to avoid busy looping.
if (idle) {
Thread.sleep(IDLE_INTERVAL_MS);
final long timeNow = System.currentTimeMillis();
if (lastSendTime + KEEPALIVE_INTERVAL_MS <= timeNow) {
// We are receiving for a long time but not sending.
// Send empty control messages.
packet.put((byte) 0).limit(1);
for (int i = 0; i < 3; ++i) {
packet.position(0);
tunnel.write(packet);
}
packet.clear();
lastSendTime = timeNow;
} else if (lastReceiveTime + RECEIVE_TIMEOUT_MS <= timeNow) {
// We are sending for a long time but not receiving.
throw new IllegalStateException("Timed out");
}
}
}
} catch (SocketException e) {
Log.e(getTag(), "Cannot use socket", e);
} finally {
if (iface != null) {
try {
iface.close();
} catch (IOException e) {
Log.e(getTag(), "Unable to close interface", e);
}
}
}
return connected;
}
private ParcelFileDescriptor handshake(DatagramChannel tunnel)
throws IOException, InterruptedException {
// To build a secured tunnel, we should perform mutual authentication
// and exchange session keys for encryption. To keep things simple in
// this demo, we just send the shared secret in plaintext and wait
// for the server to send the parameters.
// Allocate the buffer for handshaking. We have a hardcoded maximum
// handshake size of 1024 bytes, which should be enough for demo
// purposes.
ByteBuffer packet = ByteBuffer.allocate(1024);
// Control messages always start with zero.
packet.put((byte) 0).put(mSharedSecret).flip();
// Send the secret several times in case of packet loss.
for (int i = 0; i < 3; ++i) {
packet.position(0);
tunnel.write(packet);
}
packet.clear();
// Wait for the parameters within a limited time.
for (int i = 0; i < MAX_HANDSHAKE_ATTEMPTS; ++i) {
Thread.sleep(IDLE_INTERVAL_MS);
// Normally we should not receive random packets. Check that the first
// byte is 0 as expected.
int length = tunnel.read(packet);
if (length > 0 && packet.get(0) == 0) {
return configure(new String(packet.array(), 1, length - 1).trim());
}
}
throw new IOException("Timed out");
}
private ParcelFileDescriptor configure(String parameters) throws IllegalArgumentException {
// Configure a builder while parsing the parameters.
MyVpnService.Builder builder = mService.new Builder();
for (String parameter : parameters.split(" ")) {
String[] fields = parameter.split(",");
try {
switch (fields[0].charAt(0)) {
case 'm':
builder.setMtu(Short.parseShort(fields[1]));
break;
case 'a':
builder.addAddress(fields[1], Integer.parseInt(fields[2]));
break;
case 'r':
builder.addRoute(fields[1], Integer.parseInt(fields[2]));
break;
case 'd':
builder.addDnsServer(fields[1]);
break;
case 's':
builder.addSearchDomain(fields[1]);
break;
}
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Bad parameter: " + parameter);
}
}
// Create a new interface using the builder and save the parameters.
final ParcelFileDescriptor vpnInterface;
synchronized (mService) {
vpnInterface = builder
.setSession(mServerName)
.setConfigureIntent(mConfigureIntent)
.establish();
if (mOnEstablishListener != null) {
mOnEstablishListener.onEstablish(vpnInterface);
}
}
Log.i(getTag(), "New interface: " + vpnInterface + " (" + parameters + ")");
return vpnInterface;
}
private final String getTag() {
return VpnConnection.class.getSimpleName() + "[" + mConnectionId + "]";
}
}

Download database File For Google Drive API Android

I am using the drive api to create a database file in the hidden app folder on google drive. The database file is called notes.db I have been able to successfully upload the database file to google drive but I have no idea how to download it back to the user's device. This is what i'm trying to do. My app makes a folder on the user's device called School Binder. in that folder is another folder called Note backups. Here is where I backup the database. The directory is
Environment.getExternalStorageDirectory() + "/School Binder/Note Backups/Notes.db"
Google drive takes this file and uploads it to the hidden app folder. Now I want to get this notes.db file stored in that app folder on google drive and download it back to this directory on the phone.
Environment.getExternalStorageDirectory() + "/School Binder/Note Backups/Notes.db"
How do I do this. Thanks. Here is my code for uploading the database to drive this works correctly
// Define And Instantiate Variable DriveContents driveContents//
DriveContents driveContents = result.getStatus().isSuccess() ? result.getDriveContents() : null;
// Gets The Data for The File//
if (driveContents != null) try {
// Define And Instantiate Variable OutputStream outputStream//
OutputStream outputStream = driveContents.getOutputStream();
// Start Writing Data To File//
if (outputStream != null) try {
// Define And Instantiate Variable InputStream inputStream//
InputStream inputStream = new FileInputStream(dbFile);
// Define And Instantiate Variable Byte buffer//
byte[] buffer = new byte[5000];
// Define Variable Int data//
int data;
// Run Code While data Is Bigger Then Zero//
while ((data = inputStream.read(buffer, 0, buffer.length)) > 0) {
// Write To outputStream//
outputStream.write(buffer, 0, data);
// Flush outputStream//
outputStream.flush();
}
} finally {
// Close outputStream//
outputStream.close();
}
} catch (Exception e) {e.printStackTrace(); Toast.makeText(getApplicationContext(), "Failed To Upload: No Backup File Found", Toast.LENGTH_LONG).show(); return;}
How do I change this to make it work for downloading data to a file from google drive
In Lifecycle of a Drive file, Drive Android API lets your app access files even if the device is offline. To support offline cases, the API implements a sync engine, which runs in the background to upstream and downstream changes as network access is available and to resolve conflicts. Perform an initial download request if the file is not yet synced to the local context but the user wants to open the file. The API handles this automatically when a file is requested.
In downloading a file, you make an authorized HTTP GET request to the file's resource URL and include the query parameter alt=media. However, please note that downloading the file requests the user to have at least read access.
Sample HTTP Request:
GET https://www.googleapis.com/drive/v3/files/0B9jNhSvVjoIVM3dKcGRKRmVIOVU?alt=media
Authorization: Bearer ya29.AHESVbXTUv5mHMo3RYfmS1YJonjzzdTOFZwvyOAUVhrs
For the coding part, this SO post might be of help too.
I figured it out this is my code to redownload a database back to the phone
//<editor-fold desc="Create Drive Db File On Device">
// Log That The File Was Opened//
Log.d("TAG", "File contents opened");
// Define And Instantiate Variable DriveContents driveContents//
DriveContents driveContents = result.getStatus().isSuccess() ? result.getDriveContents() : null;
// Gets The Data for The File//
if (driveContents != null) try {
// Define And Instantiate Variable OutputStream outputStream//
OutputStream outputStream = new FileOutputStream(dbFile);
// Define And Instantiate Variable InputStream inputStream//
InputStream inputStream = driveContents.getInputStream();
// Define And Instantiate Variable Byte buffer//
byte[] buffer = new byte[5000];
// Define Variable Int data//
int data;
// Run Code While data Is Bigger Then Zero//
while ((data = inputStream.read(buffer, 0, buffer.length)) > 0) {
// Write To outputStream//
outputStream.write(buffer, 0, data);
// Flush outputStream//
outputStream.flush();
}
// Close outputStream//
outputStream.close();
// Discard Drive Contents//
driveContents.discard(googleApiClient);
} catch (Exception e) {e.printStackTrace(); Toast.makeText(getApplicationContext(), "File Failed To Download", Toast.LENGTH_LONG).show(); }
//</editor-fold>
here is a complete class to upload an internal database, download it and delete it from Google Drive.
Only need to call functions asynchronously and show user a progressbar.
DownloadFromGoogleDrive function saves the database in the internal database folder to the app with the name "database2"
Hope it's helpful.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
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.OutputStream;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.drive.Drive;
import com.google.android.gms.drive.DriveApi;
import com.google.android.gms.drive.DriveApi.MetadataBufferResult;
import com.google.android.gms.drive.DriveFile.DownloadProgressListener;
import com.google.android.gms.drive.DriveId;
import com.google.android.gms.drive.DriveResource;
import com.google.android.gms.drive.Metadata;
import com.google.android.gms.drive.DriveApi.DriveContentsResult;
import com.google.android.gms.drive.DriveContents;
import com.google.android.gms.drive.DriveFile;
import com.google.android.gms.drive.DriveFolder.DriveFileResult;
import com.google.android.gms.drive.MetadataChangeSet;
import com.google.android.gms.drive.query.Filters;
import com.google.android.gms.drive.query.Query;
import com.google.android.gms.drive.query.SearchableField;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.os.Bundle;
import android.util.Log;
import android.webkit.MimeTypeMap;
import android.widget.Toast;
public class BackupDatabaseActivity extends Activity implements ConnectionCallbacks, OnConnectionFailedListener {
private static final String TAG = "BackupDatabaseActivity";
private GoogleApiClient api;
private boolean mResolvingError = false;
private static final int DIALOG_ERROR_CODE =100;
private static final String DATABASE_NAME = "database";
private static final String GOOGLE_DRIVE_FILE_NAME = "database_backup";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create the Drive API instance
api = new GoogleApiClient.Builder(this).addApi(Drive.API).addScope(Drive.SCOPE_FILE).
addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();
}
final private ResultCallback<DriveApi.DriveContentsResult> contentsCallback = new ResultCallback<DriveApi.DriveContentsResult>() {
#Override
public void onResult(DriveApi.DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.v(TAG, "Error while trying to create new file contents");
return;
}
CreateFileOnGoogleDrive(result);
//OR DownloadFromGoogleDrive(result);
//OR DeleteFromGoogleDrive(result);
}
};
final private ResultCallback<DriveFileResult> fileCallback = new ResultCallback<DriveFileResult>() {
#Override
public void onResult(DriveFileResult result) {
if (!result.getStatus().isSuccess()) {
Log.v(TAG, "Error while trying to create the file");
return;
}
Log.v(TAG, "File created: "+result.getDriveFile().getDriveId());
}
};
/**
* Create a file in root folder using MetadataChangeSet object.
* #param result
*/
public void CreateFileOnGoogleDrive(DriveContentsResult result){
final DriveContents driveContents = result.getDriveContents();
// Perform I/O off the UI thread.
new Thread() {
#Override
public void run() {
try {
FileInputStream is = new FileInputStream(getDbPath());
BufferedInputStream in = new BufferedInputStream(is);
byte[] buffer = new byte[8 * 1024];
BufferedOutputStream out = new BufferedOutputStream(driveContents.getOutputStream());
int n = 0;
while( ( n = in.read(buffer) ) > 0 ) {
out.write(buffer, 0, n);
}
out.flush();
out.close();
in.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String mimeType = MimeTypeMap.getSingleton().getExtensionFromMimeType("db");
MetadataChangeSet changeSet = new MetadataChangeSet.Builder()
.setTitle(GOOGLE_DRIVE_FILE_NAME) // Google Drive File name
.setMimeType(mimeType)
.setStarred(true).build();
// create a file in root folder
Drive.DriveApi.getRootFolder(api)
.createFile(api, changeSet, driveContents)
.setResultCallback(fileCallback);
}
}.start();
}
/**
* Download File from Google Drive
* #param result
*/
public void DownloadFromGoogleDrive(DriveContentsResult result){
final DriveContents driveContents = result.getStatus().isSuccess() ? result.getDriveContents() : null;
if(driveContents!=null){
Query query = new Query.Builder().addFilter(Filters.eq(SearchableField.TITLE, GOOGLE_DRIVE_FILE_NAME)).build();
Drive.DriveApi.query(api, query).setResultCallback(new ResultCallback<MetadataBufferResult>() {
#Override
public void onResult(MetadataBufferResult result) {
try{
DriveId driveId = result.getMetadataBuffer().get(0).getDriveId();
DriveFile driveFile = driveId.asDriveFile();
//mProgressBar.setProgress(0);
DownloadProgressListener listener = new DownloadProgressListener() {
#Override
public void onProgress(long bytesDownloaded, long bytesExpected) {
// Update progress dialog with the latest progress.
int progress = (int)(bytesDownloaded*100/bytesExpected);
Log.d(TAG, String.format("Loading progress: %d percent", progress));
// mProgressBar.setProgress(progress);
}
};
driveFile.open(api, DriveFile.MODE_READ_ONLY, listener).setResultCallback(driveContentsCallback);
}catch(Exception e){
Toast.makeText(getApplicationContext(), "File Failed To Download", Toast.LENGTH_LONG).show();
}
}
});
}else{
Toast.makeText(getApplicationContext(), "File Failed To Download", Toast.LENGTH_LONG).show();
}
}
private ResultCallback<DriveContentsResult> driveContentsCallback =
new ResultCallback<DriveContentsResult>() {
#Override
public void onResult(DriveContentsResult result) {
if (!result.getStatus().isSuccess()) {
Log.d(TAG, "Error while opening the file contents");
return;
}
Log.d(TAG, "Downloaded");
DriveContents dc = result.getDriveContents();
try {
InputStream inputStream = dc.getInputStream();
OutputStream outputStream = new FileOutputStream(getDbPath()+"2");
byte[] buffer = new byte[8 * 1024];
//BufferedOutputStream out = new BufferedOutputStream(dc.getOutputStream());
int n = 0;
while( ( n = inputStream.read(buffer) ) > 0 ) {
outputStream.write(buffer, 0, n);
}
outputStream.flush();
outputStream .close();
//inputStream.close();
dc.discard(api);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
/**
* Delete File from Google Drive
* #param result
*/
public void DeleteFromGoogleDrive(DriveContentsResult result){
Query query = new Query.Builder()
.addFilter(Filters.eq(SearchableField.TITLE, GOOGLE_DRIVE_FILE_NAME))
.build();
Drive.DriveApi.query(api, query)
.setResultCallback(new ResultCallback<MetadataBufferResult>() {
#Override
public void onResult(MetadataBufferResult result) {
try{
Metadata metadata = result.getMetadataBuffer().get(0);
/*String a = metadata.getTitle();
String b = metadata.getDescription();
long c = metadata.getFileSize();*/
DriveResource driveResource = metadata.getDriveId().asDriveResource();
if (metadata.isTrashable()) {
if (metadata.isTrashed()) {
driveResource.untrash(api).setResultCallback(trashStatusCallback);
} else {
driveResource.trash(api).setResultCallback(trashStatusCallback);
}
} else {
Log.d(TAG, "Error trying delete");
}
}catch(Exception e){
Log.d(TAG, "Error: metadata doesn't exist");
}
}
});
}
/**
* Callback when call to trash or untrash is complete.
*/
private final ResultCallback<Status> trashStatusCallback =
new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
if (!status.isSuccess()) {
Log.e(TAG, "Error trying delete: " + status.getStatusMessage());
return;
}else{
Log.e(TAG, "Deleted: " + status.getStatusMessage());
}
}
};
private File getDbPath() {
return this.getDatabasePath(DATABASE_NAME);
}
#Override
public void onConnectionSuspended(int cause) {
// TODO Auto-generated method stub
Log.v(TAG, "Connection suspended");
}
#Override
public void onStart() {
super.onStart();
if(!mResolvingError) {
api.connect(); // Connect the client to Google Drive
}
}
#Override
public void onStop() {
super.onStop();
api.disconnect(); // Disconnect the client from Google Drive
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.v(TAG, "Connection failed");
if(mResolvingError) { // If already in resolution state, just return.
return;
} else if(result.hasResolution()) { // Error can be resolved by starting an intent with user interaction
mResolvingError = true;
try {
result.startResolutionForResult(this, DIALOG_ERROR_CODE);
} catch (SendIntentException e) {
e.printStackTrace();
}
} else { // Error cannot be resolved. Display Error Dialog stating the reason if possible.
Toast.makeText(this, "Error: Connection failed", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onConnected(Bundle connectionHint) {
Log.v(TAG, "Connected successfully");
/* Connection to Google Drive established. Now request for Contents instance, which can be used to provide file contents.
The callback is registered for the same. */
Drive.DriveApi.newDriveContents(api).setResultCallback(contentsCallback);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == DIALOG_ERROR_CODE) {
mResolvingError = false;
if(resultCode == RESULT_OK) { // Error was resolved, now connect to the client if not done so.
if(!api.isConnecting() && !api.isConnected()) {
api.connect();
}
}
}
}
}

send udp message from PC(windows)(client) to android phone(server) not working

I want to send a UDP message from PC(server) to my android phone 4.2(client) using WIFI connection. My phone and PC are connected via wireless router. But no message is received from phone to mobile.
I have understood from debugging that the program is waiting at socket.receive(packet);. So, there is no update on the UI.
I want to show message to the UI when server received a message from client and this process will be continue.
I would be grateful, if you could help me. Thank you. I have added necessary permission.
server:
package com.example.abuttontest;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.app.Activity;
import android.os.Bundle;
import android.provider.Settings.System;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity
{
private TextView tv;
int i =0;
// String s;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button) findViewById(R.id.button1);
tv = (TextView) findViewById(R.id.textView1);
//TextView textMessage = (TextView) findViewById(R.id.textView2);
button1.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
/*cheack ping message*/
//boolean morgan= isOnline();
//String s = String.valueOf(morgan);
tv.setText("kkkkkkkkkk"); // print ping message
Log.d("MyTag#","This is sample log message");
}
});
/* Thread for receiving Data from CLient */
runThread();
}
private void runThread()
{
new Thread()
{
public void run()
{
Log.d("p2p", "1");
while (i++ < 1000)
{
Log.d("p2p", "2");
try {
/////////////////////
//System.out.println("aaa");
byte[] inbuf = new byte[1000]; // default size
DatagramPacket packet = new DatagramPacket(inbuf, inbuf.length);
Log.d("p2p", "3");
DatagramSocket socket = new DatagramSocket(6000);
socket.receive(packet);
Log.d("p2p", "4");
int numBytesReceived = packet.getLength();
//System.out.println(numBytesReceived);
String s = new String(inbuf);
//System.out.println(s);
//System.out.println(inbuf[2]);
socket.close();
Log.d("p2p", "5");
runOnUiThread(new Runnable()
{
#Override
public void run()
{
tv.setText("#" + i);
}
});
Thread.sleep(300);
}
catch (InterruptedException e)
{
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.one)
{
Toast.makeText(getApplicationContext(), "Toast Message ONE", Toast.LENGTH_LONG).show();
}
if (id == R.id.two)
{
Toast.makeText(getApplicationContext(), "Toast Message TWO", Toast.LENGTH_LONG).show();
}
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
}
client:
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/*packets in the IP layer are called the datagrams */
/*After creating a packet, the process of sending or receiving it involves calling the send or receive method of DatagramSocket. More specifically, you create a packet, then you create a socket. After you create the socket, you call the send method of DatagramSocket to send the datagram packet or use the receive method of DatagramSocket to receive a packet. You can also use the same DatagramSocket to send and receive multiple packets, each going to different destinations and coming from different sources.*/
public class client
{
public static void main(String args[])
{
System.out.println("from client");
try{
//InetAddress ipaddress = InetAddress.getByName("localhost");
// InetAddress ipaddress = InetAddress.getByName("192.168.0.103");
// while(true)
// {
InetAddress ipaddress = InetAddress.getByName("192.168.0.102");
int port = 6000;
//byte[] buffer = new byte[1024]; // empty byte array
String msg ="hello goooooooogle"; // send this message to the server
byte [] b_array = msg.getBytes();
//on SERVER side DatagramSocket able to receive packets on 8080 port
DatagramPacket packet = new DatagramPacket(b_array, b_array.length, ipaddress, port);// DatagramPacket(byte[], byte_length, InetAddress, port_number)
DatagramSocket socket = new DatagramSocket();
socket.send(packet);
socket.close();
// }
}
catch(Exception e)
{
System.out.println(e);
}
}
}
In your MainActivity you have not mentioned the port number which your server has to listen on.

Android FTP Server

I am using the following code to make the android device a ftp server (Android Internal storage). I am getting the exception of os.android.NetworkOnMainThread. I have tried to put the onStart code in the AsyncTask but app never executes and crashes on launch. Any help regarding the ftp server on Android will be great as i have no idea how to get it working.
Here is the MainActivity Code
package com.googlecode.simpleftp;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class FTPServer extends Activity {
private static int COMMAND_PORT = 2121;
static final int DIALOG_ALERT_ID = 0;
private static ExecutorService executor = Executors.newCachedThreadPool();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.new_game:
System.out.println("New game button is pressed!");
//newGame();
return true;
case R.id.quit:
System.out.println("Quit button is pressed!");
showDialog(DIALOG_ALERT_ID);
return true;
default:
return super.onOptionsItemSelected(item); }
}
#Override
protected Dialog onCreateDialog(int id){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false).setPositiveButton("yes", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int id){
FTPServer.this.finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
return alert;
}
HEre is the ServerPI Code
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class ServerPI implements Runnable{
private Socket clientSocket;
private BufferedReader in;
private PrintWriter out;
private String baseDir;
private String relativeDir;
private String absoluteDir;
private String fileName;
private String filePath;
public ServerPI(Socket incoming) throws IOException{
this.clientSocket = incoming;
in = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
out = new PrintWriter(this.clientSocket.getOutputStream(), true);
baseDir = new File("").getAbsolutePath();
relativeDir = "/";
absoluteDir = baseDir + relativeDir;
fileName = "";
filePath = absoluteDir + "/" + fileName;
}
private void readCommandLoop() throws IOException {
String line = null;
reply(220, "Welcome to the SimpleFTP server!");
while((line = in.readLine()) != null){
int replyCode = executeCommand(line.trim());
if(replyCode == 221){
return;
}
}
}
private int executeCommand(String trim) {
// TODO Auto-generated method stub
return 0;
}
public int reply(int statusCode, String statusMessage){
out.println(statusCode + " " + statusMessage);
return statusCode;
}
#Override
public void run(){
try{
this.readCommandLoop();
} catch (IOException e){
e.printStackTrace();
}
finally {
try {
if(in != null){
in.close();
in = null;
}
if(out != null){
out.close();
out = null;
}
if (clientSocket != null){
clientSocket.close();
clientSocket = null;
}
}
catch (IOException e){
e.printStackTrace();
}
}
}
}
I have put the code in the AsyncTask, here it is
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
ServerSocket s = null;
Socket incoming = null;
try{
s = new ServerSocket(COMMAND_PORT);
String ip = (s.getInetAddress()).getHostAddress();
Context context = this.getApplicationContext();
CharSequence text = ip;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
Thread.sleep(1000);
toast.show();
while(true){
incoming = s.accept();
executor.execute(new ServerPI(incoming));
}
}
catch(Exception e){
System.out.println(e.toString());
e.printStackTrace();
}
finally{
try
{
if(incoming != null)incoming.close();
}
catch(IOException ignore)
{
//ignore
}
try
{
if (s!= null)
{
s.close();
}
}
catch(IOException ignore)
{
//ignore
}
}
return "Executed";
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
Iam calling the longOpertation in onCreate method. What is the problem that the app crashes on launch.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen);
new LongOperation().execute();
}
Maybe because you didn't set up the permissions in the manifest? You've to set permission for internet usage.
If this doesn't work, please tell us which line is it throwing the exception.
while(true){ incoming = s.accept(); ...} You cannot put that in OnStart(). That should be done in a thread. So ServerSocket s = null; should be a variable of you activity.
So I went with Swiftp application (open source) as a service in my application which helped me to achieve my task. Thanks everyone who stepped forward to help. Here is the link if someone wants to follow
Please post your code here.
NetworkOnMainthreadException occurs because you maybe running Network related operation on the Main UI Thread. You should use asynctask for this purpose
This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged.
http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html
class TheTask extends AsyncTask<Void,Void,Void>
{
protected void onPreExecute()
{ super.onPreExecute();
//display progressdialog.
}
protected void doInBackground(Void ...params)//return result here
{
//http request. do not update ui here
//call webservice
//return result here
return null;
}
protected void onPostExecute(Void result)//result of doInBackground is passed a parameter
{
super.onPostExecute(result);
//dismiss progressdialog.
//update ui using the result returned form doInbackground()
}
}
http://developer.android.com/reference/android/os/AsyncTask.html. Check the topic under the heading The 4 Steps.
A working example of asynctask # To use the tutorial in android 4.0.3 if had to work with AsynxTasc but i still dont work?.
The above makes a webserive call in doInBakckground(). Returns result and updates the ui by setting the result in textview in onPostExecute().
You can not do network operation in main thread in android 3.0 higher. Use AsyncTask for this network operation. See this for further explanation

How to store Logs in a txt file using the android.util.log

I know this topic has been talked a lot but not in this meanings.
I need to store the logs in a .txt file but I cannot use the log4j or any other class but android.util.log
I have this solution but it is not the best.
For have the same information than in: Log.i(TAG, "An INFO Message");
I have to write...
ERROR = logLevel < 3;
WARNING = logLevel < 2;
INFO = logLevel < 1;
if (INFO){
appendLog("LEVEL: I TIME: "+java.util.GregorianCalendar.DAY_OF_MONTH +
"-"+ java.util.GregorianCalendar.MONTH +" "+GregorianCalendar.HOUR_OF_DAY +":"+GregorianCalendar.MINUTE +
":"+GregorianCalendar.SECOND +"."+GregorianCalendar.MILLISECOND + " PID: "+
android.os.Process.myPid()+ " TID: "+android.os.Process.myTid()+ " Application: com.example.myapplication"+
" TAG:" +TAG+ " TEXT: An INFO Message");
}
and then...
public void appendLog(String text) {
File logFile = new File("sdcard/log.txt");
if (!logFile.exists()) {
try {
logFile.createNewFile();
}catch (IOException e){
e.printStackTrace();
}
}
try {
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Does anyone has a more elegant solution than this? Thank you for helping me.
Here with I attached simple Logger class definition, you can use at it is.
To store the log information in to Log.txt file in SDCARD, use at it is.
package com.clientname.projectname;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.FileHandler;
import android.os.Environment;
import android.util.Log;
/**
* #author Rakesh.Jha
* Date - 07/10/2013
* Definition - Logger file use to keep Log info to external SD with the simple method
*/
public class Logger {
public static FileHandler logger = null;
private static String filename = "ProjectName_Log";
static boolean isExternalStorageAvailable = false;
static boolean isExternalStorageWriteable = false;
static String state = Environment.getExternalStorageState();
public static void addRecordToLog(String message) {
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
isExternalStorageAvailable = isExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
isExternalStorageAvailable = true;
isExternalStorageWriteable = false;
} else {
// Something else is wrong. It may be one of many other states, but all we need
// to know is we can neither read nor write
isExternalStorageAvailable = isExternalStorageWriteable = false;
}
File dir = new File("/sdcard/Files/Project_Name");
if (Environment.MEDIA_MOUNTED.equals(state)) {
if(!dir.exists()) {
Log.d("Dir created ", "Dir created ");
dir.mkdirs();
}
File logFile = new File("/sdcard/Files/Project_Name/"+filename+".txt");
if (!logFile.exists()) {
try {
Log.d("File created ", "File created ");
logFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.write(message + "\r\n");
//buf.append(message);
buf.newLine();
buf.flush();
buf.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Now once you created this file, where ever you want to store a log info into log.txt file use below code. -
package com.clientname.projectname;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
/**
* #author Rakesh.Jha
* Date - 03/10/2013
* Definition - //ToDO
*/
public class MainActivity extends Activity {
private static final String TAG = null;
Logger logger;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("Testing :","log"); // no need to do this line, use below line
logger.addRecordToLog("Testing : log " );
logger.addRecordToLog("TAG MediaPlayer audio session ID: " );
MediaPlayer mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.test);//test is audio file, u have to keep in raw folder
logger.addRecordToLog( "MediaPlayer audio session ID: " + mediaPlayer.getAudioSessionId());
logger.addRecordToLog( "Media Player started " + "Started !");
mediaPlayer.start(); // no need to call prepare(); create() does that for you
}
private void prepareMediaServer() { }
}
Create a wrapper class that will wrap the Android's Log class. This wrapper class will extend the functionality of Log class by additionally logging the text into a file.
Example:
public class MyLog{
public static void i(String TAG, String message){
// Printing the message to LogCat console
Log.i(TAG, message);
// Write the log message to the file
appendLog(message);
}
public static void d(String TAG, String message){
Log.d(TAG, message);
appendLog(message);
}
// rest of log methods...
}
Then you whould use it like this:
MyLog.i("LEVEL 1", "Your log message here...");

Categories

Resources