从RecyclerView中的SQLite中检索数据

时间:2015-02-02 12:30:30

标签: java android xml

在通过recyclerView从SQLite显示片段中的数据时遇到问题。当我点击showfragment按钮它崩溃并显示“不幸的应用程序停止”。它有6个java类和4个xml 我在下面给出了我的代码

DbHelperAdapter.java

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class DbHelperAdapter{

DbHelper helper;
public DbHelperAdapter(Context context){
    helper=new DbHelper(context);
}

public long insetData(String name,String password){
    SQLiteDatabase db=helper.getWritableDatabase();
    ContentValues contentValues=new ContentValues();
    contentValues.put(DbHelper.NAME,name);
    contentValues.put(DbHelper.PASSWORD,password);
    long id=db.insert(DbHelper.TABLE_NAME,null,contentValues);
    db.close();
    return id;
}
public String getAllData(){
    SQLiteDatabase db= helper.getWritableDatabase();
    String[] columns={DbHelper.UID,DbHelper.NAME,DbHelper.PASSWORD};
    Cursor cursor=db.query(DbHelper.TABLE_NAME, columns, null, null, null, null, null);
    StringBuffer buffer = new StringBuffer();
    while (cursor.moveToNext()){
        int cid=cursor.getInt(cursor.getColumnIndex(DbHelper.UID));
        String name = cursor.getString(cursor.getColumnIndex(DbHelper.NAME));
        String pass = cursor.getString(cursor.getColumnIndex(DbHelper.PASSWORD));
        buffer.append(cid+" "+name+" "+pass+"\n");

    }
    return buffer.toString();
}

public List<Information> getAllData_a(){
    SQLiteDatabase db= helper.getWritableDatabase();
    String[] columns={DbHelper.UID,DbHelper.NAME,DbHelper.PASSWORD};
    Cursor cursor=db.query(DbHelper.TABLE_NAME, columns, null, null, null, null, null);
    List<Information> data=new ArrayList<>();

    while (cursor.moveToNext()){
        int cid=cursor.getInt(cursor.getColumnIndex(DbHelper.UID));
        String name = cursor.getString(cursor.getColumnIndex(DbHelper.NAME));
        String pass = cursor.getString(cursor.getColumnIndex(DbHelper.PASSWORD));
        Information current = new Information();
        current.u_id=cid;
        current.user=name;
        current.pass=pass;
        data.add(current);
    }
    return data;

}

public String getData(String name){
    SQLiteDatabase db= helper.getWritableDatabase();
    String[] columns={DbHelper.NAME,DbHelper.PASSWORD};
    Cursor cursor=db.query(DbHelper.TABLE_NAME, columns, DbHelper.NAME+" = '"+name+"' ", null, null, null, null);
    StringBuffer buffer = new StringBuffer();
    while (cursor.moveToNext()){
        String PersonName = cursor.getString(cursor.getColumnIndex(DbHelper.NAME));
        String pass = cursor.getString(cursor.getColumnIndex(DbHelper.PASSWORD));
        buffer.append(PersonName+" "+pass+"\n");
    }
    return buffer.toString();
}

static class DbHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "demo";
    private static final String TABLE_NAME = "tbl_demo";
    private static final int VERSION_NAME=3;
    private static final String UID="_id";
    private static final String NAME="name";
    private static final String PASSWORD="Password";
    private static final String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+UID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+NAME+" VARCHAR(255),"+PASSWORD+" VARCHAR(255));";
    private static final String DROP_TABLE="DROP TABLE IF EXISTS "+TABLE_NAME+"";
    private Context context;

    public DbHelper(Context context){
        super(context,DATABASE_NAME,null,VERSION_NAME);
        this.context=context;
        Message.message(context, "constructorCalled");
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        try {
            db.execSQL(CREATE_TABLE);
            Message.message(context, "onCreateCalled");
        }catch (android.database.SQLException e){
            Message.message(context, ""+e);
        }

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        try {
            Message.message(context, "onUpgradeCalled");
            db.execSQL(DROP_TABLE);
            onCreate(db);
        } catch (android.database.SQLException e) {
            Message.message(context, ""+e);
        }
    }
}
}

Information.java

public class Information {
int u_id;
String user;
String pass;}

MainActivity.java

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.support.v4.app.Fragment;


public class MainActivity extends ActionBarActivity {

DbHelperAdapter dbHelperAdapter;
EditText userName;
EditText password;
EditText selectionName;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    dbHelperAdapter = new DbHelperAdapter(this);

    userName= (EditText) findViewById(R.id.username);
    password= (EditText) findViewById(R.id.password);
    selectionName= (EditText) findViewById(R.id.selection_name);
}

public void addUser(View view){
    String user = userName.getText().toString();
    String pass = password.getText().toString();
    long id = dbHelperAdapter.insetData(user,pass);
    if(id<0){
        Message.message(this,"Unsuccessful");
    }
    else {
        Message.message(this,"Successfully insert A Row");
    }
}

public void getTheFragment(View view){
    Intent i= new Intent(this,MainActivity2.class);
    startActivity(i);
}

public void viewDetails(View view){
    String data=dbHelperAdapter.getAllData();
    Message.message(this,data);
}
public void getDataBySelection(View view){
    String name = selectionName.getText().toString();
    String selections=dbHelperAdapter.getData(name);
    Message.message(this,selections);
}

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

MainActivity2.java

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;


public class MainActivity2 extends ActionBarActivity {

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

    ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
    pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
}

private class MyPagerAdapter extends FragmentPagerAdapter {

    public MyPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int pos) {
        return new MyFragment();
    }

    @Override
    public int getCount() {
        return 1;
    }
}}

Myfragment.java

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class MyFragment extends Fragment {

RecyclerView recyclerView;
RecyclerViewAdapter adapter;
DbHelperAdapter dbHelperAdapter;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View layout=inflater.inflate(R.layout.fragment_new, container, false);
    recyclerView = (RecyclerView) layout.findViewById(R.id.list);
    adapter = new RecyclerViewAdapter(getActivity(),dbHelperAdapter.getAllData_a());
    recyclerView.setAdapter(adapter);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    return layout;
}}

RecyclerViewAdapter.java

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.Collections;
import java.util.List;

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {

private LayoutInflater inflater;
List<Information> data= Collections.emptyList();

public RecyclerViewAdapter(Context context, List<Information> data){
     inflater = LayoutInflater.from(context);
     this.data =data;
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view=inflater.inflate(R.layout.custom_raw,parent,false);
    MyViewHolder holder=new MyViewHolder(view);
    return holder;
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    Information current = data.get(position);
    holder.UID.setText(current.u_id);
    holder.USER.setText(current.user);
    holder.PASS.setText(current.pass);
}

@Override
public int getItemCount() {
    return data.size();
}

class MyViewHolder extends RecyclerView.ViewHolder {

    TextView UID;
    TextView USER;
    TextView PASS;

    public MyViewHolder(View itemView) {
        super(itemView);
        UID= (TextView) itemView.findViewById(R.id.u_id);
        USER = (TextView) itemView.findViewById(R.id.user);
        PASS = (TextView) itemView.findViewById(R.id.pass);
    }
}}

activity_main.xml中

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity"
    android:orientation="vertical">
<EditText
    android:id="@+id/username"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    />

<EditText
    android:id="@+id/password"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/editText"
     />

<Button
    android:id="@+id/button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/editText2"
    android:onClick="addUser"
    android:text="@string/add_user" />

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:onClick="viewDetails"
    android:text="View Details"
    android:id="@+id/view_details_btn"
    android:layout_gravity="center_horizontal" />

<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/selection_name"
    android:layout_gravity="center_horizontal" />

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="GetSelectedData"
    android:onClick="getDataBySelection"
    android:id="@+id/getDataBySelection" />

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Show Fragment"
    android:onClick="getTheFragment"
    android:id="@+id/show_fragment"
    />

</LinearLayout>

activity_main_activity2.xml

<android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/viewPager"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    />

custom_raw.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/u_id"
        android:layout_gravity="center"
        android:text="UID"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/user"
        android:layout_gravity="center"
        android:text="NAME"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/pass"
        android:layout_gravity="center"
        android:text="PASSWORD"/>

</LinearLayout>

fagment_new.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </android.support.v7.widget.RecyclerView>

</RelativeLayout>

google drive link:https://drive.google.com/folderview?id=0B0uBfXsWeMlgX0U5OE8tREhxQkk&usp=sharing

logcat错误:

02-02 22:15:27.455  10562-10562/com.maticoders.databasetest E/AndroidRuntime? FATAL EXCEPTION: main
    java.lang.NullPointerException
            at com.maticoders.databasetest.MyFragment.onCreateView(MyFragment.java:29)
            at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1126)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1489)
            at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:486)
            at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:1073)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:919)
            at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1441)
            at android.view.View.measure(View.java:15635)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4919)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
            at android.view.View.measure(View.java:15635)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4919)
            at android.support.v7.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:453)
            at android.view.View.measure(View.java:15635)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4919)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
            at android.view.View.measure(View.java:15635)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4919)
            at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1411)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:698)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
            at android.view.View.measure(View.java:15635)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4919)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
            at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2200)
            at android.view.View.measure(View.java:15635)
            at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2165)
            at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1249)
            at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1443)
            at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1139)
            at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4872)
            at android.view.Choreographer$CallbackRecord.run(Choreographer.java:776)
            at android.view.Choreographer.doCallbacks(Choreographer.java:579)
            at android.view.Choreographer.doFrame(Choreographer.java:548)
            at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:762)
            at android.os.Handler.handleCallback(Handler.java:800)
            at android.os.Handler.dispatchMessage(Handler.java:100)
            at android.os.Looper.loop(Looper.java:194)
            at android.app.ActivityThread.main(ActivityThread.java:5371)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
            at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:1)

错误发生在我的RecyclerViewAdapter类中 我没有传递上下文并在textView中传递一个整数 这是我的RecylerViewAdapter类

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.Collections;
import java.util.List;

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {

    private Context context;
    private LayoutInflater inflater;
    List<Information> data= Collections.emptyList();

    public RecyclerViewAdapter(Context context, List<Information> data){
         this.context=context;
         inflater = LayoutInflater.from(context);
         this.data =data;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view=inflater.inflate(R.layout.custom_raw,parent,false);
        MyViewHolder holder=new MyViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        Information current = data.get(position);
        holder.UID.setText(String.valueOf(current.u_id));
        holder.USER.setText(current.user);
        holder.PASS.setText(current.pass);
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder {

        TextView UID;
        TextView USER;
        TextView PASS;

        public MyViewHolder(View itemView) {
            super(itemView);
            UID= (TextView) itemView.findViewById(R.id.u_id);
            USER = (TextView) itemView.findViewById(R.id.user);
            PASS = (TextView) itemView.findViewById(R.id.pass);
        }
    }
}