Accessing Text File from FTP Server, Android Development - android

I am trying to access files on an FTP server in Android.
For some reason whenever I import any external jar such as commons-net or ftp4j my app crashes on run. I have verified this by commenting out all lines that refer to the jars and the app runs properly.
I want to access data in a text file on an FTP server and print it out to a TextView. I have been stuck on this all day. How do I fix this? Permissions including in manifest are internet and external storage.
package com.testing.pack;
import java.io.BufferedInputStream;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.http.client.HttpClient;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
public class TestingActivity extends Activity implements OnClickListener {
/** Called when the activity is first created. */
TextView tv;
Button go;
HttpClient client;
FTPClient ftp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.tvTry);
Typeface face = Typeface.createFromAsset(getAssets(),
"Roboto-LightItalic.ttf");
tv.setTypeface(face);
go = (Button) findViewById(R.id.bGO);
go.setOnClickListener(this);
try {
//Attempt using commons-net
FTPClient ftpClient = new FTPClient();
ftpClient.connect("ftp://........./");
ftpClient.login(".......", ".....");
ftpClient.changeWorkingDirectory("......");
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
BufferedInputStream buffIn=null;
buffIn=new BufferedInputStream(new FileInputStream(file));
ftpClient.enterLocalPassiveMode();
ftpClient.storeFile("test.txt", buffIn);
buffIn.close();
ftpClient.logout();
ftpClient.disconnect();
//Attempt using ftp4j
//FTPClient ftp = new FTPClient();
//ftp.connect("........");
//ftp.login(".......", ".....");
//ftp.changeDirectoryUp();
//ftp.changeDirectory(".....");
//ftp.changeDirectory("public_ftp");
//ftp.download("test.txt", new java.io.File("....."));
} catch (Exception e) {
}
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
getData ex = new getData();
try {
tv.setText(ex.getInternetData());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Are you using Eclipse to add the jars? Instead create a libs folder and copy the jars into it.
Here is a similar question: How can I use external JARs in an Android project?

Related

my app could not send a message from my real device to emulator! What is goes wrong? is needed to more settings?

i am new by android.I have started work with a simple chat app. I wrote a short code by UDP socket one for client and one for server.Now i have some issues at connectivity android real device which client app installed on it , and emulator device which server app run on it.
Client app is a simple code which must set IP for connection to emulator and also has a EditText for sending a message.(I at this point set 10.0.2.2 or 10.0.2.15. But my app could not send a message from my real device to emulator! What is goes wrong? is needed to more settings?)
Server app has only a textView for getting and showing recived message.
here is Client code:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class ClienttextchatActivity extends Activity
{
private String udpMsg=null;
Handler hand=new Handler();
EditText edtSetIp=null , edtText=null;
Button btnSetIp=null , btnSend=null;
static String ip=null;
static final String LOG_TAG = "UdpStream";
static final int PORT = 8888;
static final int BUF_SIZE=4096;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edtText=(EditText)findViewById(R.id.edtText);
edtSetIp=(EditText)findViewById(R.id.edtSetIp);
btnSetIp=(Button)findViewById(R.id.btnSetIp);
btnSend=(Button)findViewById(R.id.btnSend);
btnSetIp.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
ip=edtSetIp.getText().toString();
}
});
btnSend.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Thread mythread=new Thread(new th1() );
mythread.start();
}
});
}
//#############################################
public class th1 implements Runnable
{
public void run()
{
udpMsg =edtText.getText().toString();
Log.d(LOG_TAG,udpMsg);
DatagramSocket ds = null;
try
{
ds = new DatagramSocket();
InetAddress serverAddr = InetAddress.getByName(ip);
Log.d(LOG_TAG,"address server address created.");
DatagramPacket dp;
dp = new DatagramPacket(udpMsg.getBytes(), udpMsg.length(), serverAddr, PORT);
ds.send(dp);
Log.d(LOG_TAG,"packet send.");
}
catch (SocketException e)
{
e.printStackTrace();
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (ds != null)
{
ds.close();
}
}
}//end run
}//end class th
}
Make sure emulator is started, then in ADB shell, type this command, it will show ip address of emulator.
adb shell
ifconfig etho

Taking screenshot crashes app

I tried creating a screenshot app, but somehow I can not get the root content.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Canvas;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.MeasureSpec;
public class Screenshot extends Activity {
public final String TAG = "Screen";
String output;
public String takeScreen(String savepathname) {
Log.e(TAG, "TAKESCREEN 01");
//View content = findViewById(R.id.button1);
//View content = findViewById(R.id.layoutroot);
//View content = getWindow().getDecorView().findViewById(android.R.id.content);
Log.e(TAG, "TAKESCREEN 01.5");
content.setDrawingCacheEnabled(true);
Log.e(TAG, "TAKESCREEN 02");
//View content = findViewById(R.id.layoutroot);
Bitmap bitmap = content.getDrawingCache();
File file = new File( Environment.getExternalStorageDirectory() + savepathname);
Log.e(TAG, "TAKESCREEN 03");
try{
Log.e(TAG, "TAKESCREEN 04");
file.createNewFile();
Log.e(TAG, "TAKESCREEN 05");
FileOutputStream ostream = new FileOutputStream(file);
Log.e(TAG, "TAKESCREEN 06");
bitmap.compress(CompressFormat.PNG, 100, ostream);
Log.e(TAG, "TAKESCREEN 07");
ostream.close();
output = "Successfully saved -> "+savepathname;
}catch (Exception e) {
e.printStackTrace();
output = "Screenshot.java -> "+e;
}
return output;
}
}
If I use findViewbyId, I only get this error: "layoutroot cannot be resolved or is not a field".
While using "getWindow().getDecorView().findViewById(android.R.id.content);" works, but then the app crashes in that part.
Could someone help me with that, please?
Did you implement this part too? If you didn't, place it inside your Screen class. By the way, I strongly believe that going over this activity lifecycle tutorial will help you.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Assuming that button1 and layoutroot are properly described within activity_main.xml

How to write (and append) data to text files externally? (test using real device vs emulator)

First, I used the code below that I wrote with the help from:
How to save parsed text file in internal/external storage in android
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button) findViewById(R.id.button1);
b.setOnClickListener(this);
}
#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 void onClick(View v) {
String string = "nooooon";
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard.getAbsolutePath() + "/MyFiles");
directory.mkdirs();
File file = new File(directory, "mysdfile.txt");
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
OutputStreamWriter osw = new OutputStreamWriter(fOut);
try {
osw.write(string);
osw.flush();
osw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Then, I used emulator to test it, and it worked fine. I can see the new directory and the new file has been created. Now, I am not sure how I can append data to the current file, meaning that each time I press the button the data need to be appended in the next line.
Second, when I use a real device to test it, I cannot figure out where the new directory and file are created. I actually debugged the app and found that the new file is created under /storage/emulated/0/MyFiles/mysdfile.txt , but I cannot actually see the file in the file explorer or on the device. (Also, I gave permission to write) how can I see the newly generated files/directories?
I appreciate your time.

Run script with android app

i've got this shell script:
#!system/bin/sh
while :
do
sync
echo 3> /proc/sys/vm/drop_caches
echo "Script is been launched"
sleep 30m
done
exit 0;
i wish run this script with an android app. I have already created a button with only a toast for now. How can i take the script (free.sh) and launch it with the button on the app? Or is there a solution to rewrite the code in java? Thanks
First, you will use Eclipse to create a simple Android helloworld app.
And add a button in your layout. This is very priliminary practise of Android development which you can dig a lot more from http://d.android.com
please try this code in your button's onclick call back function:
Button b = (Button)findViewById(R.id.buttonPower);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Process p=null;
try {
p = new ProcessBuilder()
.command("PathToYourScript")
.start();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(p!=null) p.destroy();
}
}
});
Here is how you can run shell script from your android app
try {
Process process = Runtime.getRuntime().exec("sh /sdcard/test.sh");
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String listOfFiles = "";
String line;
while ((line = in.readLine()) != null) {
listOfFiles += line;
}
}
catch (IOException e) {
e.printStackTrace();
}
Well, now No errors (THANK YOU!) but do nothing..to try i've written a easy script that write a file.txt. See the code:
package com.mkyong.android;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import java.io.IOException;
import com.example.toast.R;
public class MainActivity extends Activity {
private Button button;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab1);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#SuppressLint("SdCardPath")
#Override
public void onClick(View arg0) {
Process p=null;
try {
p = new ProcessBuilder()
.command("/sdcard/Script/scritturafile.sh")
.start();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(p!=null) p.destroy();
}
}
});
}
}
The are no errors but when i press the button i think the shell doesn't go so don't create the file.txt
I've got errors in my code:
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import com.example.toast.R;
public class MainActivity extends Activity {
private Button button;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab1);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Process process = new ProcessBuilder()
.command("PATH")
.redirectErrorStream(true)
.start();
try {
InputStream in = process.getInputStream();
OutputStream out = process.getOutputStream();
readStream(in);// Here: Syntax error, insert "}" to complete `Block`
finally {
process.destroy();
}
}
}
}); //Here: Syntax error on token "}", delete this token
}
protected void readStream(InputStream in) {
// TODO Auto-generated method stub
}
}

How to check if my App is downloading a file from FTP

I am trying to download a file from FTP via my app. But neither of my toasts show. How can I check if I am connected and if the file is downloaded?
Code:
package no.kraftpriser.oversikt;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.SocketException;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTPClient;
public class KraftpriserActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
FTPClient ftp;
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
int duration2 = Toast.LENGTH_LONG;
ftp = new FTPClient();
ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
try {
int reply;
String server = "62.97.235.213";
int port = 21;
ftp.connect(server, port);
ftp.login("anonymous","nobody");
ftp.enterLocalPassiveMode();
ftp.changeWorkingDirectory("/Fastpris");
InputStream inStream = ftp.retrieveFileStream("2011.txt");
CharSequence tilkoblet = "Connected!";
Toast toastTilkoblet = Toast.makeText(context, tilkoblet, duration2);
toastTilkoblet.show();
reply = ftp.getReplyCode();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
if (ftp.isConnected()) {
try {
ftp.disconnect();
}
catch (IOException f) {
//Do nothing
}
}
CharSequence ikkeTikoblet = "Kunne ikke koble til server";
Toast toastIkkeTilkoblet = Toast.makeText(context, ikkeTikoblet, duration);
toastIkkeTilkoblet.show();
e.printStackTrace();
}
}
}
Your "connected" toast wouldn't show until your transfer is complete since getFileAsStream will block until the transfer is completed. Additionally, you're just loading the file into an InputStream in the code above... you still need to write that input stream to a file if you want to persist it to your SD card or internal storage.
To be able to see the progress of the download, you'd need to do the actual download in a background thread (use AsyncTask). You can then post status updates back to the UI thread via the onProgressUpdate method.
Depending on the FTP client you're using, you can also probably check the return value from the connect and/or login method to see if each of those operations was successful.

Categories

Resources