mercredi 27 avril 2016

Not able to access individual data entries in SQLite database in Android

I have saveinSQL class (extends SQLiteOpenHelper) where in I have defined my database accessing methods. I have created a database in Create class. I want to access the database in Home class. I'm able to get the number of rows in my database in my Home class by which I imply that I am able to access the database. But I am not able to access the data entries in a particular cell of the SQLite table with the help of cursor. My getHeader function seems to be faulty. Someone please help me. The part I'm dealing with is in the onCreate function of Home Class. The error I'm getting is android.database.CursorIndexOutOfBoundsException: Index 1 requested, with a size of 1

This is my Home class. I'm getting error on temp.header = mydb.getHeader(1);

package com.example.yashubale.mypetitions;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
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.ListView;
import android.widget.Toast;
import java.util.ArrayList;
    public class Home extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
        ArrayList<Petition> ap;
        saveinSQL mydb;

        String a,b,c;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        setTitle("Dashboard");
        ap = new ArrayList<Petition>();
        mydb = saveinSQL.getInstance(this);
        int numPetitions = mydb.numberOfRows();
    Toast.makeText(this , Integer.toString(numPetitions) ,     Toast.LENGTH_LONG).show();
        Petition temp = new Petition();
    //        temp.header = mydb.getHeader(2);
        temp.header = mydb.getHeader(1);
    //        temp.header = mydb.getHeader(3);
    //        for(int i= 1 ; i <= numPetitions ; i++){
    //
    //           // temp.header = mydb.getHeader(i);
    //            temp.description = mydb.getDescription(i);
    //            temp.people = mydb.getPeople(i);
    //            //ap.add(temp);
    //        }
      //  ListView lv = (ListView) findViewById(R.id.listpetitions);
      //  customeAdapter ca = new customeAdapter(this,ap);


    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.setDrawerListener(toggle);
    toggle.syncState();



    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}

@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) {
//            return true;
//        }

    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_create) {
        startCreate(this);

    } else if (id == R.id.nav_mypetitions) {

    } else if (id == R.id.nav_dashboard) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}
public void startCreate(Context c){
    Intent intent = new Intent(c , Create.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
}
}

This is my saveinSQL class

 package com.example.yashubale.mypetitions;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
public class saveinSQL extends SQLiteOpenHelper {

String header = new String();
String descrip = new String();
String people = new String();
Cursor res;
private static saveinSQL mInstance = null;
private Context myctx;
private static final int DATABASE_VERSION = 2;
private static final String PETITIONS_TABLE_NAME = "Petitions";
private static final String DATABASE_NAME = "myDB.db";
public static final String PETITIONS_COLUMN_ID = "id";
public static final String PETITIONS_COLUMN_HEADING = "heading";
public static final String PETITIONS_COLUMN_DESCRIPTION = "description";
public static final String PETITIONS_COLUMN_PEOPLE = "people";

public saveinSQL(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    myctx = context;
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(
            "create table Petitions" +
                    "(id integer primary key, heading text, description text, people text)"
    );
}

public static synchronized saveinSQL getInstance(Context context) {
    if (mInstance == null) {
        mInstance = new saveinSQL(context.getApplicationContext());
    }
    return mInstance;
}

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

public boolean insertPetition  (String heading, String description,String people)
{
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put("heading", heading);
    contentValues.put("description", description);
    contentValues.put("people", people);
    db.insert("Petitions", null, contentValues);
    return true;
}

public Cursor getData(int id){
    SQLiteDatabase db = this.getReadableDatabase();
     res =  db.rawQuery( "select * from Petitions where id="+id+"", null );
    return res;
}




public  String getHeader(int id){
    SQLiteDatabase db = this.getReadableDatabase();
     res = db.rawQuery("select * from Petitions where id=" + id + "", null);
    res.moveToPosition(id);
//        for(int i = 1; i < id; i++){
//            res.moveToNext();
//        }
    header =    res.getString(res.getColumnIndex(saveinSQL.PETITIONS_COLUMN_HEADING));
    res.moveToFirst();
    return header;
}

public String getDescription(int id){
    SQLiteDatabase db = this.getReadableDatabase();
    res = db.rawQuery("select * from Petitions where id=" + id + "", null);
    res.moveToFirst();
    for(int i = 1; i < id; i++){
        res.moveToNext();
    }
     descrip = res.getString(res.getColumnIndex(saveinSQL.PETITIONS_COLUMN_DESCRIPTION));
    return descrip;
}

public String getPeople(int id){
    SQLiteDatabase db = this.getReadableDatabase();
     res = db.rawQuery("select * from Petitions where id=" + id + "", null);
    res.moveToFirst();
    for(int i = 1; i < id; i++){
        res.moveToNext();
    }
     people = res.getString(res.getColumnIndex(saveinSQL.PETITIONS_COLUMN_PEOPLE));
    return people;
}




public int numberOfRows(){
    SQLiteDatabase db = this.getReadableDatabase();
    int numRows = (int) DatabaseUtils.queryNumEntries(db, PETITIONS_TABLE_NAME);
    return numRows;
}

public boolean updatePetitiont (Integer id, String heading, String description, String people)
{
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put("heading", heading);
    contentValues.put("description", description);
    contentValues.put("people", people);
    db.update("Petitions", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
    return true;
}

public Integer deletePetition (Integer id)
{
    SQLiteDatabase db = this.getWritableDatabase();
    return db.delete("Petitions",
            "id = ? ",
            new String[] { Integer.toString(id) });
}

public ArrayList<String> getAllPetitions()
{
    ArrayList<String> array_list = new ArrayList<String>();

    //hp = new HashMap();
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res =  db.rawQuery( "select * from Petitions", null );
    res.moveToFirst();

    while(res.isAfterLast() == false){
        array_list.add(res.getString(res.getColumnIndex(PETITIONS_COLUMN_HEADING)));
        res.moveToNext();
    }
    return array_list;
}
}

This my Create Class

public class Create extends AppCompatActivity {
private EditText mHeadingView;
private EditText mDescriptionView;
saveinSQL mydb = new saveinSQL(this);
EditText headingGet;
EditText descriptionGet;
EditText peopleGet;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_create);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    Button mEmailSignInButton = (Button) findViewById(R.id.createpetition);
    mEmailSignInButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            createPetition();
        }
    });

}

public void createPetition(){
    boolean cancel = false;
    View focusView = null;
    mHeadingView = (EditText)findViewById(R.id.heading);
    mDescriptionView = (EditText)findViewById(R.id.description);
    mHeadingView.setError(null);
    mDescriptionView.setError(null);
    String heading = mHeadingView.getText().toString();
    String description = mDescriptionView.getText().toString();
    if(heading.isEmpty()) {
        mHeadingView.setError("Heading is too short");
        focusView = mHeadingView;
        cancel = true;
    }
    if(description.isEmpty()){
        mDescriptionView.setError("Description is too short");
        focusView = mDescriptionView;
        cancel  = true;
    }

    if (cancel) {
        focusView.requestFocus();

    }
    else{
        headingGet =(EditText)findViewById(R.id.heading);
        descriptionGet =(EditText)findViewById(R.id.description);
        peopleGet =(EditText)findViewById(R.id.members);
//            for(int i = 1; i < 5 ; i++){
//                mydb.deletePetition(i);
//            }
        if(mydb.insertPetition(headingGet.getText().toString(), descriptionGet.getText().toString(), peopleGet.getText().toString())){
            Toast.makeText(getApplicationContext(), "Petition Added" , Toast.LENGTH_LONG).show();
            finish();
        }
    }
}

}

Aucun commentaire:

Enregistrer un commentaire