I have built three row layout. Assume RowLayout1, RowLayout2, RowLayout3 are the three row layouts. I would like to add RowLayout1 as first row, followed by RowLayout2 and as last row rowLayout3. Data for RowLayout2 comes from sqllite, other data from values .
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
public class Paasurams extends Activity {
private Divyadesamdb dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pasuram);
dbHelper = new Divyadesamdb(this);
dbHelper.open();
/*
* Check if data already exist if total count is
*/
int totalRows = dbHelper.getCountAllPasurams();
Log.d("VC", "totalRows = " + totalRows);
//dbHelper.deleteAllPasurams();
//Log.d("VC", "totalRows after delete = " + totalRows);
if (totalRows < 4535) {
// Clean all data commented to improve performance
dbHelper.deleteAllPasurams();
// Add some data
dbHelper.insertPasurams();
totalRows = dbHelper.getCountAllPasurams();
Log.d("VC","After insertPasurams rows found are "+totalRows);
}
Intent intent = getIntent();
String mcategory = intent.getStringExtra(MainActivity.EXTRA_CATEGORY);
String mstart = intent.getStringExtra(MainActivity.EXTRA_START);
String mending = intent.getStringExtra(MainActivity.EXTRA_ENDING);
String mpasuramNumber = intent
.getStringExtra(MainActivity.EXTRA_PASURAMNUMBER);
String maayiram = intent.getStringExtra(MainActivity.EXTRA_AAYIRAM);
String mazhwaar = intent.getStringExtra(MainActivity.EXTRA_AZHWAAR);
String mmangalasasanamOn = intent
.getStringExtra(MainActivity.EXTRA_MANGALASASANAMON);
String msubCategory = intent
.getStringExtra(MainActivity.EXTRA_SUBCATEGORY);
String mtitle = intent.getStringExtra(MainActivity.EXTRA_TITLE);
// Generate ListView from SQLite Database
displayListView(mpasuramNumber, maayiram, mazhwaar, mcategory,
mmangalasasanamOn, msubCategory, mtitle, mstart, mending);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void displayListView(String mpasuramNumber, String maayiram,
String mazhwaar, String mcategory, String mmangalasasanamOn,
String msubCategory, String mtitle, String mstart, String mending) {
String category = mcategory;
String starting = mstart;
String ending = mending;
String pasuramNumber = mpasuramNumber;
String aayiram = maayiram;
String azhwaar = mazhwaar;
String mangalasasanamOn = mmangalasasanamOn;
String subCategory = msubCategory;
String title = mtitle;
int rowsFound = 0;
Cursor cursor = dbHelper.fetchAllPasurams(pasuramNumber, aayiram,
azhwaar, category, mangalasasanamOn, subCategory, title,
starting, ending);
/*
* How many rows returned from the query
*/
rowsFound = cursor.getCount();
// the desired columns to be bound
String[] columns = new String[] {
Divyadesamdb.PASURAMS_COLUMN_PAASURAMNUMBER,
Divyadesamdb.PASURAMS_COLUMN_AAYIRAM,
Divyadesamdb.PASURAMS_COLUMN_AZHWAAR,
Divyadesamdb.PASURAMS_COLUMN_CATEGORY,
Divyadesamdb.PASURAMS_COLUMN_MANGALASASANAMON,
Divyadesamdb.PASURAMS_COLUMN_PAASURAM_EN_STR,
Divyadesamdb.PASURAMS_COLUMN_SUBCATEGORY,
Divyadesamdb.PASURAMS_COLUMN_TITLE,
Divyadesamdb.PASURAMS_COLUMN_TITLENUMBER,
Divyadesamdb.PASURAMS_COLUMN_IMAGE_ID };
// the XML defined views which the data will be bound to
int[] to = new int[] { R.id.tvPaasuramNumber, R.id.tvAayiram,
R.id.tvAzhwaar, R.id.tvCategory, R.id.tvMangalasasanamOn,
R.id.tvPaasuram, R.id.tvSubCategory, R.id.tvTitle,
R.id.tvtvTitleNumber, R.id.ivAzhwaar };
// create the adapter using the cursor pointing to the desired data
// as well as the layout information
MyCursorAdapter dataAdapter = new MyCursorAdapter(this,
R.layout.paasuram_single_item, cursor, columns, to, 0);
ListView listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(dataAdapter);
Log.d("VC", "Found rows " + rowsFound);
}
// extend the SimpleCursorAdapter to create a custom class where we
// can override the getView to change the row colors
private class MyCursorAdapter extends SimpleCursorAdapter {
Context mContext;
public MyCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to, int flags) {
super(context, layout, c, from, to, flags);
mContext = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// get reference to the row
View view = super.getView(position, convertView, parent);
// check for odd or even to set alternate colors to the row
// background
// want to get the value of this text view,
// but not getting handle.
if (position % 2 == 0) {
view.setBackgroundColor(Color.rgb(238, 233, 233));
} else {
view.setBackgroundColor(Color.rgb(255, 255, 255));
}
return view;
}
}
}
Related
I'm using a simplecursortreeadapter to populate an expandablelistview and want to have a row at the top of all the children views that has titles for the data.
Group 1 Name [Expanded]
Header (Date, Name, $)
Child 1 (07/12/2017, Chad, 50.00)
Child 2 (08/11/2017, Mike, 63.21)
Group 2 Name [Expanded]
Header (Date, Name, $)
Child 1 (03/25/2017, Ken, 23.97)
Child 2 (01/25/2017, Will, 101.11)
Group 3 [Collapsed]
Is it possible to have the textviews that contain the 3 sets of header text (Date, Name, $) to only appear when the group is expanded? Since the SimpleCursorTreeAdapter handles adding the cursor data into the views, I'm not sure how to add a row to that or how to achieve this. Is this possible?
Edit: Here is my adapter class:
package com.example.myproject.michaelc.billme;
import android.content.Context;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.database.MergeCursor;
import android.support.v4.content.Loader;
import android.util.Log;
import android.widget.SimpleCursorTreeAdapter;
import com.example.myproject.michaelc.billme.data.BillMeContract;
import java.util.HashMap;
public class PayeeCursorAdapter extends SimpleCursorTreeAdapter {
private final String LOG_TAG = getClass().getSimpleName();
private PayeeActivity mActivity;
protected final HashMap<Integer, Integer> mGroupMap;
// No cursor is added to the adapter so that it only runs when the CursorLoader runs, instead of every time the activity does
public PayeeCursorAdapter(
Context context, // The activity where the adapter will be running
int groupLayout, // The .xml layout file for the group layout
int childLayout, // The .xml layout file for the child layout
String[] groupFrom, // String of column names in the cursor that is the data for each group item
int[] groupTo, // The ID of the views in the group layout that display the column from the groupFrom String[]
String[] childrenFrom, // String of column names in the cursor that is the data for each child item
int[] childrenTo) { // The ID of the views in the child layout that display the column from the childFrom String[]
super(context, null, groupLayout, groupFrom, groupTo, childLayout, childrenFrom, childrenTo);
mActivity = (PayeeActivity) context;
mGroupMap = new HashMap<Integer, Integer>();
}
#Override
protected Cursor getChildrenCursor(Cursor groupCursor) {
int groupPos = groupCursor.getPosition();
int groupId = groupCursor.getInt(groupCursor.getColumnIndex(BillMeContract.PayeeEntry._ID));
Log.d(LOG_TAG, "getChildrenCursor() for groupPos " + groupPos);
Log.d(LOG_TAG, "getChildrenCursor() for groupId " + groupId);
mGroupMap.put(groupId, groupPos);
Loader<Cursor> loader = mActivity.getSupportLoaderManager().getLoader(groupId);
if(loader != null && !loader.isReset()) {
mActivity.getSupportLoaderManager().restartLoader(groupId, null, mActivity);
} else {
mActivity.getSupportLoaderManager().initLoader(groupId, null, mActivity);
}
return null;
}
public HashMap<Integer, Integer> getGroupMap(){
return mGroupMap;
}
}
Yes it can possible .
you can also see this link , hope you will get your solution.
http://www.worldbestlearningcenter.com/tips/Android-expandable-listview-header.htm
package android.widget.expandablelistview;
import android.os.Bundle;
import android.util.ExpandableListScenario;
import android.widget.Button;
import android.widget.ExpandableListView;
public class ExpandableListWithHeaders extends ExpandableListScenario {
private static final int[] sNumChildren = {1, 4, 3, 2, 6};
private static final int sNumOfHeadersAndFooters = 12;
#Override
protected void init(ExpandableParams params) {
params.setStackFromBottom(false)
.setStartingSelectionPosition(-1)
.setNumChildren(sNumChildren)
.setItemScreenSizeFactor(0.14)
.setConnectAdapter(false);
}
#Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
final ExpandableListView expandableListView = getExpandableListView();
expandableListView.setItemsCanFocus(true);
for (int i = 0; i < sNumOfHeadersAndFooters; i++) {
Button header = new Button(this);
header.setText("Header View " + i);
expandableListView.addHeaderView(header);
}
for (int i = 0; i < sNumOfHeadersAndFooters; i++) {
Button footer = new Button(this);
footer.setText("Footer View " + i);
expandableListView.addFooterView(footer);
}
// Set adapter here AFTER we set header and footer views
setAdapter(expandableListView);
}
/**
* #return The number of headers (and the same number of footers)
*/
public int getNumOfHeadersAndFooters() {
return sNumOfHeadersAndFooters;
}
}
This is my first app and i'm having some problem whit ListView
How can I get the ID in the database after clicking on a Item?
I can't use position because the Id may not be continuous and even if it is in order sometimes does not return the correct Id any.
this is my code, Thank you for your help:
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class livello1 extends AppCompatActivity {
DatabaseHelper myDb;
Button next;
#Override
protected void onCreate(Bundle savedInstanceState) {
myDb = new DatabaseHelper(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.livello1);
populateListView();
registerClick();
}
private void registerClick(){
ListView list =(ListView)findViewById(R.id.listViewMain);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id) {
Intent i = new Intent(livello1.this, bossi.note.Edit.class);
i.putExtra("id", position);
//i.putExtra("id", id);
startActivity(i);
}
});
}
private void populateListView(){
Cursor res = myDb.getAllData();
String[] myItems = new String[myDb.numRow()];
int cont = 0;
if(res.getCount() == 0){
// show message
return;
}
while( res. moveToNext()){
myItems[cont] = res.getString(1);
cont ++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.da_item, myItems);
ListView list =(ListView)findViewById(R.id.listViewMain);}
There are a lot of solution approaches.
For example, you can store of Id's if ArrayList before ListView initialization.
That is, execute "SELECT id FROM mytable"
Then store in arraylist and use while click method.
Example:
//in class declaration
private ArrayList<Long> ar_ids = new ArrayList<Long>;
//
String sql = "SELECT id FROM table";
Cursor cur = db.rawQuery(sql, null);
String out = "";
ArrayList<Long> ar_ids = new ArrayList<Long>;
if (cur.moveToFirst()) {
do {
ar.add(cur.getString(0));
} while (cur.moveToNext());
}else{
}
}
cur.close();
for click event:
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id) {
Intent i = new Intent(livello1.this, bossi.note.Edit.class);
i.putExtra("id", ar_id.get(position));
//this is awsome!
startActivity(i);
}
and initialize this something like:
private void myfunc() {
String sql = "SELECT id FROM table";
Cursor cur = myDb.rawQuery(sql, null);
String out = "";
ArrayList<Long> ar_ids = new ArrayList<Long>;
if (cur.moveToFirst()) {
do {
ar.add(cur.getString(0));
} while (cur.moveToNext());
}else{
throw new NullPointerException();
}
}
cur.close();
}
private void populateListView(){
myfunc();
Cursor res = myDb.getAllData();
String[] myItems = new String[myDb.numRow()];
int cont = 0;
if(res.getCount() == 0){
// show message
return;
}
while( res. moveToNext()){
myItems[cont] = res.getString(1);
cont ++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.da_item, myItems);
ListView list =(ListView)findViewById(R.id.listViewMain);}
well instead of using the ArrayAdapter you can extend a BaseAdapter or ListAdapter or even the ArrayAdapter to make your custom adapter. First of all make a plain java class to map your database data including id to an object. Then make a custom BaseAdapter instead of using the ArrayAdapter. In your BaseAdapter class you have to override various methods including getItem and getItemId methods. Now you can return the whole mapped object from the getItem method and simply obtain the object of selected item of the ListView by using listView.getSelectedItem() method in the Activity or Fragment class. Once you get the object you can access the id easily.
You can find a good example and explanation of a custom adapter here
About mapping the database result to an object, you can get some concept here
Here, you can replace you code class with this one, I have added a cursorAdapter and attached it with your ListView, in adapter I have added a method for getting Id that I call from click listener to retrieve id from cursor, you will have to set column number for _ID in public void getId(int position) from MyCursorAdapter class below.
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class livello1 extends AppCompatActivity {
DatabaseHelper myDb;
Button next;
private MyCursorAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
myDb = new DatabaseHelper(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.livello1);
populateListView();
registerClick();
}
private void registerClick(){
ListView list =(ListView)findViewById(R.id.listViewMain);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id) {
Intent i = new Intent(livello1.this, bossi.note.Edit.class);
//retrieve id from cursor
int _id = adapter.getId(position)
i.putExtra("id", _id);
//i.putExtra("id", id);
startActivity(i);
}
});
}
private void populateListView(){
Cursor res = myDb.getAllData();
adapter = new MyCursorAdapter(this, res, 0);
ListView list =(ListView)findViewById(R.id.listViewMain);
list.setAdapter(adapter);
}
//adapter for list view
class MyCursorAdapter extends CursorAdapter {
Cursor cursor;
// Default constructor
public MyCursorAdapter(Context context, Cursor cursor, int flags) {
super(context, cursor, flags);
this.cursor = cursor;
}
public void bindView(View view, Context context, Cursor cursor) {
String text = cursor.getString(1);
//make sure the TextView id is "#+id/text1" in da_item.xml
TextView tvText = (TextView) view.findViewById(R.id.text1);
tvText.setText(text);
}
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflator inflater = (LayoutInflater) context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
return Inflater.inflate(R.layout.da_item, parent, false);
}
public int getId(int position){
cursor.moveToPosition(position);
int colId = //set id column number here
int id = cursor.getLong(colId);
return id;
}
}
Since the code is untested, you might face a build issue in start, but it should give an idea of what's going on in code. feel free to ask any question if you face any problem in compilation
I have Activity that shows only listview (He pulls the data from SQLite database), There is no limit for the data he can shows, and it work out well.
Now, I want to add a new little listview to the MainActivity which will show only the last five of the data.
I could not find anywhere on the network how to do it..
DataListActivity.java
package com.example.ido.grades;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
public class DataListActivity extends ActionBarActivity {
ListView listView;
SQLiteDatabase sqLiteDatabase;
CourseDbHelper courseDbHelper;
Cursor cursor;
ListDataAdaptar listDataAdaptar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.update_course);
hideActionBar();
listView = (ListView) findViewById(R.id.list_view);
listDataAdaptar = new ListDataAdaptar(getApplicationContext(),R.layout.row_layout);
listView.setAdapter(listDataAdaptar);
registerForContextMenu(listView);
courseDbHelper = new CourseDbHelper(getApplicationContext());
sqLiteDatabase = courseDbHelper.getReadableDatabase();
cursor = courseDbHelper.getInformation(sqLiteDatabase);
registerForContextMenu(listView);
if (!cursor.moveToFirst()){
}
else {
do {
String year,semester,course,points,grade;
year = cursor.getString(0);
semester = cursor.getString(1);
course = cursor.getString(2);
points = cursor.getString(3);
grade = cursor.getString(4);
DataProvider dataProvider = new DataProvider(year,semester,course,points,grade);
listDataAdaptar.add(dataProvider);
}
while (cursor.moveToNext());
}
}
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_data_list, menu);
}
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info =
(AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
int mySelectedRowIndex = info.position;
switch (item.getItemId()) {
case R.id.update_item:
courseDbHelper = new CourseDbHelper(getApplicationContext());
sqLiteDatabase = courseDbHelper.getReadableDatabase();
DataProvider raw2 = (DataProvider)listDataAdaptar.getItem(mySelectedRowIndex);
Intent i = new Intent(DataListActivity.this, UpdateCourseActivity.class);
String year = raw2.getYear();
String semester = raw2.getSemester();
String course = raw2.getCourse();
String points = raw2.getPoints();
String grade = raw2.getGrade();
int semIndex;
if (semester.equals("A'")){
semIndex =1;
}
else if (semester.equals("B'")){
semIndex =2;
}
else{
semIndex=3;
}
i.putExtra("YEAR", year);
i.putExtra("SEMESTER", Integer.toString(semIndex));
i.putExtra("COURSE", course);
i.putExtra("POINTS", points);
i.putExtra("GRADE", grade);
i.putExtra("POS", Integer.toString(mySelectedRowIndex));
startActivity(i);
return true;
case R.id.delete_item:
courseDbHelper = new CourseDbHelper(getApplicationContext());
sqLiteDatabase = courseDbHelper.getReadableDatabase();
DataProvider raw = (DataProvider)listDataAdaptar.getItem(mySelectedRowIndex);
courseDbHelper.deleteInformation(raw.getYear(), raw.getSemester(), raw.getCourse(), raw.getPoints(), raw.getGrade());
Toast.makeText(this,"delete, pos["+mySelectedRowIndex+"]",Toast.LENGTH_LONG).show();
finish();
startActivity(getIntent());
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void onBackPressed() {
startActivity(new Intent(this, MainActivity.class));
}
private void hideActionBar() {
//Hide the action bar only if it exists
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
}
}
ListDataAdapter.java
package com.example.ido.grades;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Ido on 08/08/2015.
*/
public class ListDataAdaptar extends ArrayAdapter{
List list = new ArrayList();
public ListDataAdaptar(Context context, int resource) {
super(context, resource);
}
static class LayoutHandler{
TextView YEAR,SEMESTER,COURSE,POINTS,GRADE;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutHandler layoutHandler;
if (row == null){
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.row_layout,parent,false);
layoutHandler = new LayoutHandler();
layoutHandler.YEAR = (TextView)row.findViewById(R.id.textYear);
layoutHandler.SEMESTER = (TextView)row.findViewById(R.id.textSemester);
layoutHandler.COURSE = (TextView)row.findViewById(R.id.textCourse);
layoutHandler.POINTS = (TextView)row.findViewById(R.id.textPoints);
layoutHandler.GRADE = (TextView)row.findViewById(R.id.textGrade);
row.setTag(layoutHandler);
}
else{
layoutHandler = (LayoutHandler) row.getTag();
}
DataProvider dataProvider = (DataProvider) this.getItem(position);
layoutHandler.YEAR.setText(dataProvider.getYear());
layoutHandler.SEMESTER.setText(dataProvider.getSemester());
layoutHandler.COURSE.setText(dataProvider.getCourse());
layoutHandler.POINTS.setText(dataProvider.getPoints());
layoutHandler.GRADE.setText(dataProvider.getGrade());
return row;
}
}
You can move to the last position of your current cursor and move to previous rows getting required data. Sort of:
ArrayList string;
if (cursor.moveToLast()){
for (int i = 1; i<=6; i++) {
string.add(cursor.getString(cursor.getColumnIndex("your_data")));
cursor.moveToPrevious();
}
}
cursor.close();
The result will be ArrayList with last 6 strings of your cursor data. You can feed it to the new ArrayAdapter and show it on the screen.
Instead of ArrayList you can create another cursor as well with all existing data and feed it to already existing adapter for example as it's described here:
https://stackoverflow.com/a/18290921/4890659
Ignoring your code, you obviously have an Array of Objects your passing into the constructor of your Array Adapter.
Object[] data = new Object[]{...}
MyArrayAdapter myAdapter = new MyArrayAdapter(data ,... else)
You simply get this data array and append the last 6 elements to a new array.
Object[] data2 = new Object[6]
for(int i = data.length()-7; i<data.length(); i++){
data2[data.length()-i] = data[i]
Then create a new Adapter passing the new data2 array.
MyArrayAdapter myAdapter = new MyArrayAdapter(data2, ... else)
Create method that will return the last 6 rows i cursor [SQL query].
cursor = courseDbHelper.getInformationLast_6(sqLiteDatabase);
SQL:
SELECT * FROM table ORDER BY column DESC [ASC] LIMIT 6;
by this you can get 6 items in your list. Try with following code in your adapter class.
public int getCount() {
return 6;
}
than change your query to limit 6 by ascending order or descending order.
I have a listview on my mainactivity that is showing items from a database. I have an add button up in the action bar. When the add button is clicked on a dialog pops up and the user fills out fields for the new item and then they click "add" and it adds the item to the database. The only problem is that the listview on the mainactivity doesn't update to show the new item. I can close the app and reopen it and I see the new item. It just doesn't update immediatly. (Same problem with deleting an item, only the delete happens onLongPress)
Mainactivity.java
package blah.blah.blah
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
public class InitActivity extends FragmentActivity {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
// Gets the data repository in write mode
PlayersDBHelper mDbHelper = new PlayersDBHelper(getBaseContext());
SQLiteDatabase db = mDbHelper.getWritableDatabase();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_init);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}//End onCreate()
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.init, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_add:
showAddPlayerDialog();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void showAddPlayerDialog() {
// Create an instance of the dialog fragment and show it
DialogFragment dialog = new addPlayerDialog();
dialog.show(this.getFragmentManager(), "addPlayerFragment");
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if(position == 0) {
Fragment playersFragment = new PlayersFragment();
return playersFragment;
} else if(position == 1){
Fragment otherFragment= new otherFragment();
return otherFragment;
} else {
Fragment otherFragment2 = new otherFragment2();
return otherFragment2;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}//End sectionsPagerAdapter()
public static class PlayersFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public int myFragmentId = 1;
private ListView mylistview;
private String[] values;
public ArrayAdapter<String> adapter;
public PlayersFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_players,
container, false);
mylistview = (ListView) rootView.findViewById(R.id.myListView);
registerForContextMenu(mylistview);
PlayersDBHelper mDbHelper = new PlayersDBHelper(rootView.getContext());
SQLiteDatabase db = mDbHelper.getReadableDatabase();
// Define a projection that specifies which columns from the database
// you will actually use after this query.
String[] projection = {
PlayerEntry._ID,
PlayerEntry.COLUMN_NAME_ID,
PlayerEntry.COLUMN_NAME_NAME,
PlayerEntry.COLUMN_NAME_POSITION
};
String selection = null; //Null will return all rows for given table
String[] selectionArgs = null; //Null should return all data
// How you want the results sorted in the resulting Cursor
String sortOrder =
PlayerEntry.COLUMN_NAME_NAME + " DESC";
Cursor c = db.query(
PlayerEntry.TABLE_NAME, // The table to query
projection, // The columns to return
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
values = new String[] {};
String array[] = new String[c.getCount()];
int i = 0;
c.moveToFirst();
while (c.isAfterLast() == false) {
array[i] = c.getString(c.getColumnIndexOrThrow(PlayerEntry.COLUMN_NAME_NAME));
i++;
c.moveToNext();
}
for(int x = 0; x < array.length ; x++){
Log.d("Logan", "Entry at:" + x + " is " + array[x]);
values = push(values, array[x]);
}
adapter = new ArrayAdapter<String>(this.getActivity(),
android.R.layout.simple_list_item_1, values);
mylistview.setAdapter(adapter);
return rootView;
}
private static String[] push(String[] array, String push) {
String[] longer = new String[array.length + 1];
for (int i = 0; i < array.length; i++)
longer[i] = array[i];
longer[array.length] = push;
return longer;
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if (v.getId()==R.id.myListView) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
menu.setHeaderTitle(values[info.position]);
String[] menuItems = {"Edit", "Delete"};
for (int i = 0; i<menuItems.length; i++) {
menu.add(Menu.NONE, i, i, menuItems[i]);
}
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
PlayersDBHelper mDbHelper = new PlayersDBHelper(getActivity());
final SQLiteDatabase db = mDbHelper.getWritableDatabase();
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
int menuItemIndex = item.getItemId();
String[] menuItems = {"Edit", "Delete"};
String menuItemName = menuItems[menuItemIndex];
String listItemName = values[info.position];
if(menuItemName.equalsIgnoreCase("Edit")) {
} else {
//menuItemName === Delete
// Define 'where' part of query.
String selection = PlayerEntry.COLUMN_NAME_NAME + " =? ";
// Specify arguments in placeholder order.
String[] selectionArgs = { listItemName };
// Issue SQL statement.
db.delete(PlayerEntry.TABLE_NAME, selection, selectionArgs);
adapter.notifyDataSetChanged();
}
return true;
}
}
public static class otherFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public otherFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_lineup,
container, false);
return rootView;
}
}
public static class otherFragment2 extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public otherFragment2() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_position,
container, false);
return rootView;
}
}
}
addPlayerDialog.java
package blah.blah.blah;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
public class addPlayerDialog extends DialogFragment{
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Gets the data repository in write mode
PlayersDBHelper mDbHelper = new PlayersDBHelper(getActivity().getBaseContext());
final SQLiteDatabase db = mDbHelper.getWritableDatabase();
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
final LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
final View view = inflater.inflate(R.layout.addplayerdialog, null);
final ListView list = (ListView)view.findViewById(R.id.myListView);
builder.setView(view)
// Add action buttons
.setPositiveButton(R.string.add, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// sign in the user ...
EditText fName = (EditText) view.findViewById(R.id.editFirstName);
Editable firstName = fName.getText();
EditText lName = (EditText) view.findViewById(R.id.editLastName);
Editable lastName = lName.getText();
EditText number = (EditText) view.findViewById(R.id.playerNumber);
int num = Integer.parseInt(number.getText().toString());
Spinner spinner = (Spinner) view.findViewById(R.id.positionSpinner);
String position = spinner.getSelectedItem().toString();
// Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
values.put(PlayerEntry.COLUMN_NAME_ID, num);
values.put(PlayerEntry.COLUMN_NAME_NAME, firstName + " " + lastName);
values.put(PlayerEntry.COLUMN_NAME_POSITION, position);
// Insert the new row, returning the primary key value of the new row
long newRowId;
newRowId = db.insert(
PlayerEntry.TABLE_NAME,
null,
values);
//**** HERE IS WHERE I THINK THE CHANGE NEEDS TO BE! ****
((ArrayAdapter) list.getAdapter()).notifyDataSetChanged();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
Spinner spinner = (Spinner) view.findViewById(R.id.positionSpinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.positions, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
return builder.create();
}
}
addPlayerDialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/editFirstName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/fName" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/editLastName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/lName" />
<EditText
android:id="#+id/playerNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/playerNumberHint"
android:inputType="number" />
<Spinner
android:id="#+id/positionSpinner"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
I think you inserted the data to the DB but forgot to call yourListViewAdapter.add method before calling notifyDataSetChanged
This question already has an answer here:
i have android app that retrieve data from sqlite and display the data in BaseAdapter .. what is the best way ??
(1 answer)
Closed 8 years ago.
I have an android application that use SQLite to store and retrieve data.
In my project i have images in drawable folder that i stored their names in SQLite database, what i want is to display these images according to their names in a ListView.
I know that i need to add the fields name into the code but how to link the image to its name ?
this is my code:
MatchScheduleList.java
package com.devleb.expandablelistdemo3;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class MatchScheduleList extends Activity {
private static final String DB_NAME = "world_cup.db";
// *****Tables name**************************//
private static final String TABLE_NAME = "match_list";
// *****Tbale name******************************//
public static final String PLACE_ID = "_id";
public static final String STAD_NAME = "stad_name";
public static final String TEAM1 = "team1";
public static final String TEAM2 = "team2";
public static final String STAGE = "stage";
public static final String MATCH_DATE = "match_date";
public static final String GROUP = "group";
public static final String[] ALL_KEYS = new String[] { PLACE_ID, STAD_NAME,
TEAM1, TEAM2, STAGE, MATCH_DATE, GROUP };
// *****Tbale name******************************//
private SQLiteDatabase database;
private ListView listView;
private ArrayList<String> matchList;
private ExternalDbOpenHelper extDB;
int[] img = { R.drawable.brazil_flag, R.drawable.croatian_flag,
R.drawable.mexico_flag, R.drawable.cameroon_flag, R.drawable.spain,
R.drawable.netherlands_flag, R.drawable.czech_republic_flag,
R.drawable.australia, R.drawable.colombia_flag, R.drawable.gress,
R.drawable.cote_divoire_flag, R.drawable.japan,
R.drawable.uruguay_flag, R.drawable.costa_rica_flag,
R.drawable.england_flag, R.drawable.italy_flag,
R.drawable.switzerland, R.drawable.ecuador_flag,
R.drawable.france_flag, R.drawable.honduras_flag,
R.drawable.argentina_flag, R.drawable.bousna, R.drawable.iran_flag,
R.drawable.nigeria_flag, R.drawable.germany_flag,
R.drawable.portugal, R.drawable.ghana_flag,
R.drawable.united_states_flag, R.drawable.belgium_flag,
R.drawable.algeria_flag, R.drawable.russia_flag,
R.drawable.korea_flag };
int nextImageIndex = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_match_schedule_list);
ExternalDbOpenHelper extDB = new ExternalDbOpenHelper(this, DB_NAME);
database = extDB.openDataBase();
int imgid = img[nextImageIndex];
nextImageIndex = (nextImageIndex + 1) % img.length;
populateLitsFromDB();
}
public Cursor getAllRows() {
String where = null;
Cursor c = database.query(true, TABLE_NAME, ALL_KEYS, where, null,
null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
private void populateLitsFromDB() {
// TODO Auto-generated method stub
Cursor cursor = getAllRows();
// allo0w activity to manage life cicle of the cursor
startManagingCursor(cursor);
// setup mapping from cursor to view fields
String[] fromFieldNames = new String[] { MATCH_DATE, TEAM1, TEAM2,STAD_NAME, GROUP};
int[] toViewFields = new int[] { R.id.txtDate, R.id.textName1, R.id.textName2, R.id.textLocation, R.id.textGroup};
// create adapter to map columns of the DB INTO ELEMENT IN THE LIST
SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(this,
R.layout.row_list_match_schedule, cursor, fromFieldNames,
toViewFields);
Log.d("in the getAllRows", myCursorAdapter.toString());
// set the adapter for te listView
ListView myList = (ListView) findViewById(R.id.list);
myList.setAdapter(myCursorAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.match_schedule_list, menu);
return true;
}
}
Try this:
String imgName = "ic_launcher"; // specify here your image name fetched from db
String uri = "drawable/" + imgName;
int icon = getResources().getIdentifier(uri, "drawable", getPackageName());
imageView.setImageResource(icon);