If I populate my listview with the primary key of my table I can get this primary key using getItemAtPosition and then it works fine.
The problem is that I don't want to use the primarykey to populate de listview, instead I want to use other fields of my table. Doing that, when I use the getItemAtPosition comand, because itsn't unic I can't use this to select my register.
I thought about using getItemIdAtPosition but I didn't reached any solution.
public void populateListView() {
//get the data and append to the list
Cursor data = db.getAllDataFillup(selectedID);
ArrayList<String> listData2 = new ArrayList<>();
while (data.moveToNext()) {
//listData2.add("FILLUP_ID: " + data.getString(0) + " FILLUP_VEHICLE_ID: " + data.getString(1));
//listData2.add(data.getString(7) + " " + data.getString(8) + " " + data.getString(2));
listData2.add(data.getString(3));
//listData2.add(data.getString(2));
}
//create the list adapter and set the adapter
ListAdapter adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listData2);
list_fillup.setAdapter(adapter2);
//set onItemClickListener to the listView
list_fillup.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
int fillupID = Integer.parseInt(adapterView.getItemAtPosition(i).toString());
long position = adapterView.getSelectedItemId();
//long a = list_fillup.get(codigoDoObjeto).getCodigoIdOuPKQualquer();
toastMessage("position: " + position);
//toastMessage("fillupPosition: " + fillupPosition);
//long fillupPosition = adapterView.getItemIdAtPosition(i);
Log.d(TAG, "onItemClick: You Clicked on " + fillupID);
Cursor data = db.getDataTableFillup(fillupID);//get the data associated with that fillupID
fillupID = -1;
while (data.moveToNext()) {
fillupID = data.getInt(0);
vehicleID = data.getInt(1);
fillupDate = data.getString(2);
odometer = data.getLong(3);
kmDriven = data.getLong(4);
liters = data.getLong(5);
consumption = data.getLong(6);
label = data.getString(7);
sequence = data.getInt(8);
}
if (fillupID > -1) {
Log.d(TAG, "onItemClick: The ID is: " + fillupID);
Intent screenVehicle = new Intent(Vehicle_painel.this, Fillup_edit.class);
screenVehicle.putExtra("fillupID", fillupID);
screenVehicle.putExtra("vehicleID", vehicleID);
screenVehicle.putExtra("vehicleName", selectedName);
screenVehicle.putExtra("date", fillupDate);
screenVehicle.putExtra("odometer", odometer);
screenVehicle.putExtra("kmDriven", kmDriven);
screenVehicle.putExtra("liters", liters);
screenVehicle.putExtra("consumption", consumption);
screenVehicle.putExtra("label", label);
screenVehicle.putExtra("sequence", sequence);
//toastMessage("fillupPosition: " + fillupPosition);
startActivity(screenVehicle);
} else {
toastMessage("fillupID = " + fillupID);
//db.deleteAllFillup(selectedID);
//toastMessage("No ID associated with that name hahaha");
}
The best thing to do would be to create a custom class to hold your data. That way you no longer just get a simple String value back from your adapter. Your ArrayList would be something like:
ArrayList<YourCustomClass> listData2 ...
Create a custom class "YourCustomClass" (Call it what ever you like). It could look like:
public class YourCustomClass {
private long itemId = 0;
private String itemName;
private String itemDescription;
public YourCustomClass(){
}
public void setItemId(long id){ this.itemId = id; }
public void setItemName(String itemName){ this.itemName = itemName; }
public void setItemDescription(String itemDescription){ this.itemDescription = itemDescription; }
public long getItemId() { return this.itemId; }
public String getItemName(){ return this.itemName; }
public String getItemDescription(){ return this.itemDescription; }
}
Now in your onItemClick method get the Id and the other data like this:
YourCustomClass data = (YourCustomClass) adapterView.getItemAtPosition(i);
long orderId = data.getItemId();
String name = data.getItemName();
You will need a custom adapter to populate your ListView with data.
You can also take a look at this answer. It shows how to change the background color of a ListView item, but also shows more detail of how to implement a custom adapter for your ListView.
How to set background color for each item listview depanding on variable value
Related
How can I save a query result in a String array?
The query is simple, it's got only one column i.e.:
SELECT NAME FROM MYTABLE
What I want is to store the ids in a String array so I can show them as clickable items in a ListView
Try this
String selectQuery = "SELECT * FROM table";
try {
Cursor cursor = db.rawQuery(selectQuery, null);
ArrayList<String> ids = new ArrayList<>();
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
String id = cursor.getString(cursor.getColumnIndex(KEY_ID));
ids.add(id);
} while (cursor.moveToNext());
}
cursor.close();
} catch (Exception e) {
e.printStackTrace();
}
Assuming you've already executed your query against a SQLiteDatabase object, and received a Cursor in return, you can iterate through the cursor and save the value of each row to a String[] array like so:
String[] names;
if (cursor.moveToFirst()) {
names = new String[cursor.getCount()];
int colIndex = cursor.getColumnIndex("NAME");
do {
names[cursor.getPosition()] = cursor.getString(colIndex);
} while (cursor.moveToNext());
}
Keep in mind that names will be null if no rows are returned, so make sure you do a null check.
create following method in SQLiteOpenHelper class
public List<String> getAllNames() {
List<String> retData = new ArrayList<String>();
String selectQuery = "SELECT NAME FROM MYTABLE";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
retData.add(cursor.getString(0));
} while (cursor.moveToNext());
}
return retData;
}
then assign this returned list to adapter
The issue with listing id's is that they tend to be meaningless to an end user. Really you want to display user meaningful data, e.g. a name, but to then be able to access the respective id to then efficiently act on a selection from the list presented to a user.
Using an ArrayList is frequently the cause of much frustration, as the list shows what is required but it's then found to be of little use when attempting to use the list beyond displaying data e.g. selecting an item to then do something such as delete or update (if the value is unique within the database it can be used).
As such an ArrayList<your_object> rather then an ArrayList<String> is generally more viable as the source of the List; a Cursor Adapter can also be used as data from the underlying row is easily obtained.
However, there is an issue, unless a Custom Array Adapter is utilised, when using an ArrayList in that the ArrayAdapter class uses the toString method of the object to retrieve the data that is displayed. The simple fix is to provide a suitable toString method in the object, if you don't you will get something long the lines of “SomeType#2f92e0f4”.
Example showing all 3
In the following working example :-
the database (mydb) has 1 table named mytable which has two columns _id (Note must be _id for a CursorAdapter)
There are 3 methods to get the 3 types of list (named accordingly) :-
getAllAsStringArrayList (gets ArrayList)
getAllAsMyTableObjectArrayList (gets ArrayList). Note uses the MyTableObject class (see note in class re overriding the default toString method)
getAllAsCursor
The App, when run, will have 3 lists, the left based upon the first ArrayList, the middle based upon the ArrayList and the last based upon the Cursor.
Clicking an item in any of the lists displays the respective name along with attempts to get the id.
The ArrayList, Left List, fails in this aspect as it can only get the position (i.e. the 4th parameter passed to the listener is the same value as the position).
The ArrayList, middle List, when getting the id from the object (which is retrieved via the getItem(position) method of the Adapter) successfully retrieves the correct id, the 4th parameter is the same as the position, and should not be used.
The Cursor, Right List, retrieves the correct id both via the Cursor and the 4th parameter.
The Code
MyTableObject.java :-
public class MyTableObject {
private long id;
private String name;
public MyTableObject(long id, String name) {
this.id = id;
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/*
NOTE toString method returns just the name
*/
#Override
public String toString() {
return name;
}
}
DatabaseHelper.java :-
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DBNAME = "mydb";
public static final int DBVERSION = 1;
public static final String TB_MYTABLE = "mytable";
public static final String COl_MYTABLE_ID = BaseColumns._ID; //<<<< use standard android id column name
public static final String COL_MYTABLE_NAME = "_name";
private static final String mytable_crtsql =
"CREATE TABLE IF NOT EXISTS " + TB_MYTABLE +
"(" +
COl_MYTABLE_ID + " INTEGER PRIMARY KEY, " +
COL_MYTABLE_NAME + " TEXT " +
")";
SQLiteDatabase mDB;
public DatabaseHelper(Context context) {
super(context, DBNAME, null, DBVERSION);
mDB = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(mytable_crtsql);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
public long addRow(String name) {
ContentValues cv = new ContentValues();
cv.put(COL_MYTABLE_NAME,name);
return mDB.insert(TB_MYTABLE,null,cv);
}
public ArrayList<String> getAllAsStringArrayList() {
ArrayList<String> rv = new ArrayList<>();
Cursor csr = mDB.query(
TB_MYTABLE,
null,
null,
null,
null,
null,
null
);
while (csr.moveToNext()) {
rv.add(csr.getString(csr.getColumnIndex(COL_MYTABLE_NAME)));
}
csr.close();
return rv;
}
public ArrayList<MyTableObject> getAllAsMyTableObjectArrayList() {
ArrayList<MyTableObject> rv = new ArrayList<>();
Cursor csr = mDB.query(
TB_MYTABLE,
null,
null,
null,
null,
null,
null
);
while (csr.moveToNext()) {
rv.add(new MyTableObject(
csr.getLong(csr.getColumnIndex(COl_MYTABLE_ID)),
csr.getString(csr.getColumnIndex(COL_MYTABLE_NAME))
)
);
}
csr.close();
return rv;
}
public Cursor getAllAsCursor() {
return mDB.query(
TB_MYTABLE,
null,
null,
null,
null,
null,
null
);
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
DatabaseHelper mDBHlpr;
ListView mListView01,mListVeiw02,mListView03;
ArrayAdapter<String> mAdapterStringArrayList;
ArrayAdapter<MyTableObject> mAdapterMyTableObjectArrayList;
SimpleCursorAdapter mAdapterCursor;
ArrayList<String> mMyTableListAsStrings;
ArrayList<MyTableObject> mMyTableAsObjects;
Cursor mMyTableListAsCursor;
Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
mListView01 = this.findViewById(R.id.listview01);
mListVeiw02 = this.findViewById(R.id.listview02);
mListView03 = this.findViewById(R.id.listview03);
mDBHlpr = new DatabaseHelper(this);
mDBHlpr.addRow("Fred");
mDBHlpr.addRow("Bert");
mDBHlpr.addRow("Harry");
mDBHlpr.addRow("Fred");
//String Array List
mMyTableListAsStrings = mDBHlpr.getAllAsStringArrayList();
mAdapterStringArrayList = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
mMyTableListAsStrings
);
mListView01.setAdapter(mAdapterStringArrayList);
//Object Array List
mMyTableAsObjects = mDBHlpr.getAllAsMyTableObjectArrayList();
mAdapterMyTableObjectArrayList = new ArrayAdapter<>(
this,
android.R.layout.simple_list_item_1,
mMyTableAsObjects
);
mListVeiw02.setAdapter(mAdapterMyTableObjectArrayList);
// Cursor
mMyTableListAsCursor = mDBHlpr.getAllAsCursor();
mAdapterCursor = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_1,
mMyTableListAsCursor,
new String[]{DatabaseHelper.COL_MYTABLE_NAME},
new int[]{android.R.id.text1},
0
);
mListView03.setAdapter(mAdapterCursor);
mListView01.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
String name = mAdapterStringArrayList.getItem(position);
Toast.makeText(
mContext,
"Name is " + name +
". ID is " + String.valueOf(id) +
" (note may not match)",
Toast.LENGTH_SHORT
).show();
}
});
mListVeiw02.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
MyTableObject mytable = mAdapterMyTableObjectArrayList.getItem(position);
String name = mytable.getName();
long id_in_object = mytable.getId();
Toast.makeText(
mContext,
"Name is " + name +
". ID from object is " + String.valueOf(id_in_object) +
". ID from adapter is " + String.valueOf(id),
Toast.LENGTH_SHORT
).show();
}
});
mListView03.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Cursor csr = mAdapterCursor.getCursor(); // already positioned
String name = csr.getString(csr.getColumnIndex(DatabaseHelper.COL_MYTABLE_NAME));
long id_in_cursor = csr.getLong(csr.getColumnIndex(DatabaseHelper.COl_MYTABLE_ID));
Toast.makeText(
mContext,
"Name is " + name +
". ID from object is " + String.valueOf(id_in_cursor) +
". ID from adapter is " + String.valueOf(id),
Toast.LENGTH_SHORT
).show();
}
});
}
}
I'm making a to do list application, i made a SQLite database and linked it with my app and everything seems to work pretty fine except for the data in the array, they get over each other while creating a new item, like when i set a first task (Study) and a second task (Research) it creates two different items each of them has the name (StudyResearch)... here is my code with the base adapter, cursor, and inflater.
class MyCustomAdapter extends BaseAdapter
{
ArrayList<ListItem> Items=new ArrayList<ListItem>();
MyCustomAdapter(ArrayList<ListItem> Items ) {
this.Items=Items;
}
#Override
public int getCount() {
return (int) DatabaseUtils.queryNumEntries(db, "tasks");
}
#Override
public String getItem(int position) {
return Items.get(position).Name;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
String[] cols = {"id", "name", "time", "date"};
Cursor pointer = db.query("tasks", cols, null,null,null,null,null);
String name = "";
String time = "";
String date = "";
//String data = "";
while (pointer.moveToNext()){
name += pointer.getString(1);
time += pointer.getString(2);
date += pointer.getString(3);
//data += pointer.getInt(0) + " - " + pointer.getString(1) + " - " + pointer.getInt(2) +" - " + pointer.getInt(3);
}
LayoutInflater linflater =getLayoutInflater();
View view1=linflater.inflate(R.layout.row_view, null);
final CheckedTextView tvTasks =(CheckedTextView) view1.findViewById(R.id.tvTasks);
CheckedTextView tvDesc =(CheckedTextView) view1.findViewById(R.id.tvDesc);
tvTasks.setText(name);
tvDesc.setText(date + "(" + time + ")"); //date + "(" + time + ")"
tvTasks.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tvTasks.toggle();
}
});
return view1;
}
The issue you have is that your are traversing all of the data in the cursor combined with += is concatenating the data retrieved.
Rather what you want to do is position to the appropriate row in the cursor and get the data just from that row (not that I'd recommend this way as a CursorAdapter is better suited).
So instead of :-
while (pointer.moveToNext()){
name += pointer.getString(1);
time += pointer.getString(2);
date += pointer.getString(3);
}
You could use :-
if (pointer.moveToPosition(i)){
name = pointer.getString(1);
time = pointer.getString(2);
date = pointer.getString(3);
}
This does assume that the the order in which the pointer cursor and the source array were built is identical.
We can show all records in the DB no issue. When we try to limit the items to show with a sql Select the search and the RecyclerView Adapter populates correctly.
The code fails when the item is selected in the list view. The list view did not get the message about what position this record is at so the view when we navigate to the DetailActivity view from ListActivity is not the item in the ListView
My question is how to manage the position variable that the Adapter is using?
This code flow is as follows a button click on MainActivity sets the search variable goes to ListActivity that makes a call to DBHelper which returns to ListActivity with modelList which is and Array List Yes the design is MVP so we have a Model Class relevant code below
Main Activity btn Click
public void findAllData(View view){
selectSTRING = etFromDate.getText().toString();
Intent intent = new Intent( MainActivity.this, ListActivity.class );
startActivity( intent );
}
ListActivity call to DBHelper commented out line gets all data
helpher = new DBHelper(this);
dbList = new ArrayList<>();
dbList = helpher.getRangeDataFromDB();
//dbList = helpher.getDataFromDB();
DBHelper code to grab the selected record or records eventually
public List<DBModel> getRangeDataFromDB() {
List<DBModel> modelList = new ArrayList<>();
db = this.getReadableDatabase();
String query = "SELECT * FROM " + TABLE_INFO + " WHERE " + Col_PURCHASE_DATE + " ='" + selectSTRING + "'";
Cursor cursor = db.rawQuery(query, null);
//Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_INFO + " WHERE " + Col_PURCHASE_DATE + "='" + str + "'" , null);
String newBACK = selectSTRING;
if (cursor.moveToFirst()) {
DBModel model = new DBModel();
while (!cursor.isAfterLast()) {
if (newBACK == selectSTRING) {
model.setRowid(cursor.getString(0));
model.setStation_Name(cursor.getString(1));
model.setDate_of_Purchase(cursor.getString(2));
model.setGas_Cost(cursor.getString(3));
modelList.add(model);
cursor.moveToNext();
}
}
}
int sz = modelList.size();
System.out.println("========= SIZE "+sz);
db.close();
return modelList;
}
Now we use an intent to go to DetailsActivity and this is the fail
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
static List<DBModel> dbList;
static private Context context;
RecyclerAdapter(Context context, List<DBModel> dbList) {
RecyclerAdapter.dbList = new ArrayList<>();
RecyclerAdapter.context = context;
RecyclerAdapter.dbList = dbList;
}
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row, null);
// create ViewHolder
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerAdapter.ViewHolder holder, int position) {
holder.rowid.setText(dbList.get(position).getRowid());
holder.station.setText(dbList.get(position).getStation_Name());
System.out.println("========== new position "+position);
}
#Override
public int getItemCount() {
return dbList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView station, rowid;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
rowid = (TextView) itemLayoutView.findViewById(R.id.rvROWID);
station = (TextView) itemLayoutView.findViewById(R.id.rvSTATION);
// Attach a click listener to the entire row view
itemLayoutView.setOnClickListener(this);
}
#Override // When an item in DetailsActivity is touched (selected) the RecyclerView has
// a OnClickListener attached in the above Code that implements the method below
public void onClick(View v) {
System.out.println("======RowID "+rowid);
Intent intentN = new Intent(context, DetailsActivity.class);
Bundle extras = new Bundle();
extras.putInt("POSITION", getAdapterPosition());
extras.putString("FROM_LIST_ACTIVITY", "false");
///position = getAdapterPosition();
///position = getLayoutPosition();// Both work the same
intentN.putExtras(extras);
context.startActivity(intentN);
}
}
Thought about sending the data back from the DBHelper not sure how to write an Intent in that Class. This is turning into spaghetti code!
The solution to this issue is the developer had multiple search designs in the DBHelper each being triggered by different buttons on the search Activity this design in the DBHelper lead to multiple ArrayLists all with the same name this drove the RecycleAdapter crazy as it is bound to ArrayList so OLD Mr. Boolean to the rescue! Here is the revised design code features
In the Search Activity declare public static Boolean use = false;
and Import where needed import static com..MainActivity.use;
Here is the code for each search button
public void findAllData(View view){
helper = new DBHelper(this);
helper.getDataFromDB();
use = false;
// Set Mr. Boolean
Intent intent = new Intent( MainActivity.this, ListActivity.class );
// ListActivity shows Results of the Search
startActivity( intent );
}
public void findSelect(View v){
selectSTRING = etFromDate.getText().toString();
// Get your Search variable
helper = new DBHelper(this);
helper.getDataFromDB();
etToDate.setText(sendBACK);
use = true;
Intent intent = new Intent( MainActivity.this, ListActivity.class );
startActivity( intent );
}
Now we do the desired Search in DBHelper
/* Retrive ALL data from database table named "TABLE_INFO" */
public List<DBModel> getDataFromDB(){
//String query = "SELECT * FROM " + TABLE_INFO + " WHERE " + Col_PURCHASE_DATE + " > 0 " + " ORDER BY " + Col_ID + " DESC ";
/* Notice the SPACES before AND after the words WHERE ORDER BY ASC or DESC most of all the condition " > 0 "*/
/* =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=*/
Cursor cursor = null;
List<DBModel> modelList = new ArrayList<>();
if(use == true){
String query = "SELECT * FROM " + TABLE_INFO + " WHERE " + Col_PURCHASE_DATE + " ='" + selectSTRING + "'";
db = this.getWritableDatabase();
cursor = db.rawQuery(query,null);
}
if(use == false){
String query = "SELECT * FROM " + TABLE_INFO;
db = this.getWritableDatabase();
cursor = db.rawQuery(query,null);
}
if (cursor.moveToFirst()){
do {
DBModel model = new DBModel();
model.setRowid(cursor.getInt(0));
model.setStation_Name(cursor.getString(1));
model.setDate_of_Purchase(cursor.getString(2));
model.setGas_Cost(cursor.getString(3));
modelList.add(model);
int sz = modelList.size();
int out = model.setRowid(cursor.getInt(0));
String out1 = model.setStation_Name(cursor.getString(1));
String out2 = model.setDate_of_Purchase(cursor.getString(2));
String out3 = model.setGas_Cost(cursor.getString(3));
System.out.println("==============getDataFromDB ID "+out);
System.out.println("==============getDataFromDB Station "+out1);
System.out.println("==============getDataFromDB Date "+out2);
System.out.println("==============getDataFromDB Cost "+out3);
System.out.println("======= ======getDataFromDB SIZE "+sz);
}while (cursor.moveToNext());
}
db.close();
cursor.close();
return modelList;
}
The only stumble with this is that if if you do a search by date and do an add to the DB and jump back to the ListActivity the new record is not displayed
We are working on this Stay Tuned ha ha Good Job James_Duh
You should set your OnClickListener here :
#Override
public void onBindViewHolder(ReportAdapter.ViewHolderReport holder, int position) {
final Object object = objects.get(position);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do Something with the object at this position
}
});
}
instead of your ViewHolder because you shouldn't trust the adapter position at a time.
I am new to android programming so apologies for any misuse of technical jargon. I have a spinner which has a text value of league_name and an id of id from the leagues SQLite table.
Example of leagues table design
id | league_name
-----------------
1 | Northern Premier Division
2 | Southern League 1
3 | Northern Division 2
I also have a teams table storing information on a team and a lookup table joining the id's of the teams and leagues table called teams_vs_leagues. So the selected value of this spinner gets inserted into the league_id column in the teams_vs_leagues table. I have an edit page to edit an individual teams record, which includes selecting a league from the spinner. However it always defaults to first available id in this case 1. Although, I want the initial value of the spinner to be the selected league_id in the teams_vs_leagues which corresponds to the team_id you are currently viewing. So if the selected team_id had a league_id of 3 I want the initial value of the spinner to be Northern Division 2.
UpdateTeam Class
public class UpdateTeam extends AppCompatActivity {
ArrayList < Team > imageArry = new ArrayList < Team > ();
TeamUpdateAdapter adapter;
Button updateButton;
DatabaseHelper myDb;
EditText teamNameEdit;
ImageView teamImage;
Spinner league; //Create Spinner Variables to cast in OnCreate method
ArrayList < String > leagues = new ArrayList < String > (); //Create Array List to bind to Spinner
ArrayAdapter < String > arrayAdapter; //Declare Array Adapter
long leagueId; //Declare global long for league_id
long id; //Declare global long for team_id
String picturePath = ""; //Create String variable for image path to be stored in db table
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_team);
myDb = new DatabaseHelper(this);
updateButton = (Button) findViewById(R.id.btnUpdate);
//Call Spinner Variable and cast spinner id reference
league = (Spinner) findViewById(R.id.edit_league_id);
//Call Array Adapter to Bind Array list data to Spinner
arrayAdapter = new ArrayAdapter < String > (this, android.R.layout.simple_list_item_1, leagues);
//get selected teams values from intent
id = getIntent().getLongExtra("TEAM", 0 l);
final String editTeamName = getIntent().getStringExtra("TEAM_NAME");
picturePath = getIntent().getStringExtra("IMAGE");
leagueId = getIntent().getLongExtra("LEAGUE_ID", 01);
//Toast.makeText(getBaseContext(), "Leagueid = " + leagueId, Toast.LENGTH_LONG).show();
teamNameEdit = (EditText) findViewById(R.id.eTeamName);
teamNameEdit.setText(editTeamName, TextView.BufferType.EDITABLE);
// Reading all teams from database
final List < Team > team = myDb.getTeam((int) id);
for (Team tm: team) {
String log = "ID:" + tm.getId() + " Team Name: " + tm.getTeamName() + " ,Image: " + tm.getPath() + " ,Points: " + tm.getPoints() + " ,League Name: " + tm.getLeagueName() + " ,League ID: " + tm.getLeagueId();
// Writing teams to log
Log.d("Result: ", log);
//add teams data in arrayList
imageArry.add(tm);
}
adapter = new TeamUpdateAdapter(this, R.layout.update_team,
imageArry);
ListView dataList = (ListView) findViewById(R.id.main_list_view);
dataList.setAdapter(adapter);
//call loadSpinnerData method
loadSpinnerData();
//call updateTeam
updateTeam();
//call selectLeague
selectLeague();
}
private void loadSpinnerData() {
// Spinner Drop down elements
List < Leagues > leagueList = myDb.getAllLeagues();
// Creating adapter for spinner
ArrayAdapter < Leagues > adapter = new ArrayAdapter < Leagues > (this,
android.R.layout.simple_spinner_item, leagueList);
// Drop down layout style - list view with radio button
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
league.setAdapter(adapter);
}
public void selectLeague() {
//set onItemSelected Listener for spinner
league.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView < ? > parent, View view, int position, long id) {
//get selected league id
leagueId = Integer.parseInt(String.valueOf(((Leagues) league.getSelectedItem()).getId()));
}
#Override
public void onNothingSelected(AdapterView < ? > parent) {
}
});
}
//Create addTeam method to add new team to db
public void updateTeam() {
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (myDb.updateTeam(
id,
teamNameEdit.getText().toString(),
picturePath,
leagueId)) {
Toast.makeText(getBaseContext(), "Update successful.", Toast.LENGTH_LONG).show();
Intent intent =
new Intent(UpdateTeam.this, DisplayTeam.class);
startActivity(intent);
} else
Toast.makeText(getBaseContext(), "Update failed.", Toast.LENGTH_LONG).show();
}
});
}
}
Leagues Class
public class Leagues {
//Declare Global String & int
private int id;
private String leagueName;
/*********** Set Methods ******************/
public Leagues(int id, String leagueName) {
this.id = id;
this.leagueName = leagueName;
}
public void setId(int id) {
this.id = id;
}
public void setLeagueName(String leagueName) {
this.leagueName = leagueName;
}
/*********** Get Methods ****************/
public int getId() {
return this.id;
}
public String getLeagueName() {
return this.leagueName;
}
//Provides string value to display in Spinner
#Override
public String toString() {
return leagueName;
}
}
getAllLeagues method
public List < Leagues > getAllLeagues() {
List < Leagues > labels = new ArrayList < Leagues > ();
// Select All Query
String selectQuery = "SELECT * FROM " + LEAGUES_TABLE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(new Leagues(cursor.getInt(0), cursor.getString(1)));
} while (cursor.moveToNext());
}
// closing connection
cursor.close();
db.close();
// returning labels
return labels;
}
If you need any further information, do not hesitate to leave a comment. Any help would be appreciated.
Provide the selected league object to getPosition() method of the array adapter
int index = arrayAdapter.getPosition(SELECTED_LEAGUE_ID);
league.setSelection(index);
I have a HashMap
HashMap<String, Integer> map = new HashMap<String, Integer>();
in the map there are some value. I want to get the value one by one and add it in listview. The value which is in map are
{Intent { cmp=Bluetooth/300 }=300, Intent { cmp=Audio/400 }=400,
Intent { cmp=Video/500 }=500, Intent { cmp=Display/100 }=100, Intent {
cmp=WiFi/200 }=200}
There are two textview in the listview.
And I want to be display in listview as
Display 100
WiFi 200
Bluetooth 300.
Now I public my Adapter Class which will be helpful to you...
private class NewAdapter extends BaseAdapter {
public NewAdapter(IntentTestingActivity intentTestingActivity,
HashMap<String, Integer> map) {
}
#Override
public int getCount() {
Log.d(TAG, "Map size is: " + map.size());
return map.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
View v = view;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.class_name, null);
}
TextView className = (TextView) v.findViewById(R.id.name);
TextView tagName = (TextView) v.findViewById(R.id.tag_name);
Integer key_name;
key_name = map.get(name);
Log.d(TAG, "Complete map is: " + map.toString());
// String tag = map.get(tagName).toString();
// Integer name = map.get(className);
String keyName;
keyName = map.toString();
Log.d(TAG, "KeyName is: " + map.get(tag));
for (int i = 0; i < map.size(); ++i)
Log.d(TAG, "Tag is: " + tag + " and Name is: " + name + " and Intent is: "+intent);
HashMap<String, Integer> hashmap = map;
for (Entry<String, Integer> e : hashmap.entrySet()) {
String key = e.getKey();
int value = e.getValue();
Set<String>keyname = map.keySet();
Log.d(TAG, "Key: " + key+ " Value: "+value);
}
className.setText(name.toString());
// tagName.setText(keyName);
return v;
}
}
Where name is a just String in which holding all keyValue, such as Display, Vedio ect.
Thanx in advance...
You can create a POJO class with getter-setter and set the key and value to that class.
List<POJO> list = new ArrayList<POJO>();
Iterator<Entry<String, Integer>> iterator = map.entrySet().iterator();
Entry< String, Integer> entry;
while(iterator.hasNext()){
POJO obj = new POJO();
entry = iterator.next();
Log.d("Key Value",entry.getKey()+" "+entry.getValue());
obj.setKey(entry.getKey());
obj.setValue(entry.getValue());
list.add(obj);
}
And then set this list to your Adapter class. This is will be an easy way.
Build a custom Adapter that uses your HashMap and...
Whenever you want to do processing with the views in a ListView you
need to create a custom adapter that will handle your logic
implementation and pass that information to the views as necessary.
Seems like you are showing both values together as a single string, so you may achieve this by simply doing in this way:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.id.text1);
for(String key : map.keySet()){
adapter.add(key + " " + map.get(key));
}
yourListView.setAdapter(adapter);