Search code examples
javaandroidandroid-assets

The getAssets() method in the Android library does not work


As a newbie to Android programming, I have attached four files to the assets folder of my library.
You can see the attached image.

Library

I want to access these files through the Android library using the below code (if I don't use this code in Android library, it runs without an error when I use it in MainActivity).

public void copy_weights() {
    try {
        AssetManager assetFiles = getAssets();
        String[] files = assetFiles.list("");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (NullPointerException e) {
        e.printStackTrace();  //catch the error in this line
    } catch (Exception e) {
        e.printStackTrace();
    }
}

but this code give me the error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.AssetManager android.Context.getAssets' on a null object refrence

I tried other methods like direct accessing via home:///android_asset/7.cfg but it can't access the files too.

EDIT 1

I call the copy_weights() in mainActivity like below

public class MainActivity extends AppCompatActivity {
@Override

protected void onCreate(Bundle savedInstanceState) {
    final new_class newClass=new new_class();
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final Button button =(Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            TextView textView=(TextView) findViewById(R.id.textView);
            newClass.copy_weights();
        }
    });
}

EDIT 2
new_class code

package com.example.mylittlelibrary;
import android.content.res.AssetManager;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity; 
import org.opencv.android.OpenCVLoader;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.dnn.Net;
import org.opencv.imgcodecs.Imgcodecs;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.File;

public class new_class extends AppCompatActivity {

    private boolean opencv_sucessfully_included;
    private static int BUFFER_SIZE = 1024;

    public new_class() { }

    private static void copyAssetFiles(InputStream in, OutputStream out) {
        try {

            byte[] buffer = new byte[BUFFER_SIZE];
            int read;

            while ((read = in.read(buffer)) != -1) {
                out.write(buffer, 0, read);
            }

            in.close();
            in = null;
            out.flush();
            out.close();
            out = null;

        } catch (IOException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void copy_weights() {
        try {
            AssetManager assetFiles = getAssets();
            // MyHtmlFiles is the name of folder from inside our assets folder
            String[] files = assetFiles.list("");
            // Initialize streams
            InputStream in = null;
            OutputStream out = null;
            for (int i = 0; i < files.length; i++) {
                File file = new File(Environment.getExternalStorageDirectory() + "/" + files[i]);
                if (!file.exists()) {
                    in = assetFiles.open(files[i]);
                    out = new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + files[i]);
                    copyAssetFiles(in, out);
                }
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Solution

  • You can't initialize an Activity like that. If you need a reference to a Context (such as with getAssets()) you should pass it to the class.

    First, remove your AppCompatActivity extension:

    public class new_class {
    

    Then change your constructor and add a global variable:

    private Context context;
    
    public new_class(Context context) {
        this.context = context;
    }
    

    You'll notice some of your methods are now in red and unresolved. Just add context. before them. For example

    context.getAssets()
    

    Make a new instance of that class by adding a this argument to it:

    final new_class newClass = new new_class(this);
    

    Also, you shouldn't put anything before super.onCreate() is called, so move that to go after it.