android studio应用程序无法运行单独的类

时间:2018-03-06 17:47:17

标签: android-studio

我正在编写一个android工作室应用程序我的代码如下所示是我创建的类,如果我从MainActivity类运行代码它完美地运行但分离到它自己的类它崩溃应用程序我认为这是由于我不理解如何在android studio中使用类可以解释我做错了什么

这是有问题的课程

package edu.bsu.cs222.teamc_cardinal_calorie_counter;

import android.app.Application;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by Benaiah on 3/6/2018.
 */

public class FileData extends Application {
    public String openFile(){
        String text = "sumthing went wrong";
        InputStream inputStream;
        try {
            inputStream = getAssets().open("boarshead.txt");
            int size = inputStream.available();
            byte[] buffer = new byte[size];
            inputStream.read(buffer);
            inputStream.close();
            text = new String(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return text;
    }
}

这是调用它的MainActivity类

package edu.bsu.cs222.teamc_cardinal_calorie_counter;

import android.content.res.AssetManager;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.IOException;
import java.io.InputStream;

public class MainActivity extends AppCompatActivity {

    Button button;
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        button = findViewById(R.id.button);
        textView = findViewById(R.id.read);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FileData fileData = new FileData();
                textView.setText(fileData.openFile());
            }
        });
    }

}

感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

您必须在MainActivity中导入FileData,并将openFile方法作为静态方法。