java - 获取非 Activity 类中的应用程序上下文以传递 CSV 文件

标签 java android csv

我正在尝试弄清楚如何读取存储在 Assets 文件夹中的 CSV 文件。我尝试做的是使用 InputFileStream,因为我无法让 FileReader 找到文件。所以我将文件放入 Assets 文件夹中并使用InputFileStream。

为此,我使用了 AssetManager。问题是这是一个非 Activity 类,从主 Activity 传递上下文真的很难,因为它是一系列方法。

它以 loadCategory() 开头:

  loadCategory(0);

这在术语中称为 ToolSource 类(单例):

public void loadCategory(int categoryIndex) {
    ...
ToolsCategory cat = ToolsSource.getInstance().getCategory(categoryIndex);

这会创建一个 ToolCategories[] 数组:

 public static ToolsSource getInstance() {
    if (instance == null) {
        try {
            instance = new ToolsSource();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return instance;
}

public ToolsSource() throws IOException {
    int i;
    mCategory = new ToolsCategory[CATEGORIES.length];
    for (i = 0; i < CATEGORIES.length; i++) {
        mCategory[i] = new ToolsCategory(CATEGORIES[i]);
    }
}

最终到达发生此错误的主类。此类的要点是填充 Tool[] 数组(各个类别),该数组又填充 mCategory[] 数组中的每个 ToolCategories。 LoadCategory 加载调用 getCategory(0),该调用提取 mCategory[] 中第一个类别的名称并通过适配器分配它。

我想要做的是解析一个 CSV,其中包含所有工具的信息,作为 CSV 中代表每个类别的单独行。例如categoryName.csv 包含 3 行,因此 3 个工具。

然后,它迭代并将 3 行中的信息分配给 Tool() 类的成员字段。例如mTools[i].setTitle(nextLine[0]);

package com.anothergamedesigner.listviewtest;
import android.content.Context;
import android.content.res.AssetManager;
import com.opencsv.CSVReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class ToolsCategory {

final int TOOLS_PER_CATEGORY = 10;

Context context;

private CSVReader reader;
private String categoryName;
Tool[] mTools;

public ToolsCategory(String name) throws IOException {
    this.context = context.getApplicationContext();
    AssetManager assetManager = context.getAssets();
    categoryName = name;
    mTools = new Tool[TOOLS_PER_CATEGORY];
    assignValues(categoryName, assetManager);
}

private void assignValues(String name, AssetManager am) {
    String categoryCSV = name + ".csv";
    System.out.println("category name is: "+ categoryCSV);

    int i;
    for(i= 0; i<mTools.length; ++i){
        try {
            InputStream csvStream = am.open(categoryCSV);
            InputStreamReader csvStreamReader = new InputStreamReader(csvStream);
            reader = new CSVReader(csvStreamReader);

            String [] nextLine;

            while ((nextLine = reader.readNext()) != null) {
                // nextLine[] is an array of values from the line
                System.out.println("New title is: " + nextLine[0]);
                mTools[i].setTitle(nextLine[0]);
                System.out.println("New Subtitle is: " + nextLine[0]);
                mTools[i].setSubtitleTxt(nextLine[1]);
                System.out.println("New Description is: " + nextLine[0]);
                mTools[i].setDescriptionTxt(nextLine[2]);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public int getToolCount(){
    return mTools.length;
}

public Tool getTool(int index){
    return mTools[index];
}
}

但是,我收到一条错误消息: 尝试在空对象引用上调用虚拟方法“android.content.Context android.content.Context.getApplicationContext()”。

有什么方法可以解决这个问题,或者有替代方法来检索 csv 的 Uri/文件路径,以便我可以将其提供给 CSVReader 解析器吗?

最佳答案

您需要给出 Activity 的背景

loadCategory(0); - > loadCategory(0, this);

像这样修复代码:

1.

   public void loadCategory(int categoryIndex, Context context) {
    ...
   ToolsCategory cat = ToolsSource.getInstance(context).getCategory(categoryIndex);

2.

public static ToolsSource getInstance(Context context) {
    if (instance == null) {
        try {
            instance = new ToolsSource(context);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return instance;
}

3.

public ToolsSource(Context context) throws IOException {
    int i;
    mCategory = new ToolsCategory[CATEGORIES.length];
    for (i = 0; i < CATEGORIES.length; i++) {
        mCategory[i] = new ToolsCategory(CATEGORIES[i], context);
    }
}

4.

public ToolsCategory(String name, Context context) throws IOException {
    this.context = context;
    AssetManager assetManager = context.getAssets();
    categoryName = name;
    mTools = new Tool[TOOLS_PER_CATEGORY];
    assignValues(categoryName, assetManager);
}

关于java - 获取非 Activity 类中的应用程序上下文以传递 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37868277/

相关文章:

java - 无法通过 Java 应用程序连接到 Hive

java - 从闰年计算年数

android - 谷歌云 SQL App Engine API 身份验证

java - 我应该使用什么命令来解决这个问题?

python - 从字符串创建 Pandas DataFrame

python - 如何读取、清理并将 START 和 END 标记附加到类似 csv 的文件?

java - 在java中存储PostgreSQL/PostGIS "geometry(MultiPolygon)"数据类型

iphone - 如何从 My WebApp 调用 YouTube 应用程序

php - 导入和更新 CSV 到 MySQL

java - 拥有多项工作并选择我想在 Spring 中运行的一项