如何在片段视图上的列表视图上显示sqlite数据库内容?

时间:2018-09-23 10:25:55

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

我目前正在应用程序的管理部分。我有一个数据库,我想在ListView上的片段上显示数据。代码中没有错误,但是,当我打开那个特定的fragment(UserFragment)时,它将注销/返回上一个活动。谁能告诉我如何实现这一目标?下面是我到目前为止尝试过的,

UserFragment.java

这是我的UserFragment(当我在应用程序中打开此用户片段时,它将回到上一个活动)

import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;

public class UserFragment extends Fragment {

  dataconnect myDB;
  ArrayList < String > items_user;
  ArrayAdapter adapter;
  ListView userList;

  @Nullable
  @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.fragment_user, container, false);

    items_user = new ArrayList < > ();
    userList = (ListView) view.findViewById(R.id.listView_users);

    viewData();

    return view;
  }

  private void viewData() {
    Cursor cursor = myDB.viewData();

    if (cursor.getCount() == 0) {
      Toast.makeText(getActivity(), "No data to show", Toast.LENGTH_SHORT).show();
    } else {
      while (cursor.moveToNext()) {
        items_user.add(cursor.getString(1));
      }
      adapter = new ArrayAdapter < > (getActivity(), android.R.layout.simple_list_item_1, items_user);
      userList.setAdapter(adapter);
    }
  }
}

这是我的dataconnect.java(DatabaseHelper)

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

public class dataconnect extends SQLiteOpenHelper {
    public static final int DATABASE_VERSION = 1;
    public static final String DATABASE_NAME = "db_jeepy.db";
    public static final String TABLE_NAME = "tbl_register";
    public static final String COLUMN_ID = "UID";
    public static final String COLUMN_FNAME = "FNAME";
    public static final String COLUMN_EMAIL = "EMAIL";
    public static final String COLUMN_UNAME = "UNAME";
    public static final String COLUMN_PWORD = "PWORD";

    SQLiteDatabase sqLiteDatabase;

    public static final String TABLE_CREATE = "create table tbl_register (UID integer primary key not null auto_increment, FNAME text not null, EMAIL text not null, UNAME text not null, PWORD text not null )";


    public dataconnect(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        sqLiteDatabase.execSQL(TABLE_CREATE);
        this.sqLiteDatabase = sqLiteDatabase;
    }

    public String searchPass(String uname) {
        sqLiteDatabase = this.getReadableDatabase();
        String query = "select UNAME, PWORD from " + TABLE_NAME;
        Cursor cursor = sqLiteDatabase.rawQuery(query, null);
        String a, b;
        b = "not found";
        if (cursor.moveToFirst()) {
            do {
                a = cursor.getString(0);
                b = cursor.getString(1);

                if (a.equals(uname)) {
                    b = cursor.getString(1);
                    break;
                }
            }
            while (cursor.moveToNext());
        }

        return b;
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        String query = "DROP TABLE IF EXISTS " + TABLE_NAME;
        sqLiteDatabase.execSQL(query);
        this.onCreate(sqLiteDatabase);
    }

    public void insertContact(Contact c) {
        sqLiteDatabase = this.getWritableDatabase();
        ContentValues values = new ContentValues();

        String query = "select * from " + TABLE_NAME;
        Cursor cursor = sqLiteDatabase.rawQuery(query, null);
        int count = cursor.getCount();

        values.put(COLUMN_ID, count);
        values.put(COLUMN_FNAME, c.getFname());
        values.put(COLUMN_EMAIL, c.getEmail());
        values.put(COLUMN_UNAME, c.getUname());
        values.put(COLUMN_PWORD, c.getPword());

        sqLiteDatabase.insert(TABLE_NAME, null, values);
        sqLiteDatabase.close();
    }


    public boolean insertData(String fname, String email, String uname, String pword) {
        SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
        ContentValues values = new ContentValues();

        values.put(COLUMN_FNAME, fname);
        values.put(COLUMN_EMAIL, email);
        values.put(COLUMN_UNAME, uname);
        values.put(COLUMN_PWORD, pword);

        long result = sqLiteDatabase.insert(TABLE_NAME, null, values);
        if (result == -1)
            return false;
        else
            return true;
    }

    public Cursor viewData (){
        SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
        String query = "Select * from "+TABLE_NAME;
        Cursor cursor = sqLiteDatabase.rawQuery(query,null);
        return cursor;
    }

}

adminopen.java

这是我放置/打开UserFragment的活动

import android.content.DialogInterface;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;

public class adminopen extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
  private DrawerLayout drawer;

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

    drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer,
      R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    if (savedInstanceState == null) {
      getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
        new JeepsFragment()).commit();
      navigationView.setCheckedItem(R.id.nav_jeeps);
    }
  }

  @Override
  public void onBackPressed() {
    if (drawer.isDrawerOpen(GravityCompat.START)) {
      drawer.closeDrawer(GravityCompat.START);
    } else {
      AlertDialog.Builder builder = new AlertDialog.Builder(this);
      builder.setCancelable(false);
      builder.setMessage("Do you want to logout?");

      builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
          Intent a = new Intent(adminopen.this, MainActivity.class);
          startActivity(a);
        }
      });

      builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
          dialogInterface.cancel();
        }

      });

      AlertDialog dialog = builder.create();
      dialog.show();
    }
  }

  @Override
  public boolean onNavigationItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()) {
      case R.id.nav_users:
        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
          new UserFragment()).commit();
        break;
      case R.id.nav_jeeps:
        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
          new JeepsFragment()).commit();
        break;
    }

    drawer.closeDrawer(GravityCompat.START);
    return true;
  }
}

1 个答案:

答案 0 :(得分:0)

我已经修复了它^。^

我只是添加

mContext =getActivity(); myDB = new dataconnect(mContext);

在我片段的OnCreateView中。

所以代码变成这样。

import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;

public class UserFragment extends Fragment {

  dataconnect myDB;
  ArrayList < String > items_user;
  ArrayAdapter adapter;
  ListView userList;
  private Context mContext;

  @Nullable
  @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.fragment_user, container, false);

    mContext = getActivity();
    myDB = new dataconnect(mContext);

    items_user = new ArrayList < > ();
    userList = (ListView) view.findViewById(R.id.listView_users);

    viewData();

    userList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
      @Override
      public void onItemClick(AdapterView << ? > adapterView, View view, int i, long l) {
        String text = userList.getItemAtPosition(i).toString();
        Toast.makeText(getContext(), "" + text, Toast.LENGTH_SHORT).show();
      }
    });

    return view;
  }

  private void viewData() {
    Cursor cursor = myDB.viewData();

    if (cursor.getCount() == 0) {
      Toast.makeText(getActivity(), "No data to show", Toast.LENGTH_SHORT).show();
    } else {
      while (cursor.moveToNext()) {
        items_user.add(cursor.getString(1));
      }
      adapter = new ArrayAdapter < > (getActivity(), android.R.layout.simple_list_item_1, items_user);
      userList.setAdapter(adapter);
    }
  }

}