简体   繁体   English

Android FTP上传错误

[英]Android FTP Upload Error

Hi this is my first post, so sorry if i make any mistakes. 嗨,这是我的第一篇文章,对不起,如果我犯任何错误。

Here is my Problem: I am writing an App which should save the Date of today with the time in a txt file when you click a button and then send it to a FTP Server if you click another button. 这是我的问题:我正在编写一个应用程序,当您单击一个按钮时,该应用程序应该将今天的日期和时间保存在txt文件中,如果您单击另一个按钮,则将其发送到FTP服务器。 I use the Apache commons library for the FTP Connection. 我将Apache Commons库用于FTP连接。

That is my MainActivity: 那就是我的MainActivity:

package com.example.timestamp;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.DateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import it.sauronsoftware.ftp4j.FTPClient;

public class MainActivity extends Activity {
    private static final String TAG = MainActivity.class.getName();
    final File log = new File("TimeStampLog.txt");
    final String SERVER = "***************";
    final String USERNAME = "**************";
    final String PASSWORD = "*************";
    final int PORT = 21;
    final TextView tv = (TextView) findViewById(R.id.textView1);
    Button save = (Button) findViewById(R.id.save);
    Button send = (Button) findViewById(R.id.send);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        save.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                String date = DateFormat.getDateTimeInstance().format(new Date());
                tv.setText(date);
                StringBuilder sb = new StringBuilder();
                sb.append(date);
                sb.append("\r\n");
                sb.append(readFromFile());
                writeToFile(sb.toString());
            }
        });

        send.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                uploadFile(log);
            }
        });
    }


    @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.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void uploadFile(File fileName) {

        FTPClient client = new FTPClient();

        try {

            client.connect(SERVER, 21);
            client.login(USERNAME, PASSWORD);
            client.setType(FTPClient.TYPE_BINARY);

            client.upload(log);

        } catch (Exception e) {
            e.printStackTrace();
            try {
                client.disconnect(true);
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

    }

    private void writeToFile(String data) {
        try {
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
                    openFileOutput(log.getName(), Context.MODE_PRIVATE));
            outputStreamWriter.write(data);
            outputStreamWriter.flush();
            outputStreamWriter.close();
        } catch (IOException e) {
            Log.e(TAG, "File write failed: " + e.toString());
        }

    }

    private String readFromFile() {

        String ret = "";

        try {
            InputStream inputStream = openFileInput(log.getName());

            if (inputStream != null) {
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String receiveString = "";
                StringBuilder stringBuilder = new StringBuilder();

                while ((receiveString = bufferedReader.readLine()) != null) {
                    stringBuilder.append(receiveString);
                    stringBuilder.append("\r\n");
                }

                inputStream.close();
                ret = stringBuilder.toString();
            }
        } catch (FileNotFoundException e) {
            Log.e(TAG, "File not found: " + e.toString());
        } catch (IOException e) {
            Log.e(TAG, "Can not read file: " + e.toString());
        }

        return ret;
    }
}

My XML File: 我的XML文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.timestamp.MainActivity" >

<TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:ems="10" />

    <Button
        android:id="@+id/save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="60dp"
        android:text="@string/save" />

    <Button
        android:id="@+id/send"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/save"
        android:layout_alignBottom="@+id/save"
        android:layout_alignParentRight="true"
        android:text="@string/send" />

</RelativeLayout>

And here is the LogCat Output: 这是LogCat输出:

08-14 13:51:45.919: E/AndroidRuntime(14598): FATAL EXCEPTION: main
08-14 13:51:45.919: E/AndroidRuntime(14598): Process: com.example.timestamp, PID: 14598
08-14 13:51:45.919: E/AndroidRuntime(14598): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.timestamp/com.example.timestamp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
08-14 13:51:45.919: E/AndroidRuntime(14598):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
08-14 13:51:45.919: E/AndroidRuntime(14598):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
08-14 13:51:45.919: E/AndroidRuntime(14598):    at android.app.ActivityThread.access$800(ActivityThread.java:144)
08-14 13:51:45.919: E/AndroidRuntime(14598):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
08-14 13:51:45.919: E/AndroidRuntime(14598):    at android.os.Handler.dispatchMessage(Handler.java:102)
08-14 13:51:45.919: E/AndroidRuntime(14598):    at android.os.Looper.loop(Looper.java:135)
08-14 13:51:45.919: E/AndroidRuntime(14598):    at android.app.ActivityThread.main(ActivityThread.java:5221)
08-14 13:51:45.919: E/AndroidRuntime(14598):    at java.lang.reflect.Method.invoke(Native Method)
08-14 13:51:45.919: E/AndroidRuntime(14598):    at java.lang.reflect.Method.invoke(Method.java:372)
08-14 13:51:45.919: E/AndroidRuntime(14598):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
08-14 13:51:45.919: E/AndroidRuntime(14598):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
08-14 13:51:45.919: E/AndroidRuntime(14598): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
08-14 13:51:45.919: E/AndroidRuntime(14598):    at android.app.Activity.findViewById(Activity.java:2071)
08-14 13:51:45.919: E/AndroidRuntime(14598):    at com.example.timestamp.MainActivity.<init>(MainActivity.java:33)
08-14 13:51:45.919: E/AndroidRuntime(14598):    at java.lang.reflect.Constructor.newInstance(Native Method)
08-14 13:51:45.919: E/AndroidRuntime(14598):    at java.lang.Class.newInstance(Class.java:1572)
08-14 13:51:45.919: E/AndroidRuntime(14598):    at android.app.Instrumentation.newActivity(Instrumentation.java:1065)
08-14 13:51:45.919: E/AndroidRuntime(14598):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2199)
08-14 13:51:45.919: E/AndroidRuntime(14598):    ... 10 more

Yes I added Internet into the uses-permission 是的,我将互联网添加到了使用权限中

I think the Problem might be that I need another Thread for the FTP implementation and i tried it with AsyncTask and Handler but I kept getting the same error. 我认为问题可能是我需要另一个线程来实现FTP,并且我使用AsyncTask和Handler进行了尝试,但我一直遇到相同的错误。

From LogCat Output I can see that you are getting NullPointerException because You have initialized your Button and TextView where we can declare any variable. 从LogCat输出中,我可以看到您正在获取NullPointerException,因为您已经初始化了Button和TextView,可以在其中声明任何变量。

You have initlize and inflate all Buttons and TextView before Calling setContentView(R.layout.activity_main); 在调用setContentView(R.layout.activity_main);之前,您已经对所有Button和TextView进行了初始化和膨胀 in OnCreate() method. OnCreate()方法中。 You have move your code in OnCreate Method then Try to upload file. 您已经在OnCreate方法中移动了代码,然后尝试上传文件。

You can try this code: 您可以尝试以下代码:

package com.example.timestamp;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.DateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import it.sauronsoftware.ftp4j.FTPClient;

public class MainActivity extends Activity {
    private static final String TAG = MainActivity.class.getName();
    final File log = new File("TimeStampLog.txt");
    final String SERVER = "***************";
    final String USERNAME = "**************";
    final String PASSWORD = "*************";
    final int PORT = 21;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final TextView tv = (TextView) findViewById(R.id.textView1);
        Button save = (Button) findViewById(R.id.save);
        Button send = (Button) findViewById(R.id.send);
        save.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                String date = DateFormat.getDateTimeInstance().format(new Date());
                tv.setText(date);
                StringBuilder sb = new StringBuilder();
                sb.append(date);
                sb.append("\r\n");
                sb.append(readFromFile());
                writeToFile(sb.toString());
            }
        });

        send.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                uploadFile(log);
            }
        });
    }


    @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.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void uploadFile(File fileName) {

        FTPClient client = new FTPClient();

        try {

            client.connect(SERVER, 21);
            client.login(USERNAME, PASSWORD);
            client.setType(FTPClient.TYPE_BINARY);

            client.upload(log);

        } catch (Exception e) {
            e.printStackTrace();
            try {
                client.disconnect(true);
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }

    }

    private void writeToFile(String data) {
        try {
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
                    openFileOutput(log.getName(), Context.MODE_PRIVATE));
            outputStreamWriter.write(data);
            outputStreamWriter.flush();
            outputStreamWriter.close();
        } catch (IOException e) {
            Log.e(TAG, "File write failed: " + e.toString());
        }

    }

    private String readFromFile() {

        String ret = "";

        try {
            InputStream inputStream = openFileInput(log.getName());

            if (inputStream != null) {
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String receiveString = "";
                StringBuilder stringBuilder = new StringBuilder();

                while ((receiveString = bufferedReader.readLine()) != null) {
                    stringBuilder.append(receiveString);
                    stringBuilder.append("\r\n");
                }

                inputStream.close();
                ret = stringBuilder.toString();
            }
        } catch (FileNotFoundException e) {
            Log.e(TAG, "File not found: " + e.toString());
        } catch (IOException e) {
            Log.e(TAG, "Can not read file: " + e.toString());
        }

        return ret;
    }
}

I hope it helps! 希望对您有所帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM