These are the methods of spinners
mSpinnerModel.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedModel = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), "Selected Model: " + selectedModel, Toast.LENGTH_LONG).show();
String sp1 = String.valueOf(mSpinnerModel.getSelectedItem());
if (sp1.contentEquals("College1")) {
List<String> list = new ArrayList<String>();
list.add("MAHARANI UNIVERSITY ");
//list.add("MANIPAL ");
// list.add("ITM UNIVERSITY ");
// list.add("UNIVERSITY1");
// list.add("MAHARANI UNIVERSTY");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dataAdapter.notifyDataSetChanged();
// selectedMake = parent.getItemAtPosition(position).toString();
mSpinnerMake.setAdapter(dataAdapter);
}
if (sp1.contentEquals("College2")) {
List<String> list1 = new ArrayList<String>();
list1.add("ITM UNIVERSITY");
//list1.add("UNIVERSITY2");
// list1.add("UNIVERSITY3");
// selectedMake = parent.getItemAtPosition(position).toString();
ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, list1);
dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dataAdapter2.notifyDataSetChanged();
mSpinnerMake.setAdapter(dataAdapter2);
}
if (sp1.contentEquals("College3")) {
List<String> list = new ArrayList<String>();
list.add("MANIPAL ");
//list.add("UNIVERSITY4");
//list.add("UNIVERSITY5");
ArrayAdapter<String> dataAdapter3 = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, list);
dataAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dataAdapter3.notifyDataSetChanged();
mSpinnerMake.setAdapter(dataAdapter3);
// selectedMake = parent.getItemAtPosition(position).toString();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
mSpinnerMake.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedMake = parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
mSpinnerYear.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
selectedYear = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "Selected Year: " + selectedYear, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
mButtonShow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String eligibleBattery=fetchEligibleBattery(mSqLiteDatabase);
mTextViewResult.setText(eligibleBattery);
}
});
}
And this is method for data and query for fetching data but it is not working. when i select data in spinners it shows in logcat but it is not fetching data the query right below is not working please help.
private String fetchEligibleBattery(SQLiteDatabase db) {
String battery="";
String SELECT_BATTERY_QUERY = "SELECT "+ DatabaseConstants.KEY_BATTERY+" FROM " + DatabaseConstants.TABLE_CAR_DETAILS + " WHERE " + DatabaseConstants.KEY_CAR_MAKE + " ='" +selectedMake +
"' AND "+ DatabaseConstants.KEY_CAR_MODEL +" = '"+ selectedModel+ "' AND "+ DatabaseConstants.KEY_CAR_YEAR+"= '"+selectedYear +"' ;";
Log.d("Database", "Battery Select Query : " + SELECT_BATTERY_QUERY);
Cursor cursor = db.rawQuery(SELECT_BATTERY_QUERY, null);
try {
if (cursor.moveToFirst()) {
battery=cursor.getString(cursor.getColumnIndex(DatabaseConstants.KEY_BATTERY));
}
} catch (Exception e) {
Log.d("Database", "Error while trying to get icons from database");
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
return battery;
}
public void fetchDataFromDBForSpinners(SQLiteDatabase db) {
String SELECT_MODELS_QUERY = "SELECT * FROM " + DatabaseConstants.TABLE_CAR_DETAILS + ";";
String model, make, year;
Cursor cursor = db.rawQuery(SELECT_MODELS_QUERY, null);
try {
if (cursor.moveToFirst()) {
do {
model = cursor.getString(cursor.getColumnIndex(DatabaseConstants.KEY_CAR_MODEL));
make = cursor.getString(cursor.getColumnIndex(DatabaseConstants.KEY_CAR_MAKE));
year = cursor.getString(cursor.getColumnIndex(DatabaseConstants.KEY_CAR_YEAR));
models.add(model);
makes.add(make);
years.add(year);
} while (cursor.moveToNext());
}
} catch (Exception e) {
Log.d("DATABASE", "Error while trying to get events from database");
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
This query wrong
Please check carefully my fixed code
String SELECT_BATTERY_QUERY = "SELECT "+ DatabaseConstants.KEY_BATTERY+" FROM " + DatabaseConstants.TABLE_CAR_DETAILS + " WHERE " + DatabaseConstants.KEY_CAR_MAKE + " = " +selectedMake +" AND "+ DatabaseConstants.KEY_CAR_MODEL +" = "+ selectedModel+ " AND "+ DatabaseConstants.KEY_CAR_YEAR+"= "+selectedYear ";
Related
I have two spinner in my application which populating list from sqlite and it is working fine. When I select State in first spinner then second spinner list populate depend on first spinner. Now what I want that when I select item in both spinner and then I press back and again launch the activity then the list of second spinner still there. I want to clear list of second spinner when I press back button and Populate list in second spinner when user select value in first spinner.
public void fillStateData() {
try {
ArrayList<String> state_array = new ArrayList<String>();
state_array.add("Select State");
Cursor cursor_State = db.rawQuery("SELECT nSerialNo as _id,cCodeName FROM CodeMaster where nCtgId = 6", null);
if (cursor_State.moveToFirst()) {
do {
//assing values
String stateID = cursor_State.getString(0);
String stateName = cursor_State.getString(1);
stateData = stateName;
state_array.add(stateData);
} while (cursor_State.moveToNext());
}
ArrayAdapter my_Adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, state_array);
spnState.setAdapter(my_Adapter);
cursor_State.close();
spnState.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
state = spnState.getSelectedItem().toString();
Cursor cursor = db.rawQuery("SELECT nSerialNo FROM CodeMaster where cCodeName = '" + state + "'", null);
if (cursor.moveToFirst()) {
stateCodeId = cursor.getString(0);
}
cursor.close();
fillDistrictData(stateCodeId);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
public void fillDistrictData(String stateCodeId) {
try {
district_array = new ArrayList<String>();
district_array.clear();
district_array.add("Select District");
Cursor cursor_District = db.rawQuery("SELECT nSerialNo as _id,cCodeName FROM CodeMaster where nParentSerialNo = '" + stateCodeId + "'", null);
if (cursor_District.moveToFirst()) {
do {
//assing values
String districtID = cursor_District.getString(0);
String districtName = cursor_District.getString(1);
districtData = districtName;
district_array.add(districtData);
} while (cursor_District.moveToNext());
}
district_Adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, district_array);
spnDistrict.setAdapter(district_Adapter);
cursor_District.close();
spnDistrict.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
district = spnDistrict.getSelectedItem().toString();
Cursor cursor = db.rawQuery("SELECT nSerialNo FROM CodeMaster where cCodeName = '" + district + "'", null);
if (cursor.moveToFirst()) {
do {
//assing values
districtCodeId = cursor.getString(0);
} while (cursor.moveToNext());
}
cursor.close();
fillTalukaData(districtCodeId);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
add this method to activity.Hope this will work .
#Override
public void onBackPressed() {
spnDistrict.getAdapter().clear();
spnDistrict.getAdapter().notifyDataSetChanged();
finish();
}
Try using
adapter.clear();
spinner.setAdapter(new ArrayAdapter<String>(YourActivity.this,android.R.layout.simple_dropdown_item_1line,adapter));
Use Onresume for clear the array list you want
#Override
public void onResume() {
Log.e("DEBUG", "onResume of LoginFragment");
state_array.clear();
district_array.clear();
super.onResume();
}
or in onCreate view After Inttilizing array clean both arrayList.
I am populating two spinner from sqlite. Now what I want that when my Activity is created then all state populate in spnState. But when I select any state from spinner then I want to bind District from sqlite in spnDistrict. I am getting problem when I select state after that list of district not showing in district spinner it is only showing "select district". How can I achieve that.
public void SpinnerValue(){
/*-----------------------Fill State start here----------------------------*/
try {
ArrayList<String> state_array = new ArrayList<String>();
state_array.add("Select State");
Cursor cursor_State = db.rawQuery("SELECT nSerialNo as _id,cCodeName FROM CodeMaster where nCtgId = 6", null);
if (cursor_State.moveToFirst()) {
do {
//assing values
String stateID = cursor_State.getString(0);
String stateName = cursor_State.getString(1);
stateData = stateName;
state_array.add(stateData);
} while (cursor_State.moveToNext());
}
ArrayAdapter my_Adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, state_array);
spnState.setAdapter(my_Adapter);
cursor_State.close();
spnState.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
state = spnState.getSelectedItem().toString();
Cursor cursor = db.rawQuery("SELECT nSerialNo FROM CodeMaster where cCodeName = '" + state + "'", null);
if (cursor.moveToFirst()) {
do {
//assing values
stateCodeId = cursor.getString(0);
} while (cursor.moveToNext());
}
cursor.close();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
/*-----------------------Fill District start here----------------------------*/
try {
ArrayList<String> district_array = new ArrayList<String>();
district_array.add("Select District");
Cursor cursor_District = db.rawQuery("SELECT nSerialNo as _id,cCodeName FROM CodeMaster where nParentSerialNo = '"+stateCodeId+"'", null);
if (cursor_District.moveToFirst()) {
do {
//assing values
String districtID = cursor_District.getString(0);
String districtName = cursor_District.getString(1);
districtData = districtName;
district_array.add(districtData);
} while (cursor_District.moveToNext());
}
ArrayAdapter district_Adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, district_array);
spnDistrict.setAdapter(district_Adapter);
cursor_District.close();
spnDistrict.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
district = spnDistrict.getSelectedItem().toString();
Cursor cursor = db.rawQuery("SELECT nSerialNo FROM CodeMaster where cCodeName = '" + district + "'", null);
if (cursor.moveToFirst()) {
do {
//assing values
districtCodeId = cursor.getString(0);
} while (cursor.moveToNext());
}
cursor.close();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
I have checked your code and you are setting all values in one simple method, therefore it will not take stateId to fetch districts, So just apply below two method and call first in onCreate method to resolve your issue,
Call Below method in onCreate() method
// In onCreate() method call below method
fillStateData();
public void fillStateData()
{
try {
ArrayList<String> state_array = new ArrayList<String>();
state_array.add("Select State");
Cursor cursor_State = db.rawQuery("SELECT nSerialNo as _id,cCodeName FROM CodeMaster where nCtgId = 6", null);
if (cursor_State.moveToFirst())
{
do {
//assing values
String stateID = cursor_State.getString(0);
String stateName = cursor_State.getString(1);
stateData = stateName;
state_array.add(stateData);
} while (cursor_State.moveToNext());
}
ArrayAdapter my_Adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, state_array);
spnState.setAdapter(my_Adapter);
cursor_State.close();
spnState.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
state = spnState.getSelectedItem().toString();
Cursor cursor = db.rawQuery("SELECT nSerialNo FROM CodeMaster where cCodeName = '" + state + "'", null);
if (cursor.moveToFirst()) {
stateCodeId = cursor.getString(0);
}
cursor.close();
fillDistrictData(stateCodeId);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
public void fillDistrictData(String stateCodeId)
{
try {
ArrayList<String> district_array = new ArrayList<String>();
district_array.add("Select District");
Cursor cursor_District = db.rawQuery("SELECT nSerialNo as _id,cCodeName FROM CodeMaster where nParentSerialNo = '"+stateCodeId+"'", null);
if (cursor_District.moveToFirst()) {
do {
//assing values
String districtID = cursor_District.getString(0);
String districtName = cursor_District.getString(1);
districtData = districtName;
district_array.add(districtData);
} while (cursor_District.moveToNext());
}
ArrayAdapter district_Adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, district_array);
spnDistrict.setAdapter(district_Adapter);
cursor_District.close();
spnDistrict.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
district = spnDistrict.getSelectedItem().toString();
Cursor cursor = db.rawQuery("SELECT nSerialNo FROM CodeMaster where cCodeName = '" + district + "'", null);
if (cursor.moveToFirst()) {
do {
//assing values
districtCodeId = cursor.getString(0);
} while (cursor.moveToNext());
}
cursor.close();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
I couldn't get corresponds data from list view's item.
here i am using sms and email templates. when i click on sms or any email listviews item then it will open in edit text form db and then could update data and then store. corresponding with email or sms .i create fields into db for email and sms template such as
id, template_name, message, template_code(0,1) i.e. specifies which on i'm using either sms or email.
here is three activity ManageEmailTemplate, ManageSmsTemplate that intents to next activity i.e. SMSTemplateEdit
ManageEmailTemplate.java
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.manage_email_template);
//-------------------------
dba = new MyDB(this);
dba.open();
mQuery = "Select " +
Constants.KEY_ID_GREET + "," +
Constants.GREETING_NAME + "," +
Constants.GREETING_MESSAGE+ "," +
Constants.KEY_ID_SETUP_GREET +
" from " + Constants.TABLE_NAME_GREETINGS +
" where " + Constants.KEY_ID_SETUP_GREET + " = " + Constants.EMAIL_CODE;
c = dba.getResults( mQuery );
startManagingCursor(c);
String[] resultColumns;
if( c != null && c.moveToFirst()){
}
int[] textviews = new int[] {android.R.id.text1};
resultColumns = new String[] { Constants.GREETING_NAME};
mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, c, resultColumns, textviews);
this.setListAdapter(mAdapter);
getListView().setTextFilterEnabled(true);
//dba.close();
//-------------------------
// Create Email Templates
//setup Create Email Templates Listener
Button createEmailTemplatesButton = (Button) findViewById(R.id.create_email_template_button);
createEmailTemplatesButton.setOnClickListener(new OnClickListener(){
public void onClick(View view){
showCreateEmailTemplate();
}
});
}
private void showCreateEmailTemplate(){
Intent i = new Intent(this, CreateNewTemplate.class);
i.putExtra("template_type","email");
//startActivity(i);
startActivityForResult(i, mRequestCode);
}
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id)
{
super.onItemClick(parent, v, position, id);
final Cursor c = (Cursor) mAdapter.getItem(position);
String name = c.getString(c.getColumnIndex( Constants.GREETING_NAME ));
final int template_id = c.getInt(c.getColumnIndex( Constants.KEY_ID_GREET ));
temp_id=String.valueOf(template_id);
goForEdit();
//confirm
Toast.makeText(this,
"Name :"+name+" id : " +template_id , Toast.LENGTH_LONG)
.show();
}
public void goForEdit(){
Intent launchSMSTempEdit = new Intent(
ManageEmailTemplate.this,
EmailSMSTempEdit.class);
launchSMSTempEdit.getExtras().get("selection"));
// startActivity(launchSMSTempEdit);
// Toast.makeText(this, temp_id, Toast.LENGTH_LONG).show();
// startActivity(launchSMSTempEdit);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
//now get Editor
SharedPreferences.Editor editor = sharedPref.edit();
//put your value
editor.putString("Temp_id", temp_id);
editor.putString("template_type", "email");
//commits your edits
editor.commit();
startActivity(launchSMSTempEdit);
}
}
ManageSMSTemplate.java
public class ManageSMSTemplate extends
ActionBarListActivity {
private MyDB dba;
private Cursor c;
String temp_id;
private SimpleCursorAdapter mAdapter;
private int mRequestCode = 0000;
ListView lst;
private String mQuery;
/** Called when the activity is first created. */
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState)
{
lst =(ListView)findViewById(android.R.id.list);
super.onCreate(savedInstanceState);
setContentView(R.layout.manage_sms_template);
// -------------------------
dba = new MyDB(this);
dba.open();
mQuery = "Select " + Constants.KEY_ID_GREET + ","
+ Constants.GREETING_NAME + ","
+ Constants.GREETING_MESSAGE + ","
+ Constants.KEY_ID_SETUP_GREET + " from "
+ Constants.TABLE_NAME_GREETINGS
+ " where " + Constants.KEY_ID_SETUP_GREET
+ " = " + Constants.SMS_CODE;
c = dba.getResults(mQuery);
startManagingCursor(c);
String[] resultColumns;
if (c != null && c.moveToFirst()) {
}
int[] textviews = new int[] { android.R.id.text1 };
resultColumns = new String[] { Constants.GREETING_NAME };
mAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1, c,
resultColumns, textviews);
this.setListAdapter(mAdapter);
getListView().setTextFilterEnabled(true);
// -------------------------
// Create sms Templates
// setup Create SMS Templates Listener
Button createSMSTemplatesButton = (Button) findViewById(R.id.create_sms_template_button);
createSMSTemplatesButton
.setOnClickListener(new OnClickListener() {
public void onClick(View view)
{
showCreateSMSTemplate();
}
});
}
private void showCreateSMSTemplate()
{
Intent i = new Intent(this, CreateNewTemplate.class);
i.putExtra("template_type", "sms");
startActivityForResult(i, mRequestCode);
}
#Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode,
data);
Log.v("Crash",
"Returned from template creation in SMStemplate Manager");
if (mAdapter == null)
Log.d("Crash", "SMS-Manager - mAdapter is NULL");
else
Log.d("Crash",
"SMS-Manager - mAdapter is NOT Null");
if (requestCode == mRequestCode) {
if (resultCode == RESULT_OK) {
if (mAdapter.getCursor() != null)
mAdapter.getCursor().requery();
mAdapter.notifyDataSetChanged();
}
}
}
#Override
protected void onDestroy()
{
dba.close();
super.onDestroy();
}
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id)
{
super.onItemClick(parent, v, position, id);
final Cursor c = (Cursor) mAdapter
.getItem(position);
String name = c.getString(c
.getColumnIndex(Constants.GREETING_NAME));
final int template_id = c.getInt(c
.getColumnIndex(Constants.KEY_ID_GREET));
temp_id=String.valueOf(template_id);
goForEdit();
// confirm
Toast.makeText(this,
"Name :"+name+" id : " +template_id , Toast.LENGTH_LONG)
.show();
}
public void goForEdit(){
Intent launchSMSTempEdit = new Intent(
ManageSMSTemplate.this,
EmailSMSTempEdit.class);
// Intent i = new Intent(ManageSMSTemplate.this, SMSTempEdit.class);
//i.putExtra("KeyId", temp_id.toString());
// startActivity(i);
// launchSMSTempEdit.putExtra("selection", temp_id.toString());
// Log.d("*** OUTBOUND INTENT: ", "" + launchSMSTempEdit.getExtras().get("selection"));
// startActivity(launchSMSTempEdit);
// Toast.makeText(this, temp_id, Toast.LENGTH_LONG).show();
// startActivity(launchSMSTempEdit);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
//now get Editor
SharedPreferences.Editor editor = sharedPref.edit();
//put your value
editor.putString("userName", temp_id);
editor.putString("template_type", "sms");
//commits your edits
editor.commit();
startActivity(launchSMSTempEdit);
}
}
EmailSMSTempEdit.java
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.create_template);
// sms_key_id=getIntent().getStringExtra("id");
// String sms_key_id;
// if (savedInstanceState == null) {
// Bundle extras = getIntent().getExtras();
// if(extras == null) {
// sms_key_id= null;
// } else {
// sms_key_id= extras.getString("STRING_I_NEED");
// }
// } else {
// sms_key_id= (String) savedInstanceState.getSerializable("STRING_I_NEED");
// }
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
sms_key_id = sharedPref.getString("userName", "Not Available");
mTemplateType=sharedPref.getString("template_type", "Not Available");
Toast.makeText(this, mTemplateType, Toast.LENGTH_LONG).show();
dba = new MyDB(this);
dba.open() ;
//array to hold values to show in spinner
nameTypeArr = new String[]{getString(R.string.insert_name_prompt),
getString(R.string.first_name),
getString(R.string.last_name)};
//get views from xml
mNameBox = (EditText) findViewById(R.id.template_name_box);
mSubjectBox = (EditText) findViewById(R.id.template_subject_box);
mMessageBox = (EditText) findViewById(R.id.template_message_box);
mInsertNameSpinner = (Spinner) findViewById(R.id.insert_name_here_spinner);
//create adapter for the spinner and set it
ArrayAdapter<String> mAdapter1=
new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, nameTypeArr);
mAdapter1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
mInsertNameSpinner.setAdapter(mAdapter1);
//listener for the spinner
mInsertNameSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
//if the spinner has just been created, ignore this call to onItemSelected
if(spinnerBeingCreated == true){
spinnerBeingCreated = false;
return;
}
//what item did the user click in spinner
String typeOfName = parent.getItemAtPosition(pos).toString();
//based on user choice, insert corresponding placeholder in text
if(typeOfName.equals( getString(R.string.first_name) )){
insertAtCurrentLocation( getString(R.string.first_name_placeholder) );
}else if(typeOfName.equals( getString(R.string.last_name) )){
insertAtCurrentLocation( getString(R.string.last_name_placeholder) );
}
//reset the spinner item selection back to first one
mInsertNameSpinner.setSelection(0);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {}
});
//if its a template for sms, hide the subject line
LinearLayout subjectarea = (LinearLayout) findViewById(R.id.template_subject_box_container);
if(mTemplateType.equals("sms")){
subjectarea.setVisibility(View.GONE);
} else if(mTemplateType.equals("email")){
subjectarea.setVisibility(View.VISIBLE);
}
fillData(sms_key_id);
//Save the template
//setup Save Template Listener
Button saveTemplateButton = (Button) findViewById(R.id.save_template_button);
saveTemplateButton.setOnClickListener(new OnClickListener(){
public void onClick(View view){
// saveTemplate();
updateTemplate(sms_key_id);
}
});
//Cancel
//Cancel Listener
Button cancelTemplateButton = (Button) findViewById(R.id.cancel_template_button);
cancelTemplateButton.setOnClickListener(new OnClickListener(){
public void onClick(View view){
finish();
}
});
}
public void fillData(String sms_key_id) {
Toast.makeText(EmailSMSTempEdit.this, sms_key_id, Toast.LENGTH_LONG).show();
dba.open();
String queryStr =
"Select " +
"*" + " from " +
Constants.TABLE_NAME_GREETINGS +
" where "+ Constants.KEY_ID_GREET+"=" + sms_key_id ;
//Toast.makeText(this, queryStr, Toast.LENGTH_SHORT).show();
c = dba.getResults(queryStr);
startManagingCursor(c);
if(c.moveToFirst()){
do{
mNameBox.setText(c.getString(c.getColumnIndex(Constants.GREETING_NAME)));
mMessageBox.setText(c.getString(c.getColumnIndex(Constants.GREETING_MESSAGE)));
// System.out.println(c.getString(c.getColumnIndex(Constants.KEY_ID_GREET)));
// System.out.println(c.getString(c.getColumnIndex(Constants.GREETING_NAME)));
// System.out.println(c.getString(c.getColumnIndex(Constants.GREETING_MESSAGE)));
// System.out.println(c.getString(c.getColumnIndex(Constants.KEY_ID_SETUP_GREET)));
} while(c.moveToNext());
}
}
public void updateTemplate(String sms_key_id){
String subject = mSubjectBox.getText().toString();
String name = mNameBox.getText().toString();
String message = mMessageBox.getText().toString();
dba.open();
//if name is null or empty, don't save
if(name == null || name.equals("")){
Toast.makeText(this, R.string.empty_template_name_error, Toast.LENGTH_LONG).show();
return;
}
//whether its sms or email, requied fro db query
int messageTypeCode = -1; //for sms, it is 0. For email it is 1
if(mTemplateType.equals("email")){
message = subject + subjectMessageDelimiter + message; //|~| is the delimiter
messageTypeCode = Constants.EMAIL_CODE;
} else if(mTemplateType.equals("sms")){
messageTypeCode = Constants.SMS_CODE;
}
String Stmt = "update " +
Constants.TABLE_NAME_GREETINGS +
" set "+
Constants.GREETING_NAME+"='"+name + "',"+
Constants.GREETING_MESSAGE+"='"+message + "'," +
Constants.KEY_ID_SETUP_GREET+"='"+messageTypeCode +"'" +
" where "+ Constants.KEY_ID_GREET+"=" + sms_key_id ;
dba.execute(Stmt);
dba.close();
Toast.makeText(this, "Successfully updated Template: " + name, Toast.LENGTH_LONG).show();
//finish the activity
// setResult(RESULT_OK, null);
finish();
}
#Override
protected void onDestroy(){
//dba.close();
super.onDestroy();
}
//insert at currnet cursor location in subject or message field
private void insertAtCurrentLocation(String str){
int start, end;
if(mMessageBox.hasFocus()){
start = mMessageBox.getSelectionStart();
end = mMessageBox.getSelectionEnd();
mMessageBox.getText().replace(Math.min(start, end), Math.max(start, end),
str, 0, str.length());
} else if(mSubjectBox.hasFocus()){
start = mSubjectBox.getSelectionStart();
end = mSubjectBox.getSelectionEnd();
mSubjectBox.getText().replace(Math.min(start, end), Math.max(start, end),
str, 0, str.length());
}
}
private boolean alreadyExists(String templateName){
int type_code = -1;
if(mTemplateType.equals("sms")){
type_code = Constants.SMS_CODE;
} else if(mTemplateType.equals("email")){
type_code = Constants.EMAIL_CODE;
}
String query = "Select * from " + Constants.TABLE_NAME_GREETINGS
+ " where " + Constants.GREETING_NAME + " = '" + templateName
+ "' AND " + Constants.KEY_ID_SETUP_GREET + "=" + type_code;
Cursor c = null;
Boolean exists = false;
dba.open();
try {
c = dba.getResults( query );
if (c != null) {
if (c.moveToFirst()) {
exists = (c.getCount() > 0);
} else {
exists = false;
}
}
} catch (Exception e) {
Log.e("CreateNewTemplate", "Error while checking if name already exists. Details: "+e.getMessage(), e);
e.printStackTrace();
} finally {
if (c != null)
c.close();
dba.close();
}
return exists;
}
}
move your cursor to the position of the list view item that you have clicked and then fetch the data from db using that cursor. Below is a small snippet:
yourListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(cursor!=null){
cursor.moveToPosition(position);
//do your stuff here....
cursor.close();
}
}
});
I have created a custom list view with 6 colomns. Each row is populated.
the first 3 fields are textviews,which are filled from db. Then a spinner and the last two edittexts.
i want to enter values to edittexts and spinner.. this much is ok.
The problem is when i enter values in edittext and after that if i scroll the list, the values entered in edittext changes in position. if i entered in first row, after scrolling it will be in last row or any other.. how i can solve this.. Need help pls..
My adapter class is given below.
public class CustomTransAdapter extends BaseAdapter {
public ArrayList<retrieveTrans> ret_arrArrayList;
private List<retrieveTrans> ret_translist;
private LayoutInflater inflater;
ArrayAdapter<String> adapterspin;
String time, currntdate, status;
String Maxcramnt, balamount;
double Mamount, Bamount, actualamnt;
String idpref, str_agent_id2, accno;
int trcheck;
int d = 0;
String tramnt = "", remarks = "";
Context context;
int count;
public CustomTransAdapter(NewTransactionSheet newTransactionSheet,
int transListPop, List<retrieveTrans> translist) {
// TODO Auto-generated constructor stub
super();
this.ret_translist = translist;
inflater = LayoutInflater.from(newTransactionSheet);
this.ret_arrArrayList = new ArrayList<retrieveTrans>();
this.ret_arrArrayList.addAll(translist);
this.context = newTransactionSheet;
String[] items = new String[] { "Type", "credit", "debit" };
final ArrayAdapter<String> adapterspin = new ArrayAdapter<String>(
newTransactionSheet, android.R.layout.simple_spinner_item,
items);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return ret_translist.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return ret_translist.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
class ViewHolder {
TextView acc_txt, name_txt, balAmnt_txt;
Spinner trans_spinner;
EditText transAmnt_edittxt, remarks_edittxt;
Button save;
}
#Override
public View getView(final int pos, View cv, ViewGroup arg2) {
// TODO Auto-generated method stub
try {
final ViewHolder holder;
View row = cv;
int p = pos;
Log.e("position of getview:", "" + p);
if (cv == null) {
cv = inflater.inflate(R.layout.trans_pop_list, null);
holder = new ViewHolder();
holder.acc_txt = (TextView) cv
.findViewById(R.id.txtTransAccNo_pop);
holder.name_txt = (TextView) cv
.findViewById(R.id.txtTransName_pop);
holder.balAmnt_txt = (TextView) cv
.findViewById(R.id.txtTransBalAmnt_pop);
holder.trans_spinner = (Spinner) cv
.findViewById(R.id.spinTrans_Type);
holder.transAmnt_edittxt = (EditText) cv
.findViewById(R.id.editTransAmnt_pop);
holder.save = (Button) cv.findViewById(R.id.save);
holder.remarks_edittxt = (EditText) cv
.findViewById(R.id.editRemarks_pop);
cv.setTag(holder);
} else {
holder = (ViewHolder) cv.getTag();
}
holder.acc_txt.setText("" + ret_translist.get(pos).getRetAccNo());
String hari = holder.acc_txt.getText().toString();
holder.name_txt.setText("" + ret_translist.get(pos).getRetName());
holder.balAmnt_txt.setText(""
+ ret_translist.get(pos).getRetBalAmnt());
String[] items = new String[] { "Type", "credit", "debit" };
final ArrayAdapter<String> adapterspin = new ArrayAdapter<String>(
context, android.R.layout.simple_spinner_item, items);
final String haris = holder.name_txt.getText().toString();
holder.trans_spinner.setAdapter(adapterspin);
/* ******************* Save button Click **************** */
holder.save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int position = pos;
final String accno = holder.acc_txt.getText().toString();
final String tramnt = holder.transAmnt_edittxt.getText()
.toString();
String remarks = holder.remarks_edittxt.getText()
.toString();
final String spinner = holder.trans_spinner
.getSelectedItem().toString();
Log.e("accno:", "" + accno);
Log.e("name :", "" + tramnt);
Log.e("position:", "" + position);
Log.e("remark:", "" + remarks);
Log.e("spinner:", "" + spinner);
/****************** time and date **********************/
// ----------Time----------
Calendar c = Calendar.getInstance();
time = (c.get(Calendar.HOUR) + ":" + c.get(Calendar.MINUTE)
+ ":" + c.get(Calendar.SECOND));
Log.e("Current Time", " " + time);
// -----------Date---------
Date now = new Date();
Date alsoNow = Calendar.getInstance().getTime();
currntdate = new SimpleDateFormat("M-d-yyyy").format(now);
Log.e("Date ", " " + currntdate);
status = new String("y");
if (tramnt.equals("")) {
Toast.makeText(arg0.getContext(),
"enter Transaction amount", 5000).show();
Log.e("if cndition", " " + tramnt);
} else if (spinner.equals("type")) {
Toast.makeText(arg0.getContext(),
"enter Transaction type", 5000).show();
Log.e("if cndition", " " + tramnt);
}
else {
if (remarks.equals("")) {
remarks = "null";
}
/************ declaration for dbcall *********************/
AccountDBAdapter db = new AccountDBAdapter(context);
NewTransactionSheet ts = new NewTransactionSheet();
try {
db.open();
String accid = db.getAccID(accno);
String Maxcramnt = db.getMaxCrAmnt(accno);
db.close();
Mamount = Double.parseDouble(Maxcramnt);
Bamount = Double.parseDouble(tramnt);
actualamnt = Mamount - Bamount;
balamount = "" + actualamnt;
db.open();
db.close();
/* Log.e("c value", " " +actualamnt); */
Log.e("tramnt", " " + tramnt);
Log.e("if cndition out", " " + tramnt);
db.open();
db.update_MaxCrAmnt(balamount, accid);
db.close();
actualamnt = 0;
db.open();
String userId = "" + 2;
db.insertTransactionTable(accid.toString(),
currntdate.toString(), spinner.toString(),
tramnt.toString(), userId.toString(),
time.toString(), remarks.toString(),
status.toString());
db.close();
holder.save.setText("SAVED");
holder.save.setBackgroundColor(Color.DKGRAY);
// }
} catch (Exception e) {
Log.e("error", e.getMessage());
}
}
}
});
} catch (Exception c) {
Log.e("adapter error", "" + c.getMessage());
}
return cv;
}
}
Working on this for many days... need help.. Thanks in advance.
I am trying to build up a application which has a custom adapter and all ListView row has three Button. I have onClick operation for all Button in custom adapter. I can change the data source when Button clicked however I can not reload the data from custom adapter.
public class CallListViewCustomAdapter extends ArrayAdapter<Person> {
Context context;
SQLiteDatabase sb;
private static final String SAMPLE_DB_NAME = "androidData.sqlite";
private static final String SAMPLE_TABLE_NAME = "calldetails";
int layoutResourceId;
ArrayList<Person> data = new ArrayList<Person>();
public CallListViewCustomAdapter(Context context, int layoutResourceId, ArrayList<Person> data) {
super(context, layoutResourceId,data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
public void refresh(ArrayList<Person>list)
{
data = list;
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = null;
View row = convertView;
final int fPosition = position;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
final WeatherHolder holder = new WeatherHolder();
holder.phoneNumber = (TextView)row.findViewById(R.id.number);
holder.fname = (TextView)row.findViewById(R.id.fName);
holder.call = (Button)row.findViewById(R.id.callButton);
holder.skip = (Button)row.findViewById(R.id.skip);
holder.called = (Button)row.findViewById(R.id.called);
holder.called.setTag(position);
Person weather = data.get(position);
holder.phoneNumber.setText(weather.number);
holder.fname.setText(weather.fName);
holder.call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
holder.called.setVisibility(View.VISIBLE);///error comes
holder.skip.setVisibility(View.VISIBLE);///error comes
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + data.get(fPosition).number));
callIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(callIntent);
}
});
holder.called.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
//business logic for data source change
refresh(data);///I want listview change here
sb.close();
Log.v("ONMESSAGE", "HARD");
}
});
// holder.desc= (TextView)row.findViewById(R.id.txtViewDescription);
// holder.switchState = (Switch)row.findViewById(R.id.switch1);
row.setTag(holder);
}
return row;
}
static class WeatherHolder
{
TextView phoneNumber;
TextView fname;
Switch switchState;
Button call,skip,called;
}
}
Fragment where The list is used
public class NewFragment extends Fragment{
View rootView;
ProgressDialog pDialog;
private ListView listView1;
CallListViewCustomAdapter adapter;
private static final String SAMPLE_DB_NAME = "androidData.sqlite";
private SQLiteDatabase sampleDB;
ArrayList<Person>list;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
rootView = inflater.inflate(R.layout.newfragment, container, false);
initDB();
list = new ArrayList<Person>();
new CallLogDetails().execute();
return rootView;
}
public int checkTable() {
int return_var = 0;
sampleDB = getActivity().openOrCreateDatabase(SAMPLE_DB_NAME, Context.MODE_PRIVATE, null);
Cursor cc = sampleDB.rawQuery("SELECT * FROM " + "calldetails", null);
if (cc != null){
if (cc.moveToFirst()) {
do {
return_var = cc.getInt(1);
} while (cc.moveToNext());
}
}
return return_var;
}
public void parseandStoreOpearation()
{
try{
CSVReader reader = new CSVReader(new InputStreamReader(getActivity().getAssets().open("batch2.csv")));
String [] nextLine;
sampleDB = getActivity().openOrCreateDatabase(SAMPLE_DB_NAME, Context.MODE_PRIVATE, null);
while ((nextLine = reader.readNext()) != null) {
//Log.v("ONMESSAGE", "YES");
Log.v("ONMESSAGE", "Name: [" + nextLine[0] + "]\nAddress: [" + nextLine[1] + "]\nEmail: [" + nextLine[2] + "]");
if(!nextLine[0].equals("First Name"))
{
//Person newPerson = new Person(nextLine[0],nextLine[1], nextLine[2], 1);
ContentValues cv = new ContentValues();
cv.put("callNumber", nextLine[2]);
cv.put("fName", nextLine[0]);
cv.put("lName", nextLine[1]);
cv.put("callflag", 1);
sampleDB.insert("calldetails", null, cv);
//list.add(newPerson);
}
}
}
catch(Exception e)
{
Log.v("ONMESSAGE", "EXCEPTION " + e.toString());
}
}
public ArrayList<Person> getList()
{
ArrayList<Person> arr = new ArrayList<Person>();
sampleDB= getActivity().openOrCreateDatabase(SAMPLE_DB_NAME, Context.MODE_PRIVATE, null);
Cursor cc = sampleDB.rawQuery("SELECT * FROM " +"calldetails", null);
if(cc != null)
if(cc.moveToFirst()){
do
{ Log.v("Datas",cc.getString(2)+ " " +cc.getString(3) + " " + cc.getString(1) + " " + cc.getInt(4));
Person ph = new Person(cc.getString(2), cc.getString(3), cc.getString(1),cc.getInt(4),cc.getInt(0));
arr.add(ph);
}while(cc.moveToNext());
}
sampleDB.close();
Log.v("ONMESSAGE", new Integer(arr.size()).toString());
return arr;
}
private void initDB() {
sampleDB = getActivity().openOrCreateDatabase(SAMPLE_DB_NAME, Context.MODE_PRIVATE, null);
sampleDB.execSQL("CREATE TABLE IF NOT EXISTS " +
"calldetails" +" (callid INTEGER PRIMARY KEY AUTOINCREMENT,"+ "callNumber TEXT," +
" fName TEXT," + "lName TEXT," + "callflag INTEGER);");
}
private class CallLogDetails extends AsyncTask<Void,Void,Void>{
#Override
protected void onPreExecute(){
pDialog = new ProgressDialog(getActivity());
pDialog.setTitle("Processing");
pDialog.setMessage("Loading Number List");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
protected void onPostExecute(Void params){
super.onPostExecute(params);
pDialog.dismiss();
if(list.size() == 0)
{
list.add(new Person("No Data", "NO Data", "No Data", 0,0));
}
Collections.reverse(list);
if(adapter != null)
adapter.clear();
adapter = new CallListViewCustomAdapter(getActivity(),
R.layout.listview_row, list);
listView1 = (ListView)getActivity().findViewById(R.id.lvAlbumList);
listView1.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
final int arg2, long arg3) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Delete Record");
builder.setMessage("Do you want to delete the record?");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
if(list.size() > 0){
sampleDB=getActivity().openOrCreateDatabase(SAMPLE_DB_NAME, SQLiteDatabase.OPEN_READWRITE, null);
//sampleDB.execSQL("DELETE FROM "+ SAMPLE_DB_NAME + " " + "WHERE callDesc= " + desc);
//sampleDB.execSQL("DELETE FROM calldetails WHERE callDesc='"+desc+"';");
Toast.makeText(getActivity(), "Row Deleted", Toast.LENGTH_LONG).show();
sampleDB.close();
new CallLogDetails().execute();
}
else
Toast.makeText(getActivity(), "This is a default object. You can not delete this.", Toast.LENGTH_LONG).show();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
arg0.cancel();
}
});
builder.show();
return false;
}
});
listView1.setAdapter(adapter);
}
#Override
protected Void doInBackground(Void... arg0) {
list.clear();
if(checkTable() == 0)
{
parseandStoreOpearation();
}
list = getList();
Log.v("ONMESSAGE", "Doing");
return null;
}
}
}
For an ArrayAdapter, notifyDataSetChanged() only works if you use the add, insert, remove, and clear functions on the Adapter.
Try following code:
public void refresh(ArrayList<Person>list)
{
data.clear();
data.addAll(list);
this.notifyDataSetChanged();
}
Do something like this inside activity
CallListViewCustomAdapter thadapter=new CallListViewCustomAdapter(MainActivity.this, R.layout.list,numAl);
NumberList.setAdapter(thadapter);
#Override
public void onClick(View v) {
thadapter.notifyDataSetChanged();
}
});
Call notifyDataSetChanged() and recall adapter
Call notifyDataSetChanged() method to the ListView adapter object.