0

Don't ask questions here often but I have a MyDBHelper class with a method 'databaseToString' which I'm pretty sure is wrong but what I want to do is get the details that the user enters in the form which are stored in the 'details' table and output them in a seperate fragment/listview using cursors. (focus on one table for now) First of all I think my method 'databaseToString' is wrong as I want it to get what the user enters and display all the columns in a listview and secondly what do I do with this method so as to output the contents of the cursor to a new listview/fragment?

EDITED MyDBHelper class

package com.astuetz.viewpager.extensions.sample;

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

import java.util.ArrayList;
import java.util.List;

public class MyDBHandler extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "detailsDB.db";
public static final String TABLE_DETAILS = "details";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_FIRSTNAME = "firstname";
public static final String COLUMN_SURNAME = "surname";
public static final String COLUMN_PHONE = "phone";
public static final String COLUMN_EMAIL = "email";
public static final String COLUMN_ADDRESS1 = "address1";
public static final String COLUMN_ADDRESS2 = "address2";

public static final String TABLE_KIN_DETAILS = "kindetails";
public static final String COLUMN_KIN_ID = "_id";
public static final String COLUMN_KIN_YOUREMAIL = "youremailkin";
public static final String COLUMN_KIN_FIRSTNAME = "firstnamekin";
public static final String COLUMN_KIN_SURNAME = "surnamekin";
public static final String COLUMN_KIN_PHONE = "phonekin";
public static final String COLUMN_KIN_EMAIL = "emailkin";
public static final String COLUMN_KIN_ADDRESS1 = "address1kin";
public static final String COLUMN_KIN_ADDRESS2 = "address2kin";

// Pass database information along to superclass
public MyDBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
    super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    String query = " CREATE TABLE " + TABLE_DETAILS + "("
            + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
            + COLUMN_FIRSTNAME + " TEXT, "
            + COLUMN_SURNAME + " TEXT, "
            + COLUMN_PHONE + " TEXT, "
            + COLUMN_EMAIL + " TEXT, "
            + COLUMN_ADDRESS1 + " TEXT, "
            + COLUMN_ADDRESS2 + " TEXT "
            + ");";

    String query2 = " CREATE TABLE " + TABLE_KIN_DETAILS + "("
            + COLUMN_KIN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
            + COLUMN_KIN_YOUREMAIL + " TEXT, "
            + COLUMN_KIN_FIRSTNAME + " TEXT, "
            + COLUMN_KIN_SURNAME + " TEXT, "
            + COLUMN_KIN_PHONE + " TEXT, "
            + COLUMN_KIN_EMAIL + " TEXT, "
            + COLUMN_KIN_ADDRESS1 + " TEXT, "
            + COLUMN_KIN_ADDRESS2 + " TEXT "
            + ");";
    db.execSQL(query);
    db.execSQL(query2);
}

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

//Add a new row to the database
public void addDetails(Details details) {
    ContentValues values = new ContentValues();
    values.put(COLUMN_FIRSTNAME, details.getFirstname());
    values.put(COLUMN_SURNAME, details.getSurname());
    values.put(COLUMN_PHONE, details.getPhone());
    values.put(COLUMN_EMAIL, details.getEmail());
    values.put(COLUMN_ADDRESS1, details.getAddress1());
    values.put(COLUMN_ADDRESS2, details.getAddress2());
    SQLiteDatabase db = getWritableDatabase();
    db.insert(TABLE_DETAILS, null, values);
    db.close();
}


public void addKinDetails(KinDetails kinDetails){
    ContentValues values = new ContentValues();
    values.put(COLUMN_KIN_YOUREMAIL, kinDetails.getyourEmailkin());
    values.put(COLUMN_KIN_FIRSTNAME, kinDetails.getFirstnamekin());
    values.put(COLUMN_KIN_SURNAME, kinDetails.getSurnamekin());
    values.put(COLUMN_KIN_PHONE, kinDetails.getPhonekin());
    values.put(COLUMN_KIN_EMAIL, kinDetails.getEmailkin());
    values.put(COLUMN_KIN_ADDRESS1, kinDetails.getAddress1kin());
    values.put(COLUMN_KIN_ADDRESS2, kinDetails.getAddress2kin());
    SQLiteDatabase db = getWritableDatabase();
    db.insert(TABLE_KIN_DETAILS, null, values);
    db.close();
}



public List<Details> getAllDetails(){

    //create a new list in which we put all persons
    List<Details>detailsList = new ArrayList<>();

    SQLiteDatabase db = getWritableDatabase();
    String query = "SELECT * FROM " + TABLE_DETAILS;

    //Cursor points to a location in your results
    Cursor c = db.rawQuery(query, null);
    //Move to the first row in your results

    if (c != null) {

        c.moveToFirst();

        //Position after the last row means the end of the results
        while (!c.isAfterLast()) {

            //create new details object
            Details details = new Details();

            //Here use static decalared on top of the class..dont use "" for the table column
            details.set_id(c.getColumnIndex(COLUMN_ID));
            details.setFirstname(c.getString(c.getColumnIndex(COLUMN_FIRSTNAME)));
            details.setSurname(c.getString(c.getColumnIndex(COLUMN_SURNAME)));
            details.setPhone(c.getString(c.getColumnIndex(COLUMN_PHONE)));
            details.setEmail(c.getString(c.getColumnIndex(COLUMN_EMAIL)));
            details.setAddress1(c.getString(c.getColumnIndex(COLUMN_ADDRESS1)));
            details.setAddress2(c.getString(c.getColumnIndex(COLUMN_ADDRESS2)));

            detailsList.add(details);


            c.moveToNext();
        }

        c.close();
    }

    db.close();

    //return our list of persons
    return detailsList;

}

}

Details class

package com.astuetz.viewpager.extensions.sample;


public class Details {
int _id;
String firstname;
String surname;
String phone;
String email;
String address1;
String address2;

// Empty constructor
public Details(String s){
}

public void set_id(int _id) {
    this._id = _id;
}

public void setFirstname(String firstname) {
    this.firstname = firstname;
}

public void setSurname(String surname) {
    this.surname = surname;
}

public void setPhone(String phone) {
    this.phone = phone;
}

public void setEmail(String email) {
    this.email = email;
}

public void setAddress1(String address1) {
    this.address1 = address1;
}

public void setAddress2(String address2) {
    this.address2 = address2;
}







public int get_id() {
    return _id;
}

public String getFirstname() {
    return firstname;
}

public String getSurname() {
    return surname;
}

public String getPhone() {
    return phone;
}

public String getEmail() {
    return email;
}

public String getAddress1() {
    return address1;
}

public String getAddress2() {
    return address2;
}
}

LOGCAT ERROR

Error:(126, 35) error: constructor Details in class Details cannot be applied to given types;
required: String
found: no arguments
reason: actual and formal argument lists differ in length
Kdawg92
  • 21
  • 2
  • 8
  • what is wrong exactly? in your databasetoString method you have to check for cursor null, and close the cursor...the rest if it gives you a good result there is nothing wrong, also your DBHandler structure is looking good – J.Vassallo Feb 24 '15 at 19:28
  • How would I check for cursor null? I've never used cursors before and what I'm really confused about, even after looking at tutorials is how to use this method to put the cursor contents into a listview in a new fragment? – Kdawg92 Feb 24 '15 at 19:33
  • lol sry now i understood what you trying to achieve..im preparing you a nice answer ..hold on :) – J.Vassallo Feb 24 '15 at 19:36

2 Answers2

2

The best approach is to create your custom objects to manage data for your example , create a new java file and name it Person, the following is the person class (for simplicity of code we do only 2 properties, you build yours completed with all the fields) :

public class Person {

//Properties
private String _id;
private String firstname;

//Constructor
public Person() {
}


//Getters and Setters
public String get_id() {
    return _id;
}

public void set_id(String _id) {
    this._id = _id;
}

public String getFirstname() {
    return firstname;
}

public void setFirstname(String firstname) {
    this.firstname = firstname;
}


}

Now this person object can be used from anywhere in your project, including send it to the dbHandler and getting from the dbHandler.

For example to retrieve (not databaseToString , try to name methods more appropriately in the future) for example in the dbHandler :

Update No 2

/**
 * This method returns a list of persons objects
 * @return
 */
public List<Person> getAllPersons(){

    //create a new list in which we put all persons 
    List<Person>personsList = new ArrayList<>();

    SQLiteDatabase db = getWritableDatabase();
    String query = "SELECT * FROM " + TABLE_DETAILS;

    //Cursor points to a location in your results
    Cursor c = db.rawQuery(query, null);
    //Move to the first row in your results

    if (c != null) {

        c.moveToFirst();

        //Position after the last row means the end of the results
        while (!c.isAfterLast()) {

            //create new person object
            Person person = new Person();

            //Here use static decalred on top of the class..dont use "" for the table column
            person.setFirstname(c.getString(c.getColumnIndex(COLUMN_FIRSTNAME)));
            person.set_id(c.getString(c.getColumnIndex(COLUMN_ID)));

            personsList.add(person);

            c.moveToNext();
        }

        c.close();
    }

    db.close();

    //return our list of persons
    return persons;

}

LOGCAT EDIT

Error:(126, 35) error: constructor Details in class Details cannot be applied to given types;
required: String
found: no arguments
reason: actual and formal argument lists differ in length
Kdawg92
  • 21
  • 2
  • 8
J.Vassallo
  • 2,282
  • 3
  • 15
  • 14
  • If you want i can explain further on how to use the Persons list and display in a listview etc – J.Vassallo Feb 24 '15 at 19:55
  • Ok, so I've created a 'Details' class (well I always had it) and I edited the method you gave me there and I'm getting errors on the following lines 'details.setFirstname(c.getColumnIndex(COLUMN_FIRSTNAME)); details.setSurname(c.getColumnIndex(COLUMN_SURNAME)); details.setPhone(c.getColumnIndex(COLUMN_PHONE)); details.setEmail(c.getColumnIndex(COLUMN_EMAIL)); details.setAddress1(c.getColumnIndex(COLUMN_ADDRESS1)); details.setAddress2(c.getColumnIndex(COLUMN_ADDRESS2));' I'm editing my question there now, 2 secs – Kdawg92 Feb 24 '15 at 20:12
  • get get all persons muust be in the dbHandler ok ? – J.Vassallo Feb 24 '15 at 20:13
  • Yup it is! First of all it's saying "variable 'details' is allready defined in the scope but if I comment that out then 'details.set_id' will give me an error. – Kdawg92 Feb 24 '15 at 20:17
  • can you update your question with the new db handler...? write update in bold on it – J.Vassallo Feb 24 '15 at 20:18
  • Sorry, just did it there! – Kdawg92 Feb 24 '15 at 20:20
  • the get all details look good..just change to this (remove the +""").. String query = "SELECT * FROM " + TABLE_DETAILS; – J.Vassallo Feb 24 '15 at 20:25
  • wait i a mistake..i am updating alldetails – J.Vassallo Feb 24 '15 at 20:26
  • we have to use c.getString before c.getColumnIndex – J.Vassallo Feb 24 '15 at 20:28
  • That solved that, one more little error I'm getting with this line "Details details = new Details();" It saying that details is allready defined in the scope but if I comment it out then "details.setFirstname(c.getString(c.getColumnIndex(COLUMN_FIRSTNAME)));" don't work. – Kdawg92 Feb 24 '15 at 20:36
  • you called the details the same name as the details object..the list change its name to detailsList : List
    detailsList = new ArrayList<>(); .... also infront of the c.moveToNext() we need to put the details object into the detailsList with detailsList.add(details); ...i updated my answer the getAllPersons method
    – J.Vassallo Feb 24 '15 at 23:06
  • Ah silly mistake! One more little error that I'm getting with the line "Details details = new Details();" .......it's saying "Details (String) in Details cannot be applied to ()" ......I've edited my DBHelper to show what I currently have – Kdawg92 Feb 24 '15 at 23:33
  • that line seems fine to me :S – J.Vassallo Feb 24 '15 at 23:48
  • Yup thats done in the eddited code above :) No odea what this error is about though :( – Kdawg92 Feb 24 '15 at 23:52
  • hello lol! its in the details item constructor change (String s) to () in the line public Details(String s){ – J.Vassallo Feb 25 '15 at 00:01
  • FINALLY, you god amognst men! :) Right, now how to display it in a listview lol? Should I ask this as another question or? – Kdawg92 Feb 25 '15 at 00:05
  • better because it will be another awesome experience trust me – J.Vassallo Feb 25 '15 at 00:09
  • now send me the link so i prepare you a nice answer :D – J.Vassallo Feb 25 '15 at 00:10
  • the theory goes like this..you build an xml for your activity ok and an xml for the listview cell, then you create a custom adapter and attach it to the listview..thats all – J.Vassallo Feb 25 '15 at 00:13
  • Perfect thank you man, I'll send you the link in the morning, I'm off to bed...cheers again man! – Kdawg92 Feb 25 '15 at 00:13
  • Hello again, heres my new question if you wouldn't mind helping me again! [http://stackoverflow.com/questions/28717017/using-sqlite-cusor-to-output-table-contents-in-listview-in-a-fragment] – Kdawg92 Feb 25 '15 at 10:49
  • im preparing u a nice answer :D – J.Vassallo Feb 25 '15 at 10:55
  • posted new answer...what i posted is thebest ay to go along in android, if you follow corerctly you can create any type of listviews – J.Vassallo Feb 25 '15 at 11:46
  • Cheers man, I'll spend some time looking at this and implementing it and I'll get back to you :) – Kdawg92 Feb 25 '15 at 11:49
  • Any chance you'd know what to do here? [http://stackoverflow.com/questions/28766920/sqlite-updating-a-row-and-updating-listview-created-by-cursor/28767394#28767394] – Kdawg92 Feb 27 '15 at 15:50
0

I have this code in a button, to do a select of the table and a cursor to get the Column with a specific name to send to a String and last set it a textView: chech it out!

BT6.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View arg0) {
                String C1, C2, C3, C4;
                String Fin="";


                if (ET1.getText().toString().equals(""))
                {
                    Fin="Ningun Resultado";
                }
                else
                {                   
                    String SELECT_QUERY = "SELECT * FROM Tutores t1 INNER JOIN Tutorados t2 ON t1._id = t2.id_tutor and t1._id = " + ET1.getText().toString().trim();
                    cursor = db.rawQuery(SELECT_QUERY, null);

                    if (cursor.getCount() != 0) {
                        if (cursor.moveToFirst()) {
                            do {
                                C1 = cursor.getString(cursor
                                        .getColumnIndex("_id"));

                                C2 = cursor.getString(cursor
                                        .getColumnIndex("nombre_tutorado"));

                                C3 = cursor.getString(cursor
                                        .getColumnIndex("id_tutor"));

                                C4 = cursor.getString(cursor
                                        .getColumnIndex("nombre_tutor"));
                                Fin += C1 + "-" + C2 + "-" + C3 + "-"+ C4 + "\n";

                            } while (cursor.moveToNext());
                        }                       
                    }
                    cursor.close();
                }
                TV2.setText(Fin);

            }           
        });

see ya!

Carlos Carrizales
  • 2,340
  • 3
  • 18
  • 24