简体   繁体   中英

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. I use the Apache commons library for the FTP Connection.

That is my 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:

<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:

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.

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.

You have initlize and inflate all Buttons and TextView before Calling setContentView(R.layout.activity_main); in OnCreate() method. You have move your code in OnCreate Method then Try to upload file.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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