Android FTP Server - android

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

Related

Multithreading with Android

I am trying to develop simple Multi-threading Application in Android. Here is my code below:
package com.sudarshan.mythread;
import android.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity implements Runnable {
EditText t;
StringBuffer buffer = new StringBuffer();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t=(EditText) findViewById(R.id.editText);
int n = 8; // Number of threads
for (int i=0; i<n; i++)
{
Thread object = new Thread(new MainActivity());
object.start();
t.setText(buffer.toString());
}
}
public void run()
{
try
{
// Displaying the thread that is running
buffer.append ("Thread " +
Thread.currentThread().getId() +
" is running");
}
catch (Exception e)
{
// Throwing an exception
showMessage("Error","Error Message");
}
}
public void showMessage(String title,String Message)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
} }
And am trying to display data in stringbuffer buffer.The data should be appended in Stringbuffer everytime a thread is run.But nothing is shown via edit text.What am I doing wrong?
You have written t.setText(buffer.toString()); immediately after threads have been started. But by that time, the buffer might not have been updated. So, update the EditText after the buffer is updated.
buffer.append ("Thread " +
Thread.currentThread().getId() +
" is running");
// Note: If you want to update UI from background thread, you should do it the following way.
runOnUiThread(new Runnable() {
public void run(){
t.setText(buffer.toString());
}
});
Also, as #Bek stated, you should replace new MainActivity() with this.

app crashes when asynctask closed with no internet connection

i am trying out below code everything works fine when net is connected
here is the workflow
there is a main activity from where on button click this activity should open
it would do the parsing part and then go to next list activity.in case there is a back press or this activity is closed the asynctask should stop using
loader.cancel(true);
this would work perfectly if net is available and tested the issue happens when dont have internet connection
the alert box shows and it goes to the first activity then it crashes
i want the alert box to show and app should not crash and go back to first -->mainactivity
i have refereed this
http://techiedreams.com/android-simple-rss-reader/
How to end AsyncTask onBackPress()
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import com.parser.DOMParser;
import com.parser.RSSFeed;
public class SplashActivity extends Activity {
//private String RSSFEEDURL = "http://www.mobilenations.com/rss/mb.xml";
RSSFeed feed;
private AsyncLoadXMLFeed loader;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Intent i = getIntent();
int position = i.getExtras().getInt("position");
String[] country = i.getStringArrayExtra("country");
//Toast.makeText(getApplicationContext(), country[position], Toast.LENGTH_SHORT).show();
//Toast.makeText(getApplicationContext(), country[position], Toast.LENGTH_SHORT).show();
String name = i.getStringExtra("name");
//Toast.makeText(getApplicationContext(), name, Toast.LENGTH_SHORT).show();
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() == null) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Unable to reach server, \nPlease check your connectivity.")
.setTitle("TD RSS Reader")
.setCancelable(false)
.setPositiveButton("Exit",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int id) {
//loader.cancel(true);
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
} else {
// Connected - Start parsing
loader = new AsyncLoadXMLFeed();
loader.execute();
//new AsyncLoadXMLFeed().execute();
}
}
private class AsyncLoadXMLFeed extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... params) {
// Obtain feed
DOMParser myParser = new DOMParser();
Intent i = getIntent();
int position = i.getExtras().getInt("position");
String[] country = i.getStringArrayExtra("country");
String name = i.getStringExtra("name");
//feed = myParser.parseXml(RSSFEEDURL);
feed = myParser.parseXml("http://"+name+".blogspot.com//feeds/posts/default/-/" + country[position] + "?alt=rss");
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed);
// launch List activity
Intent intent = new Intent(SplashActivity.this, ListActivity.class);
intent.putExtras(bundle);
startActivity(intent);
// kill this activity
finish();
}
}
#Override
public void onBackPressed() {
finish();
}
#Override
public void onDestroy(){
super.onDestroy();
// Cancel the task
loader.cancel(true);
}
My guess it crashes with NullPointerException.
It is because if you don't have network connectivity you don't create AsyncLoadXMLFeed instance.
So when onDestroy() happened and you call loader.cancel(true); it throws this Exception.
finally did this
thanks anatol needed to check loader != null
#Override
public void onDestroy(){
super.onDestroy();
// Cancel the task
if(loader != null && loader.getStatus() != AsyncTask.Status.FINISHED) {
loader.cancel(true);
}
//loader.cancel(true);
}
The best and simplest solution for handle this issue is that use try catch block in your onPost execute() in async task. like this
#Override
protected void onPostExecute(String s) {
try {
super.onPostExecute(s);
loading.dismiss();
}catch (Exception ex){
Toast.makeText(UserLogin.this, "Something is going wrong, please try again!", Toast.LENGTH_LONG).show();
}
}
simply this will prevent your app from crash.

Force Close by using Async Task

I want to display a progressdialog when a client sends request to the server..the request should be done in background...but i am getting a force close when i use the AsyncTask..Please help ..Thank you
package com.example.client;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
public static ProgressDialog Dialog;
String s1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// sendreq();
new SendUserTask().execute();
}
});
}
public String sendreq() {
try {
// TODO Auto-generated method stub
SocketAddress sockaddr = new InetSocketAddress("192.168.7.116",
9011);
Socket serversocket = new Socket();
serversocket.connect(sockaddr, 10000);
serversocket.setSoTimeout(10000);
DataOutputStream out = new DataOutputStream(
serversocket.getOutputStream());
out.flush();
DataInputStream in = new DataInputStream(
serversocket.getInputStream());
out.flush();
String msg = "";
msg = "hi";
out.writeBytes(msg);
out.flush();
byte[] message = new byte[100];
in.read(message);
s1 = new String(message);
Toast.makeText(getApplicationContext(), s1, Toast.LENGTH_LONG)
.show();
((TextView) findViewById(R.id.textView1)).setText(s1);
in.close();
out.close();
serversocket.close();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), String.valueOf(e),
Toast.LENGTH_LONG).show();
}
return null;
}
private class SendUserTask extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
Dialog = ProgressDialog.show(MainActivity.this, "",
"Logging In....", true);
super.onPreExecute();
}
protected void onPostExecute(String s) {
if (Dialog.isShowing())
Dialog.dismiss();
}
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
return sendreq();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), String.valueOf(e),
Toast.LENGTH_SHORT).show();
}
return null;
}
}
}
this ((TextView) findViewById(R.id.textView1)).setText(s1); is executed from the background thread. you cannot access UI elements outside the UI thread.
You need to move that part to either onProgressUpdate or onPostExecute, or to run it in a runOnUiThread Runnable.
doInBackgorund() is a non-UI thread and you cannot access UI elements inside it. The code inside doInBackground() runs on a separate non-ui thread which does not have access to the UI elements defined in your layout. Also, since you are calling another Activity via intents, you should always keep in mind that an Activity runs on the UI thread and hence you should never start another Activity from inside a non-ui thread.
So, remove the code " ((TextView) findViewById(R.id.textView1)).setText(s1); " accessing the UI elements from inside of doInBackground() and instead put it inside onPostExecute(), which is a UI thread and is called after doInBackground() finishes the background processing.
Ok.... After googling a lot i finally came to understand that you cant access UI elements from main thread into a new non-UI thread....So you cant use elements like textview or even getApplicationContext mtd tht v use for toast in the dobackground mtd or even in anyother mts that the dobackground is calling....This also applies for the new Thread() using runnable..Thank you njzk2 for your help :)

http-request from Button VS from Class

i got a class i made, that makes a simple GET request and displays toast messege with the response...
if i call the function from a bottom event click it displays the messege with the data returned, just ok.
but if i call the same function from a brodcast reciver class, it just showing the massege with the data '' (null)
i belive that it showing the massege before i could get the data, and with the button it waits for the data..
how can i make it work from the brodcast reciver?
the class:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.content.Context;
import android.widget.Toast;
public class myclass{
public static void doHttpRequest(String param1, Context context){
String ret="";
try {
URL url = new URL("http://website.com/page?param="+param1);
HttpURLConnection con = (HttpURLConnection) url
.openConnection();
ret=readStream(con.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
CharSequence text = "return data- "+ret;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
private static String readStream(InputStream in) {
BufferedReader reader = null;
String line = "";
String alllines = "";
try {
reader = new BufferedReader(new InputStreamReader(in));
while ((line = reader.readLine()) != null) {
alllines=alllines+line;
}
return alllines;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return alllines;
}
}
from the button it works fine:
final Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
myclass.doHttpRequest("blabla", getBaseContext());
}});
from the brodcast reciver witch in different class it won't return data, but shows the toast..
public class CustomBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "CustomBroadcastReceiver";
#Override
public void onReceive(Context context, Intent intent) {
myclass.doHttpRequest("blabla", context);
break;
} }
}
please HELP.... :) THANKS
All fixed.. it's seems to be a project settings error, or premmisions error (but i had the premissions in the manifest... must not apply in the apk while compiling)
i copied the classes to enother project made by erlier version of eclipse, and it's works there like a charm...
thanks anyway..
i tried for hours to fix it in the code.. and it was the settings....
I created a myclass.java and CustomBroadcastReceiver.java and tried your code by removing the break statement and one extra curly brace from the CustomBroadcastReceiver.java class and it worked fine for me.
The following code in Activity class demonstrates registering, uninteresting receiver and a Handler for a sample/test broadcast.
CustomBroadcastReceiver customBroadcastReceiver;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
customBroadcastReceiver = new CustomBroadcastReceiver();
registerReceiver(cusoBroadcastReceiver, new IntentFilter("com.example.app.testbroadcast"));
// For test broadcast only.
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
sendBroadcast(new Intent("com.example.app.testbroadcast"));
}
}, 2000);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(customBroadcastReceiver);
}
Hope this helps.

Android - app force closes when no Internet connection

package info.testing;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.widget.Toast;
public class SoupActivity extends Activity {
private static final String TAG = "SoupActivity";
private static final String DATA = null;
private String data = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if(savedInstanceState != null)
{
data = savedInstanceState.getString(DATA);
showResults();
}
else
{
parsePage();
}
}
protected void parsePage(){
Document doc = null;
try {
doc = Jsoup.connect("http://www.mydata.html").get();
Toast.makeText(this, R.string.success, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(this, R.string.error, Toast.LENGTH_SHORT).show();
}
Elements rows = doc.select("tr[class]");
data = "<table>" + rows.toString() + "</table>";
showResults();
}
protected void showResults(){
WebView web = (WebView)findViewById(R.id.web);
web.loadData(data, "text/html", "utf-8");
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
savedInstanceState.putString(DATA, data);
super.onSaveInstanceState(savedInstanceState);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState){
if(savedInstanceState != null)
{
data = savedInstanceState.getString(DATA);
}
super.onRestoreInstanceState(savedInstanceState);
}
}
Flash/Flex developer here starting to get in to Android development, I must admit I am loving it so far, but obviously taking a long time to work out why things happen the way they do.
So the problem I have is that my app crashes without an Internet connection - The application (process.testing) has stopped unexpectedly. This only happens when there is no internet connection and works perfectly if there is one. The only part of my code that accesses the Internet is in a try catch block, can anyone see what I'm doing wrong or how I can handle the error when there is no Internet connection available?
You can use this function to see if a connection is available :
/**
* Check the network state
* #param context context of application
* #return true if the phone is connected
*/
public static boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
return true;
}
return false;
}
When you have no internet connection, doc is probably null and you get NullPointerException because you don't check this case:
Document doc = null;
try {
// connect throws an exception, doc still null
doc = Jsoup.connect("http://www.mydata.html").get();
Toast.makeText(this, R.string.success, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(this, R.string.error, Toast.LENGTH_SHORT).show();
}
// dereferencing null (doc) throws NullPointerException
Elements rows = doc.select("tr[class]");

Categories

Resources