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

时间:2016-02-04 17:52:33

标签: java android sqlite android-studio

我最近开始了一个新项目,目前我正在尝试从主活动中创建一个SQLite数据库,并从我的assests文件夹中的文本文件中读取。这是我的代码:

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();
    }
}

这是我收到的错误:

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

我试图纠正这个错误,但似乎无法弄清楚问题!任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

你当前的问题是:

MainActivity myMain = new MainActivity();

永远不要以这种方式创建自己的活动实例。对于初学者来说,正如您所看到的那样,它们无法正常工作。此外,您 in MainActivity的一个实例。你不需要第二个。只需致电createDB()

此外,您正在主应用程序线程上执行大量磁盘I / O.因此,您的UI将被冻结一段时间。不要这样做。请将重要的磁盘I / O移动到后台线程。

请注意,对于您的用户而言,use SQLiteAssetHelper在您的应用程序中打包准备好的数据库,而不是做一堆SQL语句来完成同样的事情,对您来说会更快。