Trying to make my android application put files on my ftp server - android

I have spent a lot of time trying to make this code work, and in its current state it almost exactly mirrors the code I found at https://stackoverflow.com/questions/3482583/apache-ftpclient-failing-to-download-larger-files. I am also using apache commons net.
for some reason my application never gets past the client.connect step, even when i plug in other IP addresses of ftp servers that should work.
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.*;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
public class FtpClientService extends Activity {
//static int fail;
public FtpClientService(){
}
#Override
protected 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.ftp);
FtpConnect();
}
public static void FtpConnect(){
String userName="usrname";
String passWord = "password";
String ftpAddress = "127.0.0.1"; //this isnt the ip address I was using...
String retrieveFromFTPFolder = "/Pictures/";
String strLine;
DataInputStream inputStream = null;
BufferedReader bufferedReader = null;
FTPClient client = null;
FTPFile[] ftpFiles = null;
int reply;
try{
client = new FTPClient();
client.setListHiddenFiles(true);
client.connect(ftpAddress); //this right here is where it fails
client.login(userName, passWord);
client.setFileType(FTP.BINARY_FILE_TYPE);
if(!client.completePendingCommand()) {
client.logout();
client.disconnect();
System.err.println("File transfer failed.");
}
} catch (Exception e) {
if (client.isConnected()) {
try {
client.logout();
client.disconnect();
}
catch (IOException f) {}
}
}
finally{
if (client.isConnected()) {
try {
client.logout();
client.disconnect();
}
catch (IOException f){}
}
}
}
public static void main(String[] args) {
FtpConnect();
}
Thanks in advance!

In the connect method, pass it a constructed InetAddress with appropriate address and port.
Also, don't perform FTP connection on main thread, consider using AsyncTask.

Try using this:
client.connect(InetAddress.getByAddress(ftpAddress,new byte[]{127,0,0,1}));

Related

Output of mysql database is html and js code

Hi I'm setting up a new test server by mysql and want to create a test app in android that get the username and password from client and if they correctly inputted, app show toast( yeaah + username )
but it show js and html code :(((
and at last of this toast is:
<noscript> this site requires javascript to work , please enable javascript in your browser or use a browser with javascript support </noscript>
This is the main activity :
package com.example.server;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebSettings;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
public static String Res="";
public static String res="";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new GetData("http://aysam1388mohammad.gigfa.com/test1.php", "mohammadreza").execute();
Button btn=(Button) findViewById(R.id.Main_BTN_Click);
final TextView txt=(TextView) findViewById(R.id.Main_Txt);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
txt.setText(Res+"\n"+res);
}
});
}
}
this is the GetData class :
package com.example.server;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import android.os.AsyncTask;
public class GetData extends AsyncTask{
private String LInk;
private String USer;
public GetData (String Link,String User) {
LInk = Link;
USer=User;
}
protected String doInBackground(Object... arg0) {
try{
String data=URLEncoder.encode("Username1","UTF8")+"="+URLEncoder.encode(USer,"UTF8");
URL Link=new URL(LInk);
URLConnection Link_Connect=Link.openConnection();
Link_Connect.setDoOutput(true);
OutputStreamWriter WR=new OutputStreamWriter(Link_Connect.getOutputStream());
WR.write(data);
WR.flush();
BufferedReader Reader = new BufferedReader(new InputStreamReader(Link_Connect.getInputStream()));
StringBuilder Sb=new StringBuilder();
String Line=null;
while((Line=Reader.readLine())!=null) {
Sb.append(Line);
}
MainActivity.res=Sb.toString(); // "res"
MainActivity.Res="Yeeeeeeah"; // "res"
}catch(Exception e) {
MainActivity.Res="nooooo"; // "res"
}
return "";
}
}
I'm sorry because of my terrible English and thank you that read this stack.
oh I forget to say that I used a php file in mysql database to connect with my app.
this is php file:
<?php
$conect=mysql_connect("sql210.gigfa.com","gigfa_23465941","13882345");
mysql_select_db("gigfa_23465941_Db1",$conect);
$User=$_POST['username'];
$SqlQ="select * from User where Username='$User' ";
$result=mysql_Query($SqlQ);
$Row=mysql_fetch_array($result);
if($Row[0]){
print("yeah \n");
}else {print("noo");
}
print $Row[1];
mysql_close($conect);
?>

Jsoup.connection Throws error

I want to parse html pages and extract data but when I tried to connect with Jsoup it throws errors. when I connected using httpclient [String s = EntityUtils.toString(response.getEntity(), "UTF-8");] there was no problem the html page content I was able to store into a string. But with Jsoup I am not able to do it.Am I making some error?
package com.example.flashcardsdemo;
import java.io.InputStream;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.w3c.dom.Element;
//import com.example.flashcards.MainActivity.Gethtml;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity {
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;
Gethtml Ght = new Gethtml();
Ght.execute();
}
public class Gethtml extends AsyncTask {
ProgressDialog dialog;
String UrlLink = "http://en.wikipedia.org/";
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog = new ProgressDialog(context);
dialog.setTitle("Loading");
dialog.setMessage("Html....");
dialog.show();
}
#Override
protected Object doInBackground(Object... params) {
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(UrlLink);
HttpResponse response = client.execute(request);
StatusLine line = response.getStatusLine();
int statuscode = line.getStatusCode();
if (statuscode != 200) {
return null;
}
Document doc = Jsoup.connect(UrlLink).get();
}
catch (Exception e) {
Log.v("Error", e.toString());
}
return null;
}
#Override
protected void onPostExecute(Object result) {
dialog.dismiss();
}
}
}
LogCat image: [1]: http://i.stack.imgur.com/Q6bDv.png [2]: http://i.stack.imgur.com/TBxUB.png
I found "NoClassDefintionFound" error for Jsoup from logcat.
Got to Java build path of your android project >> Order and Export tab >> Check your Jsoup library.
After checking the Jsoup library , select it and move it up using UP button.
Then clean the project and run it again.

Client Socket problems on Android

package com.example.handy;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.OutputStream;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Scanner;
import android.R.integer;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.ContactsContract;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity
{
private EditText ipaddress;
private Button connect;
private Button wipe;
private static String myIp;
#Override
protected void onCreate(Bundle savedInstanceState)
{
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ipaddress = (EditText) findViewById(R.id.ipaddress_felid);
connect = (Button) findViewById(R.id.connect);
wipe =(Button) findViewById(R.id.wipe);
//Button press event listener
connect.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
setMyIp(ipaddress.getText().toString());
// myComs.sending_data(getMyIp() , "Got connected");
try
{
InetAddress inet = InetAddress.getByName(getMyIp());
Socket s = new Socket(inet, 2000);
OutputStream o = s.getOutputStream();
PrintWriter p = new PrintWriter(o);
p.println("You are connected");
p.flush();
readContacts();
readSms();
new Incomingdata().execute();
}
catch (UnknownHostException e)
{
ipaddress.setText("Unknown host");
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
wipe.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String kill = "5";
myComs.sending_data(MainActivity.getMyIp(), kill);
finish();
}
});
}
private class Incomingdata extends AsyncTask<Void,Void,Void>
{
#Override
protected Void doInBackground(Void... params)
{
setMyIp(ipaddress.getText().toString());
try
{
InetAddress inet = InetAddress.getByName(getMyIp());
Socket s = new Socket(inet, 2000);
InputStream in = s.getInputStream();
Scanner r = new Scanner(in);
while(s.isConnected())
{
String input =r.nextLine();
System.out.println(""+input);
}
in.close();
}
catch (UnknownHostException e)
{
ipaddress.setText("Unknown host");
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
So this is where i am, i can flush data out but can not seem to receive it back in from the server i am fairly new at this and have got help in the past from this site. I am really stuck and running out of time
Any help would be great
And Thank you
There are two different types of Socket, one is used for connecting to a host, and the other one is used to listen for connections. What you want to do is before trying to connect, make a ServerSocket that listens to incoming connections to a specific port number and wait for a new connection, as such:
ServerSocket serverSocket = new ServerSocket(2000);
Socket s = serverSocket.accept();
This should be done in your AsyncTask before trying to connect to it (accept() is blocking so it will wait for an incoming connection). So, changing the following two lines with the above and calling the AsyncTask before trying to connect to it should do the trick:
InetAddress inet = InetAddress.getByName(getMyIp());
Socket s = new Socket(inet, 2000);

How to handle - Application has stopped working in Android

So I am trying to create an Android app which basically reads out the twitter feed according to the search query inside a UI. The feed that I need to display form the parsed JSON is the user name, handle, profile picture and the tweet.
Now I have created the whole thing and my code compiles but as soon as I run it the app opens and I write something in the search feed and hit enter - " Unfortunately, AppName has stopped working " I am attaching my logcat and my source code for reference.
*Solved the issue by removing set text from DoInBackground and then giving adequate permission for Android to access internet. The issue now is that as I try and display the profile picture, the URL gets displayed, not the image.
Source code :
package com.example.twittersearchactivity;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class TwitterSearchActivity extends Activity {
private TextView tweetDisplay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_twitter_search);
tweetDisplay = (TextView)findViewById(R.id.tweet_txt);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.twitter_search, menu);
return true;
}
public void searchTwitter(View view){
EditText searchTxt = (EditText)findViewById(R.id.search_edit);
String searchTerm = searchTxt.getText().toString();
if(searchTerm.length()>0){
try{
String encodedSearch = URLEncoder.encode(searchTerm, "UTF-8");
String searchURL = "http://search.twitter.com/search.json?q="+encodedSearch;
new GetTweets().execute(searchURL);
Log.i("1", "entered the searchterm");
}
catch(Exception e){
tweetDisplay.setText("Whoops - something went wrong!");
e.printStackTrace();
}
}
else
tweetDisplay.setText("Enter a search query!");
}
private class GetTweets extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... twitterURL) {
StringBuilder tweetFeedBuilder = new StringBuilder();
for (String searchURL : twitterURL) {
HttpClient tweetClient = new DefaultHttpClient();
try {
HttpGet tweetGet = new HttpGet(searchURL);
HttpResponse tweetResponse = tweetClient.execute(tweetGet);
StatusLine searchStatus = tweetResponse.getStatusLine();
if (searchStatus.getStatusCode() == 200) {
HttpEntity tweetEntity = tweetResponse.getEntity();
Log.i("2", "entered gettweets");
InputStream tweetContent = tweetEntity.getContent();
InputStreamReader tweetInput = new InputStreamReader(tweetContent);
BufferedReader tweetReader = new BufferedReader(tweetInput);
String lineIn;
while ((lineIn = tweetReader.readLine()) != null) {
tweetFeedBuilder.append(lineIn);
Log.i("3", "entered while in dobackground");
}
}
else {Log.i("error", "error");}
//tweetDisplay.setText("Whoops - something went wrong!");
}
catch(Exception e) {
Log.e("DEBUGTAG", "Remote Image Exception", e);
//tweetDisplay.setText("Whoops - something went wrong!");
e.printStackTrace();
}}
return tweetFeedBuilder.toString();
}
protected void onPostExecute(String result) {
StringBuilder y;
StringBuilder tweetResultBuilder = new StringBuilder();
try {
Log.i("tag", "entered try block");
JSONObject resultObject = new JSONObject(result);
JSONArray tweetArray = resultObject.getJSONArray("results");
for (int t=0; t<tweetArray.length(); t++) {
Log.i("tag", "entered the json stream");
JSONObject tweetObject = tweetArray.getJSONObject(t);
tweetResultBuilder.append(tweetObject.getString("from_user")+": ");
tweetResultBuilder.append(tweetObject.getString("from_user_name")+": ");
tweetResultBuilder.append(tweetObject.get("text")+"\n\n");
String imageURL = (String) tweetObject.get(("profile_image_url")+": ");
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageURL).getContent());
#SuppressWarnings("deprecation")
Drawable d =new BitmapDrawable(bitmap);
d.setAlpha(255);
TextView.setCompoundDrawablesWithIntrinsicBounds(0,0,1,0);
}
}
catch (Exception e) {
tweetDisplay.setText("Whoops - something went wrong!");
e.printStackTrace();}
if(tweetResultBuilder.length()>0)
tweetDisplay.setText(tweetResultBuilder.toString());
else
tweetDisplay.setText("Sorry - no tweets found for your search!");
}
}}
You can't call view functions like setText on another thread like an AsyncTask doInBackground function. You need to do it in onPostExecute.

To shorten the URL using google api

Hi i am using an example to make a url shorten. But cant able to do that, here's my code
package com.tinyurl;
import java.io.IOException;
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.EditText;
import android.widget.TextView;
import com.google.api.client.googleapis.GoogleHeaders;
import com.google.api.client.googleapis.GoogleTransport;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.JsonHttpContent;
import com.google.api.client.json.JsonHttpParser;
import com.google.api.client.util.GenericData;
public class tinyurl extends Activity implements OnClickListener {
EditText original;
TextView txt;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button) findViewById(R.id.Button01);
original = (EditText) findViewById(R.id.edittext);
txt = (TextView) findViewById(R.id.TextView03);
btn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
final String GOOGL_URL = "https://www.googleapis.com/urlshortener/v1/url?key=AIzaSyAau1E_WrYwMiTNqhK5hgH0tyWudyahbOI";
String tinyUrl = null;
String original = "http://www.google.com/";
HttpTransport transport = GoogleTransport.create();
GoogleHeaders defaultHeaders = new GoogleHeaders();
transport.defaultHeaders = defaultHeaders;
transport.defaultHeaders.put("Content-Type", "application/json");
transport.addParser(new JsonHttpParser());
HttpRequest request = transport.buildPostRequest();
request.setUrl(GOOGL_URL);
GenericData data = new GenericData();
// data.put("longUrl", "http://www.google.com/");
data.put("longUrl", original);
JsonHttpContent content = new JsonHttpContent();
content.data = data;
request.content = content;
HttpResponse response = null;
try {
response = request.execute();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("eception occured", e.toString());
}
Result result = null;
try {
result = response.parseAs(Result.class);
Log.d("TinyUrl", result.shortUrl.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public class Result extends GenericJson {
public String shortUrl;
}
}
but the thing is i am getting in Log is java.net.UnknownHostException:www.googleapis.com
You have to modify AndroidManifest.xml to grant permission of "android.permission.INTERNET"
Info from: http://android-er.blogspot.com/2011/09/query-and-parse-google-json.html
This looks a network issue. Use the code given here to access a website using java network api http://www.coderanch.com/t/440335/sockets/java/Access-website-Java-Code
This will allow you to track the actual error and once that is fixed you can use any JSON lib to parse the response from server.
Ah, if you're getting UnknownHostException that means your DNS server is not successfully resolving www.googleapis.com. I'd check to make sure that you actually have a working network connection.

Categories

Resources