整个项目最初使用的代码完全相同,我甚至将其恢复了一段时间,它没有显示&#34; android.database.CursorIndexOutOfBoundsException:请求索引0,大小为0& #34 ;.我很乐意寻求帮助来解决这个问题,因为我知道这很简单,因为它关于Cursor但我仍然无法解决这个问题。< / p>
相关守则如下:
DatabaseOperations.java 包m.rami.psucalculator;
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;
public class DatabaseOperations extends SQLiteOpenHelper {
public static final int database_version = 3;
public String CREATE_QUERY = "CREATE TABLE
"+TableData.TableInfo.TABLE_NAME+"("+TableData.TableInfo.USER_NAME+"
TEXT,"+TableData.TableInfo.USER_PASSWORD+" TEXT );";
public DatabaseOperations(Context context) {
super(context, TableData.TableInfo.DATABASE_NAME, null,
database_version);
Log.d("Database operations", "Database created");
// constructor stub
}
@Override
public void onCreate(SQLiteDatabase sdb) {
sdb.execSQL(CREATE_QUERY);
Log.d("Database operations","Table created");
// method stub
}
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// method stub
}
public void putInformation(DatabaseOperations dop, String name, String pass)
{
SQLiteDatabase SQ = dop.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(TableData.TableInfo.USER_NAME, name);
cv.put(TableData.TableInfo.USER_PASSWORD, pass);
long k = SQ.insert(TableData.TableInfo.TABLE_NAME, null,cv);
Log.d("Database operations", "One raw inserted");
// inserts data into database
}
public Cursor getInformation(DatabaseOperations dop){
SQLiteDatabase SQ = dop.getReadableDatabase();
String[] columns = {TableData.TableInfo.USER_NAME,
TableData.TableInfo.USER_PASSWORD};
Cursor CR = SQ.query(TableData.TableInfo.TABLE_NAME ,columns, null,
null, null, null, null);
return CR;
}
}
Home.java
package m.rami.psucalculator;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
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.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
public class Home extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
public static final String DEFAULT = "N/A";
TextView userNameTestView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
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();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView)
findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//this code makes HOME the default fragment
android.support.v4.app.FragmentTransaction
ft=getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_home,new HomeFrag());
ft.commit();
navigationView.setCheckedItem(R.id.nav_home);
userNameTestView = findViewById(R.id.psuusername);
}
public void load(View view){
SharedPreferences sharedPreferences = getSharedPreferences("user_info",
Context.MODE_PRIVATE);
String name = sharedPreferences.getString("name",DEFAULT);
userNameTestView.setText(name);
}
public void setActionBarTitle(String title){
getSupportActionBar().setTitle(title);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, 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) {
Toast.makeText(this,"SETTINGS",Toast.LENGTH_SHORT).show();
Intent i = new Intent(Home.this,Settings.class);
startActivity(i);
} else if (id == R.id.action_information){
Toast.makeText(this,"INFORMATION",Toast.LENGTH_SHORT).show();
Intent i = new Intent(Home.this,Information.class);
startActivity(i);
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
Toast.makeText(this,"HOME", Toast.LENGTH_SHORT).show();
android.support.v4.app.FragmentTransaction
ft=getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_home,new HomeFrag());
ft.commit();
} else if (id == R.id.nav_math_250) {
Toast.makeText(this,"MATH 250",Toast.LENGTH_SHORT).show();
FragmentManager ft=getSupportFragmentManager();
ft.beginTransaction().replace(R.id.content_home,new
MATH250Frag()).commit();
} else if (id == R.id.nav_cmpsc_475) {
Toast.makeText(this,"CMPSC 475",Toast.LENGTH_SHORT).show();
FragmentManager ft=getSupportFragmentManager();
ft.beginTransaction().replace(R.id.content_home,new
CMPSC475Frag()).commit();
} else if (id == R.id.nav_stat_318) {
Toast.makeText(this,"STAT 318",Toast.LENGTH_SHORT).show();
FragmentManager ft=getSupportFragmentManager();
ft.beginTransaction().replace(R.id.content_home,new
STAT318Frag()).commit();
} else if (id == R.id.nav_math_220) {
Toast.makeText(this, "MATH 220",Toast.LENGTH_SHORT).show();
FragmentManager ft=getSupportFragmentManager();
ft.beginTransaction().replace(R.id.content_home,new
MATH220Frag()).commit();
} else if (id == R.id.nav_cmpsc_455){
Toast.makeText(this,"CMPSC 455", Toast.LENGTH_SHORT).show();
FragmentManager ft=getSupportFragmentManager();
ft.beginTransaction().replace(R.id.content_home,new
CMPSC455Frag()).commit();
} else if(id == R.id.nav_cmpsc469){
Toast.makeText(this,"CMPSC 469",Toast.LENGTH_SHORT).show();
FragmentManager ft=getSupportFragmentManager();
ft.beginTransaction().replace(R.id.content_home,new
CMPSC469Frag()).commit();
}
/*
use this code to make an activity without
nav menu.
** CREATE example class and nav_example
else if(id==R.id.nav_example){
Intent i = new Intent(Home.this,example.class);
startActivity(i);
}
*/
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
login.java
package m.rami.psucalculator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import static java.security.AccessController.getContext;
public class login extends Activity {
Button bLogin, bRegister;
EditText USERNAME, USERPASS;
String username, userpass;
Context context = this;
@Override
protected void onCreate(Bundle savedInstanceState) {
//method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
bLogin = (Button) findViewById(R.id.loginbutton);
USERNAME = (EditText) findViewById(R.id.user_name);
USERPASS = (EditText) findViewById(R.id.user_pass);
bRegister = findViewById(R.id.registernowbutton);
bLogin.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Bundle b = getIntent().getExtras();
int status = b.getInt("status");
if(status == 1)
{
Toast.makeText(getBaseContext(), "Please Wait...",
Toast.LENGTH_SHORT).show();
username = USERNAME.getText().toString();
userpass = USERPASS.getText().toString();
DatabaseOperations DOP = new
DatabaseOperations(context);
Cursor CR = DOP.getInformation(DOP);
CR.moveToFirst();
boolean loginstatus = false;
String NAME = "";
do
{
if(username.equals(CR.getString(0))&&
(userpass.equals(CR.getString(1))))
{
loginstatus = true;
NAME = CR.getString(0);
}
}while(CR.moveToNext());
if(loginstatus)
{
Toast.makeText(getBaseContext(), "Login Success\n
Hello "+NAME, Toast.LENGTH_LONG).show();
finish();
Intent logintohome = new Intent(login.this,
Home.class );
startActivity(logintohome);
}
else
{
Toast.makeText(getBaseContext(), "Login
Unsuccessful", Toast.LENGTH_LONG).show();
finish();
}
}
else if(status == 2)
{
Toast.makeText(getBaseContext(), "Please Wait...",
Toast.LENGTH_SHORT).show();
username = USERNAME.getText().toString();
userpass = USERPASS.getText().toString();
DatabaseOperations DOP = new
DatabaseOperations(context);
Cursor CR = DOP.getInformation(DOP);
CR.moveToFirst();
boolean loginstatus = false;
String NAME = "";
do
{
if(username.equals(CR.getString(0))&&
(userpass.equals(CR.getString(1))))
{
loginstatus = true;
NAME = CR.getString(0);
}
}while(CR.moveToNext());
if(loginstatus)
{
Toast.makeText(getBaseContext(), "Login Success\n
Hello "+NAME, Toast.LENGTH_LONG).show();
Intent i = new Intent("update_filter");
Bundle BN = new Bundle();
BN.putString("user_name",NAME );
BN.putString("user_pass",userpass );
i.putExtras(BN);
startActivity(i);
finish();
Intent logintohome = new Intent(login.this,
Home.class );
startActivity(logintohome);
}
else
{
Toast.makeText(getBaseContext(), "Login Unsuccessful
", Toast.LENGTH_LONG).show();
finish();
}
}
else if(status == 3)
{
Toast.makeText(getBaseContext(), "Please Wait...",
Toast.LENGTH_SHORT).show();
username = USERNAME.getText().toString();
userpass = USERPASS.getText().toString();
DatabaseOperations DOP = new
DatabaseOperations(context);
Cursor CR = DOP.getInformation(DOP);
CR.moveToFirst();
boolean loginstatus = false;
String NAME = "";
do
{
if(username.equals(CR.getString(0))&&
(userpass.equals(CR.getString(1))))
{
loginstatus = true;
NAME = CR.getString(0);
}
}while(CR.moveToNext());
if(loginstatus)
{
Toast.makeText(getBaseContext(), "Login Success\n
Hello "+NAME, Toast.LENGTH_LONG).show();
Intent i = new Intent("delete_filter");
Bundle B = new Bundle();
B.putString("user_name",NAME );
i.putExtras(B);
startActivity(i);
finish();
Intent logintohome = new Intent(login.this,
Home.class );
startActivity(logintohome);
}
else
{
Toast.makeText(getBaseContext(), "Login
Unsuccessful", Toast.LENGTH_LONG).show();
finish();
}
//Intent i = new Intent("delete_filter");
//startActivity(i);
}
}
});
bRegister.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
Intent logintoregister = new
Intent(login.this,RegisterUser.class);
startActivity(logintoregister);
}
}
);
}
public void save(View view){
SharedPreferences sharedPreferences =
getSharedPreferences("user_info",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("name",USERNAME.getText().toString());
DatabaseOperations DOOP = new DatabaseOperations(context);
Cursor CR = DOOP.getInformation(DOOP);
CR.moveToFirst();
String NAMENAME = "";
do {
if(username.equals(CR.getString(0))){
NAMENAME = CR.getString(0);
}
} while(CR.moveToNext());
editor.commit();
}
public void next(View view){
Intent i = new Intent(this, Home.class);
startActivity(i);
}
}
TableData.java
package m.rami.psucalculator;
import android.provider.BaseColumns;
public class TableData {
public TableData(){
}
public static abstract class TableInfo implements BaseColumns {
public static final String USER_NAME = "user_name";
public static final String USER_PASSWORD = "user_password";
public static final String DATABASE_NAME = "user_info";
public static final String TABLE_NAME = "reg_table";
}
}
错误屏幕
E/AndroidRuntime: FATAL EXCEPTION: main
Process: m.rami.psucalculator, PID: 28997
android.database.CursorIndexOutOfBoundsException: Index 0
requested, with a size of 0
at
android.database.AbstractCursor.checkPosition(AbstractCursor.java:460)
at
android.database.AbstractWindowedCursor.
checkPosition(AbstractWindowedCursor.java:136)
at
android.database.AbstractWindowedCursor.
getString(AbstractWindowedCursor.java:50)
at m.rami.psucalculator.login$1.onClick(login.java:51)
at android.view.View.performClick(View.java:6256)
at android.view.View$PerformClick.run(View.java:24701)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at
android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at
com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
答案 0 :(得分:0)
反转你的do / while因为它会执行,即使条件最初是假的。
while(CR.moveToNext()) {
if(username.equals(CR.getString(0))
&& (userpass.equals(CR.getString(1)))) {
loginstatus = true;
NAME = CR.getString(0);
}
}
或者更好:因为moveToFirst()返回一个布尔值意味着要获取的数据,你可以检查它:
if(CR.moveToFirst())
while(CR.moveToNext()){
//do thing with data
答案 1 :(得分:0)
您的表创建代码存在一些问题。 试试这组代码。
db.execSQL("CREATE TABLE IF NOT EXISTS " + purpose_of_loan_tb + " (" + pk_id + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "
+ purpose_of_loan_id + " INTEGER , " + user_id + " INTEGER, " + purpose_of_loan_status + " INTEGER, " +
purpose_of_loan_json + " TEXT);");
插入代码:
public long insertRows(SQLiteDatabase db, String tableName, ContentValues contentValues) {
long n = db.insert(tableName, null, contentValues);
Util.printMessage(TAG, "Row inserted in " + tableName + " : " + n);
return n;
}
通过根据列名和相应值将值放入内容值键来调用此方法。
在你的情况下:
contentValues.put("TableData.TableInfo.USER_NAME","ABCD");
要检索所有数据,您可以使用此方法:
public Cursor getValueByColumn(SQLiteDatabase db, String table_name,
String select_clause_colunms, String where_clause_column) {
Cursor cursor = db
.query(table_name, null, null, null, null, null, null);
// print("Count " + cursor.getCount());
return cursor;
}
这将返回光标,您可以在其中检查光标计数。