Running two methods inside onClick - android

I have two methods that I want to run inside my onlick. The first method is to display a ListView. The second method is to get data from a previous ListViewand put it in the new ListView. The aim is to have all these data combined and displayed in the new ListView.
Summary
Display ListView B
Get data from ListView A
Display all Data
Code
btnSave2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
PlayerStatsDatabase db = new PlayerStatsDatabase(getApplicationContext());
db.open();
db.createStats(txtGoalsScored.getText().toString(), txtMinutesPlayed.getText().toString(),txtSubstituteIn.getText().toString(),txtSubstituteOut.getText().toString(), checkText.toString());
db.close();
displayListView();
dipsplayPlayerName();
}
});
}
private void displayListView() {
// TODO Auto-generated method stub
//playerTitle.setText (PlayerNameText);
Cursor cursor = dbHelper.fetchAllStats();
setContentView(R.layout.playerstats);
// The desired columns to be bound
String[] columns = new String[] {
PlayerStatsDatabase.KEY_SCORE,
PlayerStatsDatabase.KEY_MINUTES,
PlayerStatsDatabase.KEY_SUBIN,
PlayerStatsDatabase.KEY_SUBOUT,
PlayerStatsDatabase.KEY_BOOKING,
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.pGoals,
R.id.pMinutes,
R.id.pSubIn,
R.id.pSubOut,
R.id.pBook,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
statsAdapter = new SimpleCursorAdapter(
this, R.layout.statslist,
cursor,
columns,
to
);
ListView list= (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
list.setAdapter(statsAdapter);
statsAdapter.notifyDataSetChanged();
}
private void dipsplayPlayerName() {
setContentView (R.layout.statslist);
playerTitle = (TextView) findViewById (R.id.textTitle);
playerTitle.setText (PlayerData);
playerNumber = (TextView) findViewById (R.id.pNumber);
playerNumber.setText (playerNumberStr);
playerPosition = (TextView) findViewById (R.id.pPosition);
playerPosition.setText (playerPositionStr);
playerTeam = (TextView) findViewById (R.id.pTeam);
playerTeam.setText (playerTeamStr);
}
}
The problem is they both wont work at the same time. The one that gets called first is the only one that works.
How would I work my way around this? Could putting them all in the same method work?

Related

How to pass the data in the database to a spinner

I'm creating a method to read all the information in the database and view it through a spinner here is the code i tried for this function
public Spinner loadArtist(){
SQLiteDatabase DB = getReadableDatabase();
String[] projection = {
ArtistMaster.Artist.ARTIST_NAME};
Cursor cursor = DB.query(
ArtistMaster.Artist.TABLE_ARTIST,
projection,
null,
null,
null,
null,
null);
Spinner itemIds = new ArrayList<>();
while(cursor.moveToNext()) {
long itemId = cursor.getLong(
cursor.getColumnIndex(ArtistMaster.Artist.ARTIST_NAME));
itemIds.setAdapter(itemId);
}
cursor.close();
return itemIds;
}
but it gives me an error in this line Spinner itemIds = new ArrayList<>();
Should i declare it as a list instead of spinner
itemIds should be defined as an ArrayList<Long>. A Spinner is a UI element and an ArrayList is a data structure. You will most likely need to map the data to your UI using an adapter of some sort, eg. an ArrayAdapter:
Spinner spinner = ... // findViewById, new Spinner() etc.
ArrayList<Long> itemIds = new ArrayList<>();
//... fill array with artist IDs
spinner.setAdapter(
new ArrayAdapter(
this, // Context, Activity etc.,
android.R.layout.simple_list_item_1, // Spinner TextView item resource ID
itemIds // Data set.
));
By default, ArrayAdapter will call Object#toString() on each data object in the collection.
I'd suggest that it would be easier if you used a Cursor Adpater as they are designed to be used with a Cursor and there is no need to generate arrays.
SimpleCursorAdapter being that, a simple but still pretty flexible adapter for use with Cursors.
The only issue is that a Cursor Adapter requires a column name specifically _id (BaseColumns._ID resolves to this (as used below)).
First have the following member variables (obviously names can be what you wish)
:-
Cursor mCursor;
SimpleCursorAdapter mAdapter;
Spinner spinner;
SQLiteDatabase db;
In the onCreate Method of the activity have
:-
spinner = this.findViewById(R.id.?????); //
db = ???????? (as per your existing code)
manageSpinner();
Have a method
:-
private void manageSpinner() {
mCursor = db.query(
ArtistMaster.Artist.ARTIST_NAME,
new String[]{"*","rowid AS " + BaseColumns._ID}, //<<<<<<<< adds _ID column (unless the table is a WITHOUT ROWID table, pretty unlikely)
null,null,null,null,null
);
if (mAdapter == null) {
mAdapter = new SimpleCursorAdapter(
this,
android.R.layout.simple_list_item_1,
mCursor,
new String[]{"the_column"}, // column(s) from which to extract data
new int[]{android.R.id.text1}, // layout views into which the data is placed
0
);
spinner.setAdapter(mAdapter);
// You want want to do something when an Item in the spinner is clicked (this does nothing as it is)
spinner.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//........... do your stuff here
// notes
// id will be the id of the row
// cursor will be positioned, so you can access data from the cursor if needed
}
});
} else {
mAdapter.swapCursor(mCursor);
}
}
Override the activity's onResume (refresh the spinner when returning to activity as underlying data may have changed) and onDestroy (to close the Cursor) methods using
:-
#Override
protected void onDestroy() {
super.onDestroy();
mCursor.close();
}
#Override
protected void onResume() {
super.onResume();
manageSpinner();
}

Retrieve values from database and launch a new activity when listview item is clicked

I created a listview using an adapter. The list view contains elements retrieved from a SQLite database using a distinct query.
When the listview item is clicked, it should retrieve all items which have that value used to do the distinct query.
My query looks like this:
#Override
public List<Registro> distinctByCol3(){
List aux = new ArrayList();
Cursor cursor = db.query(true,Registro.TABLE_NAME,new String[]{
BaseColumns._ID,
RegistroColumns.Col1,
RegistroColumns.Col2,
RegistroColumns.Col3,
},null,null,RegistroColumnas.Col3,null,null,null);
if (cursor.moveToFirst())
do {
Registro registro = this.parseCursorToR(cursor);
if (registro != null)
aux.add(registro);
}
while (cursor.moveToNext()) ;
if(!cursor.isClosed()){
cursor.close();
}
return aux;
}
The java class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_registros);
final ListView listView = (ListView) findViewById(R.id.lvRegistros);
DataManager servicio = new DataManagerImpl(this);
List<Registro> listRM = service.getRegistroDistinctedByCol3();
final ArrayAdapter<Registro> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listRM);
listView.setAdapter(adapter);
After click in the element, I need to launch a new activity and show all the elements whit COL3, which is the value I used in my query.
How can I achieved my goal?
If some clarification is needed, let me know. Thanks.

How to run two different methods with different content views to display data at the same time?

I have two methods that I want to run inside my onlick. The first method is to display a ListView. The second method is to get data from a previous ListViewand put it in the new ListView. The aim is to have all these data combined and displayed in the new ListView at the same time.
Summary
Display ListView B
Get data from ListView A
Display all Data at the same time
Code
btnSave2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
PlayerStatsDatabase db = new PlayerStatsDatabase(getApplicationContext());
db.open();
db.createStats(txtGoalsScored.getText().toString(), txtMinutesPlayed.getText().toString(),txtSubstituteIn.getText().toString(),txtSubstituteOut.getText().toString(), checkText.toString());
db.close();
displayListView();
dipsplayPlayerName();
}
});
}
private void displayListView() {
// TODO Auto-generated method stub
//playerTitle.setText (PlayerNameText);
Cursor cursor = dbHelper.fetchAllStats();
setContentView(R.layout.playerstats);
// The desired columns to be bound
String[] columns = new String[] {
PlayerStatsDatabase.KEY_SCORE,
PlayerStatsDatabase.KEY_MINUTES,
PlayerStatsDatabase.KEY_SUBIN,
PlayerStatsDatabase.KEY_SUBOUT,
PlayerStatsDatabase.KEY_BOOKING,
};
// the XML defined views which the data will be bound to
int[] to = new int[] {
R.id.pGoals,
R.id.pMinutes,
R.id.pSubIn,
R.id.pSubOut,
R.id.pBook,
};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
statsAdapter = new SimpleCursorAdapter(
this, R.layout.statslist,
cursor,
columns,
to
);
ListView list= (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
list.setAdapter(statsAdapter);
statsAdapter.notifyDataSetChanged();
}
private void dipsplayPlayerName() {
setContentView (R.layout.statslist);
playerTitle = (TextView) findViewById (R.id.textTitle);
playerTitle.setText (PlayerData);
playerNumber = (TextView) findViewById (R.id.pNumber);
playerNumber.setText (playerNumberStr);
playerPosition = (TextView) findViewById (R.id.pPosition);
playerPosition.setText (playerPositionStr);
playerTeam = (TextView) findViewById (R.id.pTeam);
playerTeam.setText (playerTeamStr);
}
}
The problem is they both wont work at the same time. The one that gets called first is the only one that works.
How would I fix this?

android nullpointerexception in function

I'm new to Java/android so a lot of these terms are foreign but am willing to learn. I'm not gonna go into detail on the app as I dont think it's relevant. My issue as it stands, I've used tutorials and pieces of code from a blog and have gotten my code to work. Trying to clean up and organize my code I get a nullpoiner exception when I move one line (creating my autocompletetextview). Below is the code I've used. My 1 line of code that's giving me an issue is
AutoCompleteTextView companyAutoComplete = (AutoCompleteTextView) addAddressDialog.findViewById(R.id.add_record_dialog_autocomplete);
When I move it to right under the start of my function it errors out but when left in place it works like a charm. I'd like to understand why this is.
public void addAddress() {
final Dialog addAddressDialog = new Dialog(this);
final int[] to = new int[] { android.R.id.text1 };
final String[] from = new String[] { "CompanyName" };
// Create a SimpleCursorAdapter for the CompanyName field.
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout. select_dialog_item, null, from, to);
addAddressDialog.setContentView(R.layout.add_record_dialog);
addAddressDialog.setTitle(getString(R.string.add_record_dialog_address_title));
addAddressDialog.setCancelable(true);
final EditText text1 = (EditText) addAddressDialog.findViewById(R.id.add_record_dialog_edittext);
text1.setHint(getString(R.string.add_record_dialog_company_hint));
Button buttonOK1 = (Button) addAddressDialog.findViewById(R.id.add_record_dialog_ok);
buttonOK1.setText(getString(R.string.add_record_dialog_ok_button));
Button buttonCancel1 = (Button) addAddressDialog.findViewById(R.id.add_record_dialog_cancel);
buttonCancel1.setText(getString(R.string.add_record_dialog_cancel_button));
buttonOK1.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
Bundle addressBundle = new Bundle();
addressBundle.putString("CompanyName", text1.getText().toString());
Intent intent = new Intent(MenuActivity.this, AddAddressActivity.class);
intent.putExtras(addressBundle);
startActivity(intent);
addAddressDialog.dismiss();
}
});
buttonCancel1.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
Toast.makeText(getBaseContext(), "Cancel button clicked", Toast.LENGTH_SHORT).show();
addAddressDialog.dismiss();
}
});
AutoCompleteTextView companyAutoComplete = (AutoCompleteTextView) addAddressDialog.findViewById(R.id.add_record_dialog_autocomplete);
companyAutoComplete.setAdapter(adapter);
// Set an OnItemClickListener, to update dependent fields when
// a choice is made in the AutoCompleteTextView.
companyAutoComplete.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
// Get the cursor, positioned to the corresponding row in the
// result set
Cursor cursor = (Cursor) listView.getItemAtPosition(position);
// Get the CompanyID from this row in the database.
String companyID = cursor.getString(cursor.getColumnIndexOrThrow("_id"));
// test to make sure CompanyID returned
Toast.makeText(getBaseContext(), companyID, Toast.LENGTH_SHORT).show();
}
});
// Set the CursorToStringConverter, to provide the labels for the
// choices to be displayed in the AutoCompleteTextView.
adapter.setCursorToStringConverter(new CursorToStringConverter() {
public String convertToString(android.database.Cursor cursor) {
// Get the label for this row out of the "CompanyName" column
final int columnIndex = cursor.getColumnIndexOrThrow("CompanyName");
final String str = cursor.getString(columnIndex);
return str;
}
});
// Set the FilterQueryProvider, to run queries for choices
// that match the specified input.
adapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
Cursor cursorReturn = dbAdapter.getCompanies(constraint != null ? constraint.toString() : null);
startManagingCursor(cursorReturn);
return cursorReturn;
}
});
addAddressDialog.show();
}
This happens because you call setContentView later.
setContentView sets up the layout for the addAddressDialog dialog. If you don't call setContentView, it has no layout items, therefore addAddressDialog.findViewById(...); will be null, and, obviously you cannot cast that to anything, nor can you call setHint on it.
It shouldn't matter where this line of code is in your method, as long as your line with setContentView is called before it.
The only thing that matters is that your findViewById() call is called after the call to setContentView(), i.e. this line:
addAddressDialog.setContentView(R.layout.add_record_dialog);
The XML file add_record_dialog.xml is the View hierarchy that you are traversing to find the view with the ID of add_record_dialog_autocomplete. Until you've given the dialog that view hierarchy, it cannot traverse it, hence you'll be getting a NullPointerException when you try to use your AutoCompleteTextView since it cannot find your view.
EDIT: Also, if you mean you placed it at the VERY start of the method, that will also fail due to the fact that addAddressDialog will be null until your call to
final Dialog addAddressDialog = new Dialog(this);

Populate ListView with Dynamic Array

I have a EditText box so a user can input names and then click the Add button and the name saves to the array playerList and clears the box so another name can be added.
I also have a ListView on the same Activity which will then be populated by the names in the Array playerList. The problem is that the ListView dosen't seem to be populated.
So I tried with a defualt set String teststring which you can see below and that populates the ListView fine. My question is how come it isn't working with the Array playerList maybe its not saving to the Array correctly?
Update just need adapter.notifyDataSetChanged(); adding to refresh the ListView Credit to #Lalit Poptani and #Jave
ArrayList<String> playerList = new ArrayList<String>();
ListView listview;
protected String[] teststring = {"Name 1", "Name 2"};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.addremove);
ListAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, teststring);
ListView employeeList = (ListView) findViewById(R.id.namelistview);
employeeList.setAdapter(adapter);
Button confirm = (Button) findViewById(R.id.add);
confirm.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
EditText playername = (EditText) findViewById(R.id.userinput);
String name = playername.getText().toString();
playerList.add(name);
playername.setText("");
}});
To refresh the ListView after you add new data to it you have to call adapter.notifyDataSetChanged(). This is refresh your ListView will new data.
But in your case you are populating your ListView with String[] so it won't work dynamically you will have to give the size of the String[]. So, I will suggest you to populate your ListView with ArrayList itself for adding the content dynamically.
ListAdapter adapter = new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1,playerList);
You should call adapter.notifyDataSetChanged() after adding new items to make it update with the new data.
Notifies the attached observers that the underlying data has been
changed and any View reflecting the data set should refresh itself.

Categories

Resources