3

I want to save name in the SQLite Database and later in another activity I want to retrieve that name as a String Value. But I am not being able to get data from the database. Help me please. My code is given below,

Database Helper:

    private static final String TAG = "DatabaseHelper";
    private static final String TABLE_NAME = "user";
    private static final String COL1 = "ID";
    private static final String COL2 = "name";

    public void onCreate(SQLiteDatabase db) {String createTable = 
    "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY 
    AUTOINCREMENT, " + COL2 +" TEXT)"; 
    db.execSQL(createTable);}

    public boolean addData(String item) {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    contentValues.put(COL2, item);

            Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);

            long result = db.insert(TABLE_NAME, null, contentValues);

            if (result == -1) {
                return false;
            } else {
                return true;
            }
        }

MainActivity:

    mDatabaseHelper=new DatabaseHelper(this);
    Username=(EditText)findViewById(R.id.user);
    saveBtn=(Button)findViewById(R.id.button);

    saveBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
    String newEntry = Username.getText().toString();
                            AddData(newEntry);
                            Username.setText("");

    Intent intent = new Intent(MainActivity.this, HomeActivity.class);
                        startActivity(intent);
                    }
                });

            }
            public void AddData(String newEntry) {
                boolean insertData = mDatabaseHelper.addData(newEntry);
        }
        }

HomeActivity:

public class HomeActivity extends AppCompatActivity {

    DatabaseHelper mDatabaseHelper;
    String Username;

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

        mDatabaseHelper = new DatabaseHelper(this);

    }

}

Here, in this home activity i want to get the username as a string but I don't know how to do that. Help me please...

1
  • 1
    Please fix the code so it's valid Java code (the weird color coding is a hint), and please fix the code format, i.e. the indentations, for human readability. Commented Dec 31, 2018 at 3:29

3 Answers 3

6

To retrieve data, you run a query that extracts the data into a Cursor. The Cursor will consist of 0-n rows and will have as many columns as defined in the query. You then move through the rows and use the appropriate Cursor get????? methods to get the actual data.

As an example you could add the following method to your DatabaseHelper :-

public String getName(long id) {

    String rv = "not found";
    SqliteDatabase db = this.getWritableDatabase();
    String whereclause = "ID=?";
    String[] whereargs = new String[]{String.valueOf(id)};
    Cursor csr = db.query(TABLE_NAME,null,whereclause,whereargs,null,null,null);
    if (csr.moveToFirst()) {
        rv = csr.getString(csr.getColumnIndex(COL2));
    }
    return rv;
}

The above can then be used by String name = mDatabaseHelper.getName(1);.

  • Note that this assumes that a row with an ID of 1 exists.
Sign up to request clarification or add additional context in comments.

2 Comments

I did it by following your code. I have added this getname method in my database helper and after that in my HomeActivity I just called it as a String. String name=mdatabasehelper.getName(1); Thank you so much @MikeT
@RehanSarwar that's good, you should now tick one of the answers as being the answer, if you believe it answered your question.
1

Your Database Helper:

    private static final String TAG = "DatabaseHelper";
    private static final String TABLE_NAME = "user";
    private static final String COL1 = "ID";
    private static final String COL2 = "name";



private static final String createTable = "CREATE TABLE " + TABLE_NAME + " (" + COL1 +" INTEGER PRIMARY KEY AUTOINCREMENT, " + COL2 +" TEXT)"; // You have written ID inplace of COL1






 public  DatabaseHelper(Context context)
    {

        super(context,DB_NAME,null,1);
    }

 public void onCreate(SQLiteDatabase db)
    {
        db.execSQL(createTable);

    }

public boolean insertData(String name) {

    SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
    ContentValues contentValues1 =  new ContentValues();
    contentValues1.put(COL2,name);


    long result1 = sqLiteDatabase.insert(TABLE_NAME,null,contentValues1);
    return result1 != -1;
}
public Cursor viewData()
{
    SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
    Cursor cursor ;

    String query = "Select * from " +TABLE_NAME;
    cursor= sqLiteDatabase.rawQuery(query, null);


    return cursor;
}

Your Main Activity:

 mDatabaseHelper=new DatabaseHelper(this);
    Username=(EditText)findViewById(R.id.user);
    saveBtn=(Button)findViewById(R.id.button);

    saveBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
    String newEntry = Username.getText().toString();
                            mDatabaseHelper.insertData(newEntry);
                            Username.setText("");

    Intent intent = new Intent(MainActivity.this, HomeActivity.class);
                        startActivity(intent);
                    }
                });

            }

        }

Your Home Activity:

public class HomeActivity extends AppCompatActivity {

    DatabaseHelper mDatabaseHelper;
    String Username;


ArrayList<String> listItem;
    ArrayAdapter adapter;
    ListView listView;

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

        mDatabaseHelper = new DatabaseHelper(this);
listView = (ListView) findViewById(R.id.listView);
        listItem = new ArrayList<>();
viewData1();

    }

private void viewData1() {

        Cursor cursor = mDatabaseHelper.viewData();

        if (cursor.getCount() == 0) {

            Toast.makeText(this, "No data to show", Toast.LENGTH_SHORT).show();
        } else {
            while (cursor.moveToNext()) {
                Log.i("message","Data got");

                listItem.add(cursor.getString(1)); // Adding data received to a Listview
            }
            adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listItem);
            listView.setAdapter(adapter);

        }
    }

    }

Comments

0

check it out this library

it is very easy to implement

https://github.com/wisdomrider/SqliteClosedHelper

1 Comment

Thank you for your suggestion, I will check it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.