2016-02-04 167 views
-1

我最近啓動了一個新項目,此刻我試圖從主活動中創建SQLite數據庫,並從位於我的資源文件夾中的文本文件中讀取。這裏是我的代碼:從資源文件夾中獲取資源時出錯

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 

我試圖糾正這一錯誤,但似乎無法弄清楚的問題!任何幫助,將不勝感激

回答

0

你眼前的問題是這樣的:

MainActivity myMain = new MainActivity(); 

從不創建活動,這樣你自己的實例。對於初學者,他們不工作,正如你所看到的。此外,你在一個MainActivity的實例。你不需要第二個。只需撥打createDB()即可。

此外,您正在主應用程序線程上執行大量磁盤I/O。因此,您的用戶界面將會凍結一段時間。不要這樣做。請將重要的磁盤I/O移至後臺線程。

請注意,對於您的用戶而言,開發人員可以更快地將use SQLiteAssetHelper打包到您的應用程序中,而不是爲了完成同樣的任務而執行一堆SQL語句。