简体   繁体   English

从assests文件夹中获取资源时出错

[英]Error fetching resources from assests folder

I have recently started a new project, at the moment I am trying to create a SQLite database from within the main activity and read from a text file located in my assests folder.我最近开始了一个新项目,目前我正在尝试从主要活动中创建一个 SQLite 数据库,并从位于我的资产文件夹中的文本文件中读取。 Here is my code:这是我的代码:

package com.example.kingmarkmcc.universe;

import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
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.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class MainActivity extends AppCompatActivity {

private Button simulator;
private Button helper;
private Button settings;
private Button milkyway;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    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();
        }
    });

    View.OnClickListener listener = new View.OnClickListener() {
        public void onClick(View v) {
            if (v == simulator) {
                Intent intent = new Intent(MainActivity.this, Simulator.class);
                startActivity(intent);
            } else if (v == helper) {
                Intent intent = new Intent(MainActivity.this, HelpOptions.class);
                startActivity(intent);
            } else if (v == settings) {
                Intent intent = new Intent(MainActivity.this, Settings.class);
                startActivity(intent);
            } else {
                Intent intent = new Intent(MainActivity.this, MilkyWay.class);
                startActivity(intent);
            }
        }
    };

    simulator = (Button) findViewById(R.id.buttonr1b1);
    simulator.setOnClickListener(listener);

    helper = (Button) findViewById(R.id.buttonr1b2);
    helper.setOnClickListener(listener);

    settings = (Button) findViewById(R.id.buttonr2b1);
    settings.setOnClickListener(listener);

    milkyway = (Button) findViewById(R.id.buttonr2b2);
    milkyway.setOnClickListener(listener);
}

@Override
protected void onStart()
{
    super.onStart();
    MainActivity myMain = new MainActivity();
    myMain.createDB();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.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();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
private void createDB(){

    SQLiteDatabase db= null;
    final String dbName = "starDB";
    final String tableName = "starTable";
    String[] rowRead;
    String line;

    try {
        InputStream input;
        input = getAssets().open("refinedData.txt");
        InputStreamReader inputReader = new InputStreamReader(input);
        BufferedReader bufferReader = new BufferedReader(inputReader);
        //Retrieve or create DataBase
        db = this.openOrCreateDatabase(dbName, MODE_PRIVATE, null);
        //Creating table
        db.execSQL("CREATE TABLE IF NOT EXISTS "
                + tableName
                + " (id INTEGER, proper TEXT, dist INTEGER , absmag INTEGER , spect TEXT , ci INTEGER , x INTEGER , y INTEGER , z INTEGER , vx INTEGER , vy INTEGER , vz INTEGER);");
        while((line = bufferReader.readLine())!= null) {
            rowRead = line.split(",");
            // Put data into table
            db.execSQL("INSERT INTO "
                    + tableName
                    + " (id, proper, dist, absmag, spect, ci, x, y, z, vx, vy, vz)"
                    + " VALUES (" + rowRead[0] + "," + rowRead[1] + "," + rowRead[2] + "," + rowRead[3] + "," + rowRead[4] + "," + rowRead[5] + "," + rowRead[6] + "," + rowRead[7] + "," + rowRead[8] + "," + rowRead[9] + "," + rowRead[10] + "," + rowRead[11] + ");");
        }
        bufferReader.close();

        Cursor c = db.rawQuery("SELECT * FROM " + tableName, null);

        int Column1 = c.getColumnIndex("id");
        int Column2 = c.getColumnIndex("x");

        c.moveToFirst();

        int id = c.getInt(Column1);
        int x = c.getInt(Column2);

        System.out.println(id);
        System.out.println(x);

        Toast.makeText(MainActivity.this, "End", Toast.LENGTH_LONG).show();

    }
    catch(Exception e) {
        Log.e("Error", "Error", e);}

    finally {
        if (db != null)
            db.close();
    }
}

This is the error that I am receiving:这是我收到的错误:

02-04 17:41:28.973 27362-27362/com.example.kingmarkmcc.universe D/AndroidRuntime: Shutting down VM
02-04 17:41:28.974 27362-27362/com.example.kingmarkmcc.universe E/AndroidRuntime: FATAL EXCEPTION: main
      Process: com.example.kingmarkmcc.universe, PID: 27362
      java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.kingmarkmcc.universe/com.example.kingmarkmcc.universe.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2362)
          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2424)
          at android.app.ActivityThread.access$900(ActivityThread.java:155)
          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1323)
          at android.os.Handler.dispatchMessage(Handler.java:102)
          at android.os.Looper.loop(Looper.java:139)
          at android.app.ActivityThread.main(ActivityThread.java:5298)
          at java.lang.reflect.Method.invoke(Native Method)
          at java.lang.reflect.Method.invoke(Method.java:372)
          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:950)
          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745)
       Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
          at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:106)
          at com.example.kingmarkmcc.universe.MainActivity.createDB(MainActivity.java:114)
          at com.example.kingmarkmcc.universe.MainActivity.onStart(MainActivity.java:83)
          at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1236)
          at android.app.Activity.performStart(Activity.java:6088)
          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2424) 
          at android.app.ActivityThread.access$900(ActivityThread.java:155) 
          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1323) 
          at android.os.Handler.dispatchMessage(Handler.java:102) 
          at android.os.Looper.loop(Looper.java:139) 
          at android.app.ActivityThread.main(ActivityThread.java:5298) 
          at java.lang.reflect.Method.invoke(Native Method) 
          at java.lang.reflect.Method.invoke(Method.java:372) 
          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:950) 
          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:745) 
02-04 17:41:28.977 27362-27362/com.example.kingmarkmcc.universe D/AppTracker: App Event: crash

I have tried to correct this error but cannot seem to figure out the problem!我试图纠正这个错误,但似乎无法找出问题所在! Any help would be much appreciated任何帮助将非常感激

Your immediate problem is this:您当前的问题是:

MainActivity myMain = new MainActivity();

Never create your own instances of activities this way.切勿以这种方式创建自己的活动实例。 For starters, they do not work, as you are seeing.首先,正如您所见,它们不起作用。 Besides, you are in an instance of MainActivity .此外,您MainActivity一个实例中。 You do not need a second one.你不需要第二个。 Just call createDB() .只需调用createDB()

Also, you are performing a lot of disk I/O on the main application thread.此外,您正在主应用程序线程上执行大量磁盘 I/O。 Your UI will be frozen for quite some time as a result.因此,您的用户界面将被冻结很长一段时间。 Do not do this.不要这样做。 Please move significant disk I/O to a background thread.请将重要的磁盘 I/O 移动到后台线程。

Note that it would be faster for your user, and simpler for you as a developer, to use SQLiteAssetHelper , to package a prepared database in your app, rather than do a bunch of SQL statements to accomplish the same thing.请注意,使用SQLiteAssetHelper将准备好的数据库打包到您的应用程序中,而不是执行一堆 SQL 语句来完成相同的事情,这对您的用户来说会更快,对您作为开发人员来说也更简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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