UPDATE: PROBLEM FIXED -
The ActionBar was covering the first item on the list.
SOLUTION: Android AppBarLayout overlaps listview
In my program, I am retrieving data from the database and displaying it using List View.
However, the first row elements are always skipped in the process and the display begins from the second row.
public void displaydata(){
Cursor res = myDb.getAllData();
lv = (ListView) findViewById(R.id.idListView);
if(res.getCount() == 0){
//show message
return;
}
ArrayList<String> buffer = new ArrayList<>();
while(res.moveToNext()){
buffer.add(res.getString(1));
};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,buffer);
lv.setAdapter(adapter);
}
How do I make it display from the first row?
Any help is appreciated, thanks.
EDIT: I have tried all suggested answers of using a 'do-while' and a 'for loop', all of which give the same result.
Try changing
while(res.moveToNext()){
buffer.add(res.getString(1));
};
to
Edit: change the while so it increments after:
do {
buffer.add(res.getString(1));
} while (cursor.moveToNext());
Personally, I would recommend a CursorAdapter when using a database.
lv = (ListView) findViewById(R.id.idListView);
String from = { COLUMN_NAME };
int[] to = { android.R.id.text1 };
SimpleCursorAdapter adapter =
new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1,
myDb.getAllData(),
from, to);
lv.setAdapter(adapter);
Try out this this code may be useful for fetching data from db using cursor.
public ArrayList<BasicInfo> getFetchBasicInfo() {
ArrayList<BasicInfo> data = new ArrayList<BasicInfo>();
String sql = "select * from basic_info;
Cursor c = fetchData(sql);
if (c != null) {
while (c.moveToNext()) {
String FirstName = c.getString(c.getColumnIndex("first_name"));
String LastName = c.getString(c.getColumnIndex("last_name"));
String Sabcription = c.getString(c
.getColumnIndex("salutation_id"));
data.add(new BasicInfo(FirstName, LastName));
}
c.close();
}
return data;
}
Related
I am new to programming for Android devices. I have two activities, in the first activity I send an integer value from the first activity to the second activity.
How can I add this variable in sqlite query which I receive from my first activity?
I want to add booknumber where in query written b=1 I want replace 1 with booknumber
private void setData() {
Intent mIntent = getIntent();
int booknumber= mIntent.getIntExtra("booknumber", 0);
stringArrayList = new ArrayList<>();
mDBHelper = new DatabaseHelper(this);
mDb = mDBHelper.getReadableDatabase();
Cursor cursor = mDb.rawQuery("select DISTINCT c from t_asv where b=1", new String[]{});
if(cursor!=null && cursor.getCount() > 0)
{
if (cursor.moveToFirst())
{
do {
stringArrayList.add(cursor.getString(0));
} while (cursor.moveToNext());
}
}
Just Concatenate the int booknumber to your query like below:
int booknumber= mIntent.getIntExtra("booknumber", 0);
...
Cursor cursor = mDb.rawQuery("select DISTINCT c from t_asv where b=" + booknumber, new String[]{});
Update:
Its better to use the PreparedStatement / how to use as mentioned by #patrick-hollweck
Writing code like this leaves your app wide open to a sql injection vulnerability and is generally considered a very bad practice
I am attempting to create a ListView to display values entered via an EditText. I am using an ArrayList and ArrayAdapter but I am afraid I don't fully understand how they work.
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.listView1, num1);
I am unsure why I am unable to use android.R.id.listView1 where listView1 is the id of my list view in the activity. Is this not the resourceid that the adapter needs to list off my ArrayList?
Below is my full method and delcarations. Sorry if I am being vague in my questions, I don't fully know which terminology to use for what and I don't intend to cause confusion.
public ArrayAdapter<String> adapter;
ArrayList<String> allScores = new ArrayList<>();
ListView listScores = (ListView)findViewById(R.id.listView1);
public void onButtonClick(View V){
EditText input1 = (EditText) findViewById(R.id.scorePrompt);
TextView output1 = (TextView) findViewById(R.id.textTotal);
String blankCheck = input1.getText().toString(); //CHANGE INPUT IN scorePrompt TO STRING
TextView output2 = (TextView) findViewById(R.id.custName); //TEST FOR ARRAY LIST DISPLAY
if (blankCheck.equals("")) {
Toast blankError = Toast.makeText(getApplicationContext(), "YOU CANT SKIP HOLES JERK", Toast.LENGTH_LONG);
blankError.show();
} else {
//savedScores.add(input1.getText().toString());//Save input into array list
int num1 = Integer.parseInt(input1.getText().toString()); //Get input from text box
int sum = num1 + score2;
score2 = sum;
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.listView1, num1);
output1.setText("Your score is : " + Integer.toString(sum));
input1.setText(""); //Clear input text box
}
};
For some background information on my intentions, I want the user to enter integers in an EditText, save these values in an ArrayList, and then populate a ListView line-by-line with the values the user entered. Thank you for the help.
Try This way.
ArrayAdapter<String> itemsAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
ListView listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(itemsAdapter);
here you have to use setadapter of listview not put in the adapter
try this
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,allscores);
listscores.setAdapter(adapter)
if you want to add input things than make an Arraylist and simply pass it in adapter's third parameter
This question already has answers here:
Iterate through rows from Sqlite-query
(7 answers)
Closed 6 years ago.
I used a While Loop to add the values of an SQL table into an ArrayList using the Cursor class, but at the moment of adding all the values, the While Loop stop giving values but, at the same time, it doesn't continue with the next statements. I used the condition that: if inside the While Loop the Cursor has null value, it needs to stop (c != null), it stops but doesn't continue. I used Log.i to see if I receive values after the While Loop, but I don't get any value. Here is the code I am using:
static ArrayList<String> notes = new ArrayList<>();
static ArrayAdapter arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listView);
try{
SQLiteDatabase sqLiteDatabase = this.openOrCreateDatabase("Notes",MODE_PRIVATE, null);
sqLiteDatabase.execSQL("CREATE TABLE IF NOT EXISTS notes (name VARCHAR)");
sqLiteDatabase.execSQL("INSERT INTO notes (name) VALUES ('LUIS GA')");
sqLiteDatabase.execSQL("INSERT INTO notes (name) VALUES ('LUIS')");
sqLiteDatabase.execSQL("INSERT INTO notes (name) VALUES ('GA')");
Cursor c = sqLiteDatabase.rawQuery("SELECT * FROM notes", null);
int nameIndex = c.getColumnIndex("name");
notes.add("example note");
c.moveToFirst();
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, notes);
listView.setAdapter(arrayAdapter);
int i = 0;
Log.i("Bucefalo", Integer.toString(i));
while(c != null){
Log.i("Dato",c.getString(nameIndex));
notes.add(c.getString(nameIndex));
c.moveToNext();
i++;
Log.i("Luis", Integer.toString(i));
};
i = 2;
Log.i("Napoleon", Integer.toString(i));
String Hercules = "Hercules";
Log.i("Hercules",Hercules);
}
catch (Exception e){
e.printStackTrace();
}
The values that I receive in the Logcat using Log.i, are "Bucefalo" and "Luis" (the one inside the While Loop), but I don't receive the value "Napoleon" and "Hercules", Why? How I can fix this? Thank you
This is the best way to iterate through the cursor
Cursor cursor = db.rawQuery(...);
try {
while (cursor.moveToNext()) {
...
}
} finally {
cursor.close();
}
Aside the wrong usage of the cursor, this code
while(c != null){
...
c.moveToNext();
}
should actually never stop looping.
You see: you have a local reference c there. It is not null. Calling a method on a reference absolutely can not turn the reference itself to be null. Only an assignment like c = null would you get there.
In other words: your claims about observed behavior are not supported by the code you are posting.
moveToNext returns a boolean value, but at the same time it goes ahead and moves the cursor.
Use like this,
Cursor c = sqLiteDatabase.rawQuery(....);
while (c.moveToNext()) {
}
or
do {
} while (c.moveToNext());
There is a syntax error in your while Loop.it should be below
while (expression)
{
statemets(s)
}
and moreover you are using cursor badly.
you can use
cur.moveToFirst();
while (cur.isAfterLast() == false) {
.............
............
cur.moveToNext();
}
cur.close();
or
Cursor cursor = db.rawQuery(...);
if (cursor.moveToFirst()) {
do {
...
} while (cursor.moveToNext());
}
or
Cursor cursor = db.rawQuery(...);
try {
while (cursor.moveToNext()) {
...
}
} finally {
cursor.close();
}
I'm trying to retrieve a column (a database column where names are saved) and puting them to a listview. I have a class called Data with "getters" and "setters".
The following code is placed in a DBHandler class which extends SQLiteOpenHelper. This code is called from the MainActivity.java where the listview is meant to be updated with an onClickButton event.
public String[] getNames (int a, int b) {
String[] names = new String[] {};
String selectQuery = "SELECT * FROM " + TABLE_NAME
+ " WHERE " + KEY_ONE + " = ? AND " + KEY_TWO + " = ?";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, new String[]{String.valueOf(a), String.valueOf(b)});
if (cursor.moveToFirst()) {
int i = 0;
do {
Data myData = new Data();
names [i] = cursor.getString(1); //Names in cursor
++i;
} while (cursor.moveToNext());
}
return names;
}
In the MainActivity.java I call the following code before updating and notifying the update of the listview adapter:
values = db.getNames (1, 1);
I don't know why but this isn't working, it throws many errors with String lengths and crashes the app when I click the button that is suposed to enter the onClickButton.
Thanks
Follow the laalto answer and at last convert your ArrayList to Array like below:
String[] arrRecords = names.toArray(new String[names.size()]);
String[] names = new String[] {};
...
names [i] = cursor.getString(1); //Names in cursor
You're assigning to an empty array which causes ArrayIndexOutOfBoundsException.
Consider using a list such as ArrayList where you can append your values, e.g.
List<String> names = new ArrayList<String>();
...
names.add(cursor.getString(1));
If you really need to return a String[], you can convert the list with toArray():
String[] arr = new String[names.size()];
names.toArray(arr);
return arr;
Also, when posting questions that involve exceptions, always include the exception stacktrace from logcat in the question itself.
Why use like this
String[] names = new String[] {}; //no size
names [i] = cursor.getString(1); //it can work?
Use ArrayList<String>
List<String> names = new ArrayList<String>(); //declare
names.add(<column-val>); //add column value to list
public List<UserDataHelper> getData() {
List<UserDataHelper> list = new ArrayList<UserDataHelper>();
String selectQuery = "SELECT * FROM " + TABLE;
dbase = this.getReadableDatabase();
Cursor cursor = dbase.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
UserDataHelper quest = new UserDataHelper();
quest.setID(cursor.getInt(0));
quest.setName(cursor.getString(1));
quest.setSent(cursor.getInt(2));
quest.setRecieved(cursor.getInt(3));
quest.setTotal(cursor.getInt(4));
quest.setTimeSpent(cursor.getString(5));
list.add(quest);
} while (cursor.moveToNext());
}
return list;
}
This is for a listView but I want to fetch data individually and display it in textView. How can I achieve that? There are a lot of tutorials for listviews but not for textViews so can someone help me out please.
try this
for (UserDataHelper user:getData())
{
textView.append(user.getID()+" "+user.getName()
+" "+user.getRecieved()+" "+user.getSent()
+" "+user.getTimeSpent()+" "+user.getTotal()+"\n");
}
You could simply use the class object to set/get values, do following for string values:-
textView.setText(quest.getName());
and for the integer values make sure to use one
of the following:-
textView.setText(""+quest.getId());
or
textView.setText(String.valueOf(integer));