菜单搜索中的Java NullPointerexception而不是按钮主菜单中的Java NullPointerexception

时间:2017-02-26 05:26:56

标签: java android sqlite nullpointerexception database-connection

帮我解决这个问题。我仍然坚持这一个。我真的不明白怎么做。我是新学习Java,这是我第一次构建apk。 无法打开固定应用程序中的数据库。我有三个水龙头。主菜单, search1,search2 。标签搜索都没有工作(不幸的是app停止了)。但我可以在主菜单上解锁按钮。

当我在oncreate中调用initUi方法时。它没有用。主菜单和标签搜索中的我的按钮无法打开。

当我运行我的应用程序时,这是我的LogCat,而不是单击search1

02-26 12:16:50.141: E/AndroidRuntime(1090): FATAL EXCEPTION: main
02-26 12:16:50.141: E/AndroidRuntime(1090): Process: com.rdsj.land, PID: 1090
02-26 12:16:50.141: E/AndroidRuntime(1090): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rdsj.land/com.rdsj.land.keterangan}: java.lang.NullPointerException
02-26 12:16:50.141: E/AndroidRuntime(1090):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
02-26 12:16:50.141: E/AndroidRuntime(1090):     at android.app.ActivityThread.startActivityNow(ActivityThread.java:2035)
02-26 12:16:50.141: E/AndroidRuntime(1090):     at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:135)
02-26 12:16:50.141: E/AndroidRuntime(1090):     at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:347)
02-26 12:16:50.141: E/AndroidRuntime(1090):     at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:749)
02-26 12:16:50.141: E/AndroidRuntime(1090):     at android.widget.TabHost.setCurrentTab(TabHost.java:413)
02-26 12:16:50.141: E/AndroidRuntime(1090):     at android.widget.TabHost$2.onTabSelectionChanged(TabHost.java:154)
02-26 12:16:50.141: E/AndroidRuntime(1090):     at android.widget.TabWidget$TabClickListener.onClick(TabWidget.java:546)
02-26 12:16:50.141: E/AndroidRuntime(1090):     at android.view.View.performClick(View.java:4438)
02-26 12:16:50.141: E/AndroidRuntime(1090):     at android.view.View$PerformClick.run(View.java:18422)
02-26 12:16:50.141: E/AndroidRuntime(1090):     at android.os.Handler.handleCallback(Handler.java:733)
02-26 12:16:50.141: E/AndroidRuntime(1090):     at android.os.Handler.dispatchMessage(Handler.java:95)
02-26 12:16:50.141: E/AndroidRuntime(1090):     at android.os.Looper.loop(Looper.java:136)
02-26 12:16:50.141: E/AndroidRuntime(1090):     at android.app.ActivityThread.main(ActivityThread.java:5017)
02-26 12:16:50.141: E/AndroidRuntime(1090):     at java.lang.reflect.Method.invokeNative(Native Method)
02-26 12:16:50.141: E/AndroidRuntime(1090):     at java.lang.reflect.Method.invoke(Method.java:515)
02-26 12:16:50.141: E/AndroidRuntime(1090):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
02-26 12:16:50.141: E/AndroidRuntime(1090):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
02-26 12:16:50.141: E/AndroidRuntime(1090):     at dalvik.system.NativeStart.main(Native Method)
02-26 12:16:50.141: E/AndroidRuntime(1090): Caused by: java.lang.NullPointerException
02-26 12:16:50.141: E/AndroidRuntime(1090):     at com.rdsj.aircraft.keterangan.checkResult(keterangan.java:101)
02-26 12:16:50.141: E/AndroidRuntime(1090):     at com.rdsj.aircraft.keterangan.onCreate(keterangan.java:77)
02-26 12:16:50.141: E/AndroidRuntime(1090):     at android.app.Activity.performCreate(Activity.java:5231)
02-26 12:16:50.141: E/AndroidRuntime(1090):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
02-26 12:16:50.141: E/AndroidRuntime(1090):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
02-26 12:16:50.141: E/AndroidRuntime(1090):     ... 18 more

这是我的Keterangan.Java

package com.rdsj.land;

import android.app.Activity;
import android.app.AlertDialog;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.rdsj.land.R;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.util.Patterns;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

public class keterangan extends Activity implements TextToSpeech.OnInitListener {

    final static int  SEMUA  = 1;
    final static int  CARI = 2;
    final static int ROUNDLE = 3;
    final String[] dict_name = new String[] {"SEMUA","CARI", "ROUNDLE"};

    private int DICT;
    private String text;
    private SQLiteDatabase db = null;
    private Cursor catatan = null;
    private DBPesawat db_pesawat_helper;
    private TextToSpeech mTts;
    private int SpeechStatus;
    private float font_size;

    TextView title, content;
    Button speech, close;
    WebView pic;

    Handler handler = new Handler();
    Thread searching;

    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      /* Get Intent Parameter */
      this.getIntentParameter();

      /* Open Database File */
      db_pesawat_helper = new DBPesawat(this);
      try {
        db_pesawat_helper.openDataBase();
        db = db_pesawat_helper.getReadableDatabase();
      }catch(SQLException sqle){
            throw sqle;
        }


      /* UI Initialization */                       //null pointer in this line
      if (checkResult()) this.initUI();
    }

    private void getIntentParameter() {
        // TODO Auto-generated method stub
        Uri data = this.getIntent().getData();
        if (data!=null) {
            DICT = Integer.parseInt(data.getQueryParameter("dict"));
            text = data.getQueryParameter("text");
        } else {
            DICT = this.getIntent().getExtras().getInt("DICT", 1);
            text = this.getIntent().getExtras().getString("TEXT");
        }
    }

    private boolean checkResult() {
        // TODO Auto-generated method stub
        String catatan1;
        switch(DICT) {
            default:
            case SEMUA:
                catatan1 = "SELECT ringkasan FROM Main where lower(Type)=lower('"+text.replace("'", "''")+"') ";
                break;
            case CARI:
                catatan1 = "SELECT * FROM Cari where lower(Nama_Pesawat)=lower('"+text.replace("'", "''")+"')";   // And this line null pointer too
                break;
            case ROUNDLE:
                catatan1 = "SELECT * FROM Roundle where lower(Negara)=lower('"+text.replace("'", "''")+"')";      // This one too when I click on tab search Roundle
                break;
        }
        catatan = db.rawQuery(catatan1, null);
        if (!catatan.moveToFirst()) {
            Toast.makeText(this, "word `"+text+"` not found in "+dict_name[DICT-1]+" dictionary !", Toast.LENGTH_SHORT).show();
            this.finish();
            return false;
        } else return true;
    }

    private void initUI() {
        // TODO Auto-generated method stub
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.setContentView(R.layout.keterangan);
        this.getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
        mTts = new TextToSpeech(this,this);

        title = (TextView) findViewById(R.id.title);
        content = (TextView) findViewById(R.id.content);
        speech = (Button) findViewById(R.id.speech);
        close = (Button) findViewById(R.id.close);
        pic = (WebView) findViewById(R.id.tampil);


        /* Define event callback function */
        speech.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                if (SpeechStatus == TextToSpeech.LANG_MISSING_DATA || SpeechStatus == TextToSpeech.LANG_NOT_SUPPORTED)
                    installLanguage();
                else
                    mTts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
            }
        });

        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                keterangan.this.finish();
            }
        });
    }

    private boolean isValidUrl(String url) {
        Pattern p = Patterns.WEB_URL;
        Matcher m = p.matcher(url);
        if(m.matches())
            return true;
        else
        return false;
    }



    @Override
    public void onStart() {
        super.onStart();

        /* Get Preferences */
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        font_size = Float.parseFloat(prefs.getString("font_size", "18"));

        /* Display Result */
        title.setText(text);
        content.setTextSize(TypedValue.COMPLEX_UNIT_SP, font_size);
        switch(DICT){
        case  SEMUA : 
            pic.loadUrl("file:///android_asset/img/Q.jpg");
            content.setText(catatan.getString(0));
            content.setLinkTextColor(Color.rgb(0x44, 0x44, 0xBB));
            break;
        default :
            if(catatan.getString(3).equals("-")){
                pic.loadUrl("file:///android_asset/img/Q.jpg");
                pic.getSettings().setJavaScriptEnabled(true);
            }else{
                    pic.loadUrl(catatan.getString(3));              
                }


            content.setText("Catatan\t:\t"+catatan.getString(2));               
            content.setLinkTextColor(Color.rgb(0x44, 0x44, 0xBB));
            break;
        }

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.drawable.readermenu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
      float current_size = content.getTextSize();
      switch (item.getItemId()) {
      case R.id.zoomout:
          content.setTextSize(TypedValue.COMPLEX_UNIT_PX, current_size*(float)(1/1.2));
          break;
      case R.id.zoomin:
          content.setTextSize(TypedValue.COMPLEX_UNIT_PX, current_size*(float)1.2);
          break;
      default:
        return super.onOptionsItemSelected(item);
      }
      return true;
    }

    @Override
    public void onDestroy() {
        // Don't forget to shutdown!
        if (mTts != null) {
            mTts.stop();
            mTts.shutdown();
        }
        super.onDestroy();
    }

    /* Implements TextToSpeech.OnInitListener. */
    public void onInit(int status) {
        if (status == TextToSpeech.SUCCESS) {
            switch(DICT) {
                default:
                case SEMUA:
                case CARI:
                    SpeechStatus = mTts.setLanguage(Locale.ITALY);
                    break;
                case ROUNDLE:
                    SpeechStatus = mTts.setLanguage(Locale.ITALY);
                    break;
            }
            if (SpeechStatus == TextToSpeech.LANG_MISSING_DATA || SpeechStatus == TextToSpeech.LANG_NOT_SUPPORTED) {
                // Lanuage data is missing or the language is not supported.
                speech.setBackgroundResource(R.drawable.speech_disabled);
            } else {
                speech.setBackgroundResource(R.drawable.speech_button);
            }
        } else {
            speech.setBackgroundResource(R.drawable.speech_disabled);
            speech.setEnabled(false);
            speech.setClickable(false);
        }
    }

    /* Install speech language if not available */
    protected void installLanguage() {
        // TODO Auto-generated method stub
        new AlertDialog.Builder(this)
        .setMessage("This language is not available.\nDo you want to install ?")
        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                Intent installIntent = new Intent();
                installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                startActivity(installIntent);
            }
        })
        .setNegativeButton("No", null)
        .show();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }
}

此行中的空指针

  

77:if(checkResult())this.initUI();

     

101:catatan1 =" SELECT * FROM Cari,其中较低(Nama_Pesawat)=较低('" + text.replace("'",& #34;''&#34)+"')&#34 ;;中断;

这是我的主要活动:

package com.rdsj.land;

import com.rdsj.land.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TabHost;


public class MainActivity extends TabActivity {
    /** Called when the activity is first created. */
    private AlertDialog.Builder builder;
    private AlertDialog aboutDialog;
    final String[] tab_menu = {
            "Main Menu",
            "Cari",
            "Roundle"};


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

 // call database helper

        databasehelper bantuan = new databasehelper(MainActivity.this);

        try {
            bantuan.createDataBase();

    } catch (Exception e) {
        // 1000: handle exception

        // tell when error copy

    System.out.println("Copy Database gagal " + e.getMessage());
    }

    // tell when copy success
    System.out.println("Copy Database Success");

        Resources res = getResources(); // Resource object to get Drawables
        TabHost tabHost = getTabHost();  // The activity TabHost
        TabHost.TabSpec spec;  // Resusable TabSpec for each tab
        Intent intent;  // Reusable Intent for each tab

        // All
        intent = new Intent().setClass(this, rinci.class);
        intent.putExtra("DICT", 1);
        spec = tabHost.newTabSpec("all").setIndicator(tab_menu[0] , res.getDrawable(R.drawable.tab_style)).setContent(intent);
        tabHost.addTab(spec);

        // English to Indonesian
        intent = new Intent().setClass(this, keterangan.class);
        intent.putExtra("DICT", 2);
        spec = tabHost.newTabSpec("en2id").setIndicator(tab_menu[1], res.getDrawable(R.drawable.tab_style)).setContent(intent);
        tabHost.addTab(spec);

        // Indonesian to English
        intent = new Intent().setClass(this, keterangan.class);
        intent.putExtra("DICT", 3);
        spec = tabHost.newTabSpec("id2en").setIndicator(tab_menu[2], res.getDrawable(R.drawable.tab_style)).setContent(intent);
        tabHost.addTab(spec);

        // Select Default Tab
        tabHost.setCurrentTab(0);

        // Create About Dialog
        LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(R.layout.about, (ViewGroup) findViewById(R.id.layout_root));
        builder = new AlertDialog.Builder(this)
        .setView(layout)
        .setTitle("About")
        .setNeutralButton("OK", null);
        builder.setIcon(android.R.drawable.ic_dialog_info);
        aboutDialog = builder.create();
        }

        @Override
        public void onConfigurationChanged(Configuration newConfig) {
            super.onConfigurationChanged(newConfig);
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.drawable.mainmenu, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
          switch (item.getItemId()) {
          case R.id.setting:
              Intent settingsActivity = new Intent(this.getBaseContext(), Setting.class);
              startActivity(settingsActivity);
              break;
          case R.id.about:
              aboutDialog.show();
              break;
          case R.id.exit:
              MainActivity.this.finish();
              break;
          default:
            return super.onOptionsItemSelected(item);
          }
          return true;  

    }
}

编辑: 我忘了我有databasehelper

package com.rdsj.land;


import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;

import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

public class databasehelper extends SQLiteOpenHelper{

    // Direktori default 
    String DB_PATH =null;

    // Variabel Nama Database 
    // Hanya mengganti di bagian ini saja
    private static String DB_NAME = "PESAWAT.sqlite";

    // Variabel SQLiteDatabase
    private SQLiteDatabase myDataBase; 

    // Variabel Context Untuk menggabungkan Dengan Sctivity
    private final Context myContext;

    /**
     * Constructor
     * Untuk Mengakses Asset Pada Project 
     * @param context
     */
    public databasehelper(Context context) {

        super(context, DB_NAME, null, 1);
        this.myContext = context;
        DB_PATH="/data/data/"+context.getPackageName()+"/"+"databases/";
    }   

  /**
     * Membuat database kosong pada system dan menulis kembali sesuai dengan 
     * database kita yang berada pada Asset
     * */
    public void createDataBase() throws IOException{

        boolean dbExist = checkDataBase();

        if(dbExist){
            //Tidak mengerjakan Jika database Sudah Ada
        }else{

            // Memanggil Method dan Database Yang Telah Di Buat Di Direktori Default System
            // Dari Method ini kita Dapat Menulis Database Kosong Dengan Database Kamu Dari Aplikasi 

            this.getReadableDatabase();

            try {

                close(); 
                openDataBase(); 
                copyDataBase();


            } catch (IOException e) {

                throw new Error("Error copying database");

            }
        }

    }

    /**
     * Cek jika database Tersedia untuk proses
     * apakah Sudah Ada atau Belum
     */
    private boolean checkDataBase(){

        SQLiteDatabase checkDB = null;

        try{
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

        }catch(SQLiteException e){

            //Database Belum Tersedia

        }

        if(checkDB != null){

            checkDB.close();

        }

        return checkDB != null ? true : false;
    }

    /**
     * Copy Database Dari Asset Ke Database Kosong Yang Telah Dibuat.
     * */
    private void copyDataBase() throws IOException{

        // Membuka Database Untuk proses Input Stream
        InputStream myInput = myContext.getAssets().open(DB_NAME);

        // Alamat untuk Membuat Database Kosong
        String outFileName = DB_PATH + DB_NAME;

        // Membuka Database Kosong Sebagai Output Stream untuk Copy 
        OutputStream myOutput = new FileOutputStream(outFileName);

        //Proses transfer byte dari input stream ke output stream
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer))>0){
            myOutput.write(buffer, 0, length);
        }

        //Tutup Stream
        myOutput.flush();
        myOutput.close();
        myInput.close();

    }

    public void openDataBase() throws SQLException{

        //Open Database
        String myPath = DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

    }

    @Override
    public synchronized void close() {

            if(myDataBase != null)
                myDataBase.close();

            super.close();

    }



    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

}

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

setContentView置于与onCreate方法相关联的onCreate内,并先被调用。

解决方式如下:

@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.keterangan); //here

  /* Get Intent Parameter */
  this.getIntentParameter();
     ......
          .......

从您的方法中删除:

private void initUI() {
    // TODO Auto-generated method stub
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);

    //removed from here

    this.getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    mTts = new TextToSpeech(this,this);