简体   繁体   中英

Unable to pass context from main activity to non-activity using main function

I have a MainActivity class where I have implemented a main function. This main function calls a non-activity class by passing a context (unable to implement). In the non activity class, I want to access a file from the assets folder (which requires a context, hence the passing of one) and print it in the LogCat. This is how I am trying to do it

MainActivity:

public class MainActivity extends AppCompatActivity
{

    public static void main(String[] args)
    {
        DiseaseAlgo(this).Parser();//Error. Unable to pass context
        return;
    }

    //etc
}

NonActivity Class:

package com.iotaconcepts.aurum;
import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;

import java.io.FileReader;
import java.io.IOException;

public class DiseaseAlgo
{
    static Context mContext;
    public DiseaseAlgo(Context context)
    {
        mContext = context;
    }

    public static void Parser() throws IOException
    {
        AssetManager as=mContext.getAssets();
        String parse=as.open("symp.txt").toString();
        String[] xx=parse.split("\t");
        for(String i:xx)
            Log.w("DiseaseAlgo", i);
    }
}

I'm unable to figure out how to pass the context and call the 'DiseaseAlgo' method from this function. I keep getting:

package name .MainActivity.this cannot be referenced from static content

I need this to check the correctness of my text parsing and this is the only way to show it on the LogCat.

The problem is that you are using the word this from a static function. Since the function is static, the class may or may not have an instance. What is calling that function?

If your instance of your activity is calling your Main() then pass it's context ( this ) as an arguement so the static function has access to it.

I would guess Main() is not from android's functions right? Normaly in a main() function you should initialize objects before passing them around so this does not make sense, but I don't think android works that way.

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