在list-android中搜索并检索结果

时间:2015-04-21 12:12:31

标签: java android sqlite android-listview android-sqlite

我正在尝试从sqlite数据库中搜索并检索列表视图中的结果。当我尝试搜索时,该应用程序关闭。

Logcat

 04-20 11:50:56.550    2297-2297/com.example.asus.myapplication3.app
 E/AndroidRuntime﹕ FATAL EXCEPTION: main
     Process: com.example.asus.myapplication3.app, PID: 2297
     java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase
 com.example.asus.myapplication3.app.dbtry$DatabaseHelper.getReadableDatabase()'
 on a null object reference
             at com.example.asus.myapplication3.app.searchActivity$1.onClick(searchActivity.java:62)
             at android.view.View.performClick(View.java:4756)
             at android.view.View$PerformClick.run(View.java:19749)
             at android.os.Handler.handleCallback(Handler.java:739)
             at android.os.Handler.dispatchMessage(Handler.java:95)
             at android.os.Looper.loop(Looper.java:135)
             at android.app.ActivityThread.main(ActivityThread.java:5221)
             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:899)
             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

代码

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import java.net.ContentHandler;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


public class ListAdapter extends ArrayAdapter {
    List list= new ArrayList();

    static class layoutHandler
    {


        TextView nameText;

    }
    public ListAdapter(Context context, int resource)
    {
        super(context, resource);
    }
    @Override
    public  void add (Object object){

        super.add(object);
        list.add(object);
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position)

    {
        return list.get(position);
    }

    @Override
    // retern each row of data
    public View getView(int position, View convertView, ViewGroup parent) {
        View row = convertView;
        layoutHandler layouthandler;
        if (row==null){
            LayoutInflater layoutInflater =(LayoutInflater)this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row=layoutInflater.inflate(R.layout.result,parent,false);
        //    row=layoutInflater.inflate(R.layout.listrow,parent,false);

            layouthandler=new layoutHandler();
            layouthandler.nameText=(TextView)row.findViewById(R.id.nameText);
                    row.setTag(layouthandler);

        }
        else
        {
            layouthandler =(layoutHandler) row.getTag();


        }
// return each abject from the list
        dataProvider provider=(dataProvider)this.getItem(position);
        //assaien each row of data
        layouthandler.nameText.setText(provider.getName());
        return row;
    }
}



public class dataProvider {
    private String name;


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }


    public dataProvider(String name) {


        this.name = name;

    }
}


import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;


public class searchActivity extends Activity {

        EditText rname;
        TextView result;
        Button search;
          dbtry db;
        ListView data;
        ListAdapter listAdapter;
        String search_name;
        SQLiteDatabase sqLiteDatabase;
        dbtry.DatabaseHelper dbhlper;

        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.search);

            search = (Button) findViewById(R.id.search);
            rname = (EditText) findViewById(R.id.rname);
            data = (ListView) findViewById(R.id.data);


            search.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                  //  setContentView(R.layout.result);

                    search_name = rname.getText().toString();

                    //db = new dbtry(getBaseContext());
                   sqLiteDatabase= dbhlper.getReadableDatabase();
                   Log.e("the app search ","dbhlper");


                       db.open();
                    Cursor d = db.returndata(search_name, sqLiteDatabase);
                    Log.e("the app search ","yah!");
                    listAdapter = new ListAdapter(getApplicationContext(), R.layout.listrow);
                    data.setAdapter(listAdapter);
                    data.setVisibility(View.GONE);
                    if (d.moveToFirst()) {
                        do {
                            String result_search;

                            result_search = d.getString(0);

                            //adding data to adapter
                            dataProvider provider = new dataProvider(result_search);
                            listAdapter.add(provider);
                        Log.e("the app search ","good");
                        } while (d.moveToNext());
                    }
                   // startActivity( new Intent(searchActivity.this, resultActivity.class));

                }

            }); }}


package com.example.asus.myapplication3.app;


import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.sql.SQLException;
public class dbtry {
    public static  int    _id;
    public static final String ecapp_col_name = "name";
    public static final String ecapp_col_discrption = "discrption";
    public static final String ecapp_col_ingredant = "ingredant";
  //  public static final String ecapp_image = "image";
    public static final String ecapp_col_Optional_ingredant = "Optional_ingredant";
    public static final String TABLE_NAME1 = "recipe";
    public static final String TABLE_NAME2 = "ingredant";
    public static final String DATABASE_NAME="ecapp";
    public static final int DATABASE_VERSION=1;
    public static final String DATABASE_create1 = "create"+ TABLE_NAME1+ "("+_id +"int not null auto_increment,"+ecapp_col_name+" text  UNIQUE,"+ecapp_col_discrption +"text+ );";
    public static final String DATABASE_create2 = "create "+TABLE_NAME2+ "("+ ecapp_col_ingredant+"text ,"+ecapp_col_Optional_ingredant+"text ,"+_id+ "number );";

    DatabaseHelper dbh;
    Context con;
SQLiteDatabase db2;
    public dbtry(Context con)
    {
   this.con = con;
   dbh = new DatabaseHelper(con);
}

   public static class DatabaseHelper extends SQLiteOpenHelper {


   public  DatabaseHelper (Context con)
{
    super(con,DATABASE_NAME,null,DATABASE_VERSION);
}
    @Override
    public void onCreate(SQLiteDatabase db) {

try {
    db.execSQL(DATABASE_create1);
    db.execSQL(DATABASE_create2);
    Log.d("db created ", "table2");
}
catch (Exception e) {
    e.printStackTrace();
    Log.e("db not created ", "bad");


}

    }

       @Override
       public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
           db.execSQL("DROP TABLE IF EXISTS ecapp");
           onCreate(db);

       }

   }
    public dbtry open()
    {
        db2= dbh.getWritableDatabase();
        return this;
    }



    public void close()
    {
        dbh.close();
    }




    public void insertData(String name, String ingredant, String discrption) {

        ContentValues content = new ContentValues();

        content.put(ecapp_col_name, name);
        Log.e("db created ", "good");

        content.put(ecapp_col_ingredant, ingredant);
        Log.e("db created ", "good");

        content.put(ecapp_col_discrption, discrption);
        Log.e("db created ", "good");

         db2.insert("ecapp", null, content);
        Log.e("db created ", "good");


    }
    //retrieve
    public Cursor returndata(String sname, SQLiteDatabase sqldb)

    {
       sqldb = dbh.getReadableDatabase();
        String selection, selectionArg;
        Cursor query;
        String[] projection = {ecapp_col_name};
        String[] where = {ecapp_col_name};

       query = sqldb.query(TABLE_NAME1, projection,sname,null, null, null, null);
       // query = sqldb.query( "select"+ecapp_col_name+ "form" +TABLE_NAME1+"where "+ecapp_col_name+"="+sname+;)
       Log.e( "get all data:", "query");
        return query;


    }


}

1 个答案:

答案 0 :(得分:0)

在项目的searchActivity中,在初始化sqLiteDatabase= dbhlper.getReadableDatabase();之前在search.setOnClickListener中添加这些行db = new dbtry(searchActivity.this);以避免NullPointerException。

同时对此行sqLiteDatabase= dbhlper.getReadableDatabase();发表评论,因为您已在SQLiteDatabase db2;方法中使用open()作为

public dbtry open()
{
    db2= dbh.getWritableDatabase();
    return this;
}

所以不需要dbHelper& searchActivity类中的sqliteDatabase,只需调用db.open()即可。如果您想从数据库中读取,请创建另一个方法read(),类似于dbtry类中的open()方法

public dbtry read()
{
db2= dbh.getReadableDatabase();
return this;
}
  

用法:db.read();只有在初始化db。

之后才能在searchActivity中调用它

快乐编码.. !!