I have a problem that i can't figure out how to solve. My code is the following:
package com.app.BoomBase;
import android.app.Activity;
import android.app.LauncherActivity.ListItem;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class Distance extends Activity implements OnItemSelectedListener {
Button Calc;
Spinner spType, spForce, spWeight;
double FarstCatch, TrickCatch, MTA, LongDistance ;
String[] types = { "Farst Catch", "Trick Catch", "MTA" , "Long Distance" };
EditText etWeight;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.distance);
super.onCreate(savedInstanceState);
FarstCatch = 100;
TrickCatch = 43.56;
MTA = 32.60 ;
LongDistance = 25;
ArrayAdapter<String> AdapterT = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, types);
spType = (Spinner) findViewById(R.id.spType);
AdapterT.setDropDownViewResource(android.R.layout.simple_spinner_item);
spType.setAdapter(AdapterT);
spType.setPrompt("Select Type");
spType.setOnItemSelectedListener(this);
Button Calc = (Button) findViewById(R.id.button1);
Calc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String selected = spType.getSelectedItem().toString();
Toast.makeText(getApplicationContext(), "Your Boomerang will apoximately fly this far:" + selected, Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
int position = spType.getSelectedItemPosition();
switch (position){
case 0:
double FarstCatch;
break;
case 1:
double TrickCatch;
break;
case 2:
double MTA;
break;
case 3:
double LongDistance;
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
I want to take the variable that correspond to the seleceted case from the user input (spType), and then use that for a calculation. Exmple: If the user selectes FarstCatch i want to take the number 100 and use it in this calculation: R = m / FarstCatch.
How can i do that ?
Edit:
The new code:
package com.app.BoomBase;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class Distance extends Activity implements OnItemSelectedListener {
Button Calc;
Spinner spType, spForce, spWeight;
double FarstCatch, TrickCatch, MTA, LongDistance, r ;
String[] types = { "Farst Catch", "Trick Catch", "MTA" , "Long Distance" };
double[] values = {100, 43.56, 32.6, 25};
EditText etWeight;
int etNum;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.distance);
super.onCreate(savedInstanceState);
FarstCatch = 100;
TrickCatch = 43.56;
MTA = 32.60 ;
LongDistance = 25;
ArrayAdapter<String> AdapterT = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, types);
spType = (Spinner) findViewById(R.id.spType);
AdapterT.setDropDownViewResource(android.R.layout.simple_spinner_item);
spType.setAdapter(AdapterT);
spType.setPrompt("Select Type");
spType.setOnItemSelectedListener(this);
etWeight = (EditText) findViewById(R.id.etWeight);
Button Calc = (Button) findViewById(R.id.button1);
Calc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String etValue = etWeight.getText().toString();
etNum = Integer.parseInt(etValue);
Toast.makeText(getApplicationContext(), "Your Boomerang will apoximately fly this far:" + r , Toast.LENGTH_LONG).show();
}
});
}
public void onItemSelected1(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// value corresponds to the selected spType
double value = values[arg2];
r = etNum/value;
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
int position = spType.getSelectedItemPosition();
switch (position){
case 0:
double FarstCatch;
break;
case 1:
double TrickCatch;
break;
case 2:
double MTA;
break;
case 3:
double LongDistance;
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
But it still don't work.. How can this be ?
Create another array for values corresponding to types array.
double[] values = {100, 43.56, 32.6, 25};
Next, implement onItemSelected() as follows -
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// value corresponds to the selected spType
double value = values[arg2];
// Do your calculation
//double R = m/value;
}
Note: arg2 is the selected item position so need to use getSelectedItem()
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
Sample Code:
public class Distance extends Activity implements OnItemSelectedListener {
Button Calc;
Spinner spType, spForce, spWeight;
double selectedValue, r;
String[] types = { "Farst Catch", "Trick Catch", "MTA" , "Long Distance" };
double[] values = {100, 43.56, 32.6, 25};
EditText etWeight;
int etNum;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.distance);
super.onCreate(savedInstanceState);
ArrayAdapter<String> AdapterT = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, types);
spType = (Spinner) findViewById(R.id.spType);
AdapterT.setDropDownViewResource(android.R.layout.simple_spinner_item);
spType.setAdapter(AdapterT);
spType.setPrompt("Select Type");
spType.setOnItemSelectedListener(this);
etWeight = (EditText) findViewById(R.id.etWeight);
Button Calc = (Button) findViewById(R.id.button1);
Calc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String etValue = etWeight.getText().toString();
etNum = Integer.parseInt(etValue);
r = etNum/selectedValue;
Toast.makeText(getApplicationContext(), "Your Boomerang will apoximately fly this far:" + r , Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// value corresponds to the selected spType
selectedValue = values[arg2];
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
i have problem with search, when user type something, listview will change, so the next activity will recive wrong values.
my code:
package com.example.finaltest;
import java.util.ArrayList;
import java.util.HashMap;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.text.TextWatcher;
import android.view.View;
public class Search extends ActionBarActivity {
// List view
private ListView lv;
// Listview Adapter
ArrayAdapter<String> adapter;
// Search EditText
EditText inputSearch;
// ArrayList for Listview
ArrayList<HashMap<String, String>> productList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
// Listview Data
String products[] = getResources().getStringArray(R.array.search);
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.subject_name, products);
lv.setAdapter(adapter);
/**
* Enabling Search Filter
* */
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// When user changed the Text
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
Search.this.adapter.getFilter().filter(arg0);
}
});
// after click
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
final String item = lv.getItemAtPosition(position).toString();
int total_number = 50;
for(int x = 1; x < total_number+1; x = x+1) {
String SubjectName = "subject_" + String.valueOf(x);
int resID = getResources().getIdentifier(SubjectName, "string", getPackageName());
String subject = getResources().getString(resID);
if(item.equals(subject)) {
String StringClass = "com.example.finaltest.Subject_" + String.valueOf(x);
Class<?> c = null;
if(StringClass != null) {
try {
c = Class.forName(StringClass);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Intent i = new Intent(getApplicationContext(), Show_Subjects.class);
String Subject_number = String.valueOf(position+1);
i.putExtra("subject_number", Subject_number);
startActivity(i);
}
}
}
});
}
#Override
public void onResume() {
super.onResume();
adapter.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_settings:
Intent delIntent = new Intent(Search.this, Settings.class);
Search.this.startActivity(delIntent);
return true;
case R.id.action_favorites:
Intent delItemIntent = new Intent(Search.this, Favorites.class);
Search.this.startActivity(delItemIntent);
return true;
}
return id == R.id.action_settings || super.onOptionsItemSelected(item);
}
}
my string names are Subject_N , i want to send values of N to next activity(from item row number)
my language is persian ,also i have an other problem, search field only support english ! change language is Inactive
//outside the for loop
ArrayList<String> ArraySubject_number = new ArrayList<String>();
String Subject_number;
//initialize your arraylist inside the loop for each row
//use something like
//for each row
Subject_number = String.valueOf(position+1);
ArraySubject_number.add(Subject_number);
//outside for loop
Intent intent= new Intent(getApplicationContext(), Show_Subjects.class);
intent.putExtras("subject_number", ArraySubject_number);
then in your other activity use this code to access them
ArrayList<String> ArraySubject_number = (ArrayList<String>) getIntent().getSerializableExtra("subject_number");
I'm working on an order management system for android.
On the order page where the user submits an order, i want it to be able to allow the user to submit multiple orders, then take the user to a page where it displays all the orders made.
What method can i use to accomplish that?
This is the order activity page which is made up of 3 spinners and one textfield. This page takes the user to a ViewOrder page which displays what the user has selected. Instead of that i would like the user to submit multiple orders first, then see the display of all orders submitted. Any help is much appreciated.
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.example.androidhive.R;
public class OrderActivity extends Activity {
public Button btnOrder;
public EditText txtCrates;
public Spinner sp1, sp2, sp3;
public List<String> list;
public static String crates;
public static final String EXTRA_MESSAGE = "com.example.myspinner.msg1";
public static final String EXTRA_MESSAGE2 = "com.example.myspinner.msg2";
public static final String EXTRA_MESSAGE3 = "com.example.myspinner.msg3";
public static final String EXTRA_MESSAGE4 = "com.example.myspinner.MESSAGE";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.order);
sp1 = (Spinner) findViewById(R.id.spinner1);
sp2 = (Spinner) findViewById(R.id.spinner2);
sp3 = (Spinner) findViewById(R.id.spinner3);
btnOrder = (Button) findViewById(R.id.btnOrder);
txtCrates =(EditText) findViewById(R.id.crates);
list = new ArrayList<String> ();
list.add("CocaCola");
list.add("Sprite");
list.add("Fanta Orange");
list.add("Fanta Pineapple");
list.add("Fanta Blackcurrant");
list.add("Fanta Passion");
list.add("Krest");
list.add("Stoney");
list.add("Dasani");
list.add("Minute Maid Apple");
list.add("Minute Maid Mango");
list.add("Minute Maid Orange");
final String[] str1={"300ml","500ml","1 Litre","1.25 Litres","2 Litres"};
ArrayAdapter<String> adp1 = new ArrayAdapter<String>
(this, android.R.layout.simple_dropdown_item_1line, list);
ArrayAdapter<String> adp2 = new ArrayAdapter<String>
(this, android.R.layout.simple_dropdown_item_1line, str1);
ArrayAdapter<CharSequence> adp3 = ArrayAdapter.createFromResource
(this, R.array.str2, android.R.layout.simple_dropdown_item_1line);
sp1.setAdapter(adp1);
sp2.setAdapter(adp2);
sp3.setAdapter(adp3);
btnOrder.setOnClickListener(new View.OnClickListener() {
/** Called when the user clicks the Submit Order button */
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(),ViewOrder.class);
String msg1=sp1.getSelectedItem().toString();
String msg2=sp2.getSelectedItem().toString();
String msg3=sp3.getSelectedItem().toString();
String message = txtCrates.getText().toString();
intent.putExtra(EXTRA_MESSAGE, msg1);
intent.putExtra(EXTRA_MESSAGE2, msg2);
intent.putExtra(EXTRA_MESSAGE3, msg3);
intent.putExtra(EXTRA_MESSAGE4, message);
startActivity(intent);
}
});
sp1.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), list.get(arg2),
Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
sp2.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), str1[arg2],
Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
sp3.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
String item = sp3.getSelectedItem().toString();
Toast.makeText(getBaseContext(), item, Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
Once try as follows take an List for multiple orders
ArrayList<String> orders=new ArrayList<String>();
as class variable in activity
then store a complete order as string with some special character as divider like
String msg1=sp1.getSelectedItem().toString();
String msg2=sp2.getSelectedItem().toString();
String msg3=sp3.getSelectedItem().toString();
String message = txtCrates.getText().toString();
orders.add(msg1+","+msg2+","+msg3+","+message);
then for intent add as follows
intent.putStringArrayListExtra("orders", orders);
Hope this will helps you.
I have a simple spinner which has several number options. I want to just select a number and then it does some math to that number and outputs it in a text box. For some reason it's only doing math on the 1st entry in the list and if you change it doesn't update.
Any ideas?
package placeorder.com;
import java.util.Random;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Spinner;
import android.widget.TextView;
public class Time extends Activity{
double totalhours, cost;
int price;
TextView total, orderid;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.time);
Spinner spinhours = (Spinner) findViewById(R.id.sp_hours);
total = (TextView) findViewById(R.id.tv_total);
orderid = (TextView) findViewById(R.id.tv_orderid);
Random order = new Random();
int randomorder = order.nextInt(9999);
order.nextInt(9999);
orderid.setText("Order ID: "+randomorder);
price = 5;
String hours = spinhours.getSelectedItem().toString();
totalhours = Integer.parseInt(hours);
cost = totalhours * price;
total.setText("£" + cost);
}
}
You should add listener for spinner
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
String str = (String) arg0.getSelectedItem();
outputTextview.setText(str);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
I'm really frustrated because of bad programming style, and inexperience in Android. Sorry to tell you guys that.
How the app works:
This is a todo app for my job training. There are 6 columns.
3 of these contain information about the todo and the other 3 contain a view detail, edit, and remove screen.
When the user clicks remove for some reason even after setting a notifyDataChange, my screen is not updated and the deleted row it's still displayed.
Any ideas of what is going on here? I've tried many solutions for about 3 hours now
The code is posted here sorry if its a bit tedious.
The whole class with the ListViews:
package com.DCWebMakers.Vairon;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class ManageAppointment extends Activity {
ListView rowLi, whenLi, postedLi, detailsLi, editLi, removeLi;
ArrayAdapter<String> whenAdapter, postedAdapter, detailsAdapter,
editAdapter, removeAdapter;
ArrayAdapter<Integer> rowAdapter;
final AppointmentInfo information = new AppointmentInfo(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
/*
* The ListViews created here are not the proper way to make ListViews.
* This is for testing purposes and will be updated for efficiency. The
* remove also doesn't work properly
*/
super.onCreate(savedInstanceState);
setContentView(R.layout.manage_appointment);
initVariables();
try {
databaseManagement();
detailsLi.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> aV, View v, int pos,
long arg3) {
// TODO Auto-generated method stub
Intent openDetails = new Intent(
"com.DCWebMakers.Vairon.APPOINTMENTDETAILS");
openDetails.putExtra("position", pos);
startActivity(openDetails);
}
});
editLi.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> aV, View v, int pos,
long arg3) {
// TODO Auto-generated method stub
Intent openEdit = new Intent(
"com.DCWebMakers.Vairon.EDITAPPOINTMENT");
openEdit.putExtra("position", pos);
startActivity(openEdit);
notifyChangesToAdapters();
}
});
removeLi.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> aV, View v, int pos,
long arg3) {
// TODO Auto-generated method stub
databaseManagement();
information.open();
information.delete(pos);
information.close();
Dialog sucDeleted = new Dialog(ManageAppointment.this);
sucDeleted.setTitle("Sucesfully deleted");
TextView tvDintWorked = new TextView(ManageAppointment.this);
tvDintWorked.setText("The appointment at position:" + pos
+ " was sucesfully deleted");
sucDeleted.setContentView(tvDintWorked);
sucDeleted.show();
notifyChangesToAdapters();
}
});
} catch (Exception e) {
Dialog showError = new Dialog(this);
showError.setTitle("Error");
TextView tvDintWorked = new TextView(this);
String error = e.toString();
tvDintWorked.setText(error);
showError.setContentView(tvDintWorked);
showError.show();
}
}
public void initVariables() {
rowLi = (ListView) findViewById(R.id.rowList);
whenLi = (ListView) findViewById(R.id.whenList);
postedLi = (ListView) findViewById(R.id.postedList);
detailsLi = (ListView) findViewById(R.id.detailsList);
editLi = (ListView) findViewById(R.id.editList);
removeLi = (ListView) findViewById(R.id.removeList);
}
#Override
protected void onPause() { // TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
notifyChangesToAdapters();
}
private void notifyChangesToAdapters() {
// TODO Auto-generated method stub
rowAdapter.notifyDataSetChanged();
whenAdapter.notifyDataSetChanged();
postedAdapter.notifyDataSetChanged();
detailsAdapter.notifyDataSetChanged();
editAdapter.notifyDataSetChanged();
removeAdapter.notifyDataSetChanged();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Intent mainIntent = new Intent("com.DCWebMakers.Vairon.MAINMENU");
startActivity(mainIntent);
}
public void databaseManagement() {
information.open();
int primaryKey = information.getKeys();
String when[] = information.getWhen();
String posted[] = information.getPosted();
String details[] = new String[primaryKey];
Integer rowNumber[] = new Integer[primaryKey];
String edit[] = new String[primaryKey];
String delete[] = new String[primaryKey];
for (int set = 0; set < rowNumber.length; set++) {
rowNumber[set] = (set);
}
for (int set = 0; set < details.length; set++) {
details[set] = ("Details");
}
for (int set = 0; set < edit.length; set++) {
edit[set] = ("Edit");
}
for (int set = 0; set < delete.length; set++) {
delete[set] = ("Delete");
}
information.close();
rowAdapter = new ArrayAdapter<Integer>(ManageAppointment.this,
android.R.layout.simple_list_item_1, rowNumber);
whenAdapter = new ArrayAdapter<String>(ManageAppointment.this,
android.R.layout.simple_list_item_1, when);
postedAdapter = new ArrayAdapter<String>(ManageAppointment.this,
android.R.layout.simple_list_item_1, posted);
detailsAdapter = new ArrayAdapter<String>(ManageAppointment.this,
android.R.layout.simple_list_item_1, details);
editAdapter = new ArrayAdapter<String>(ManageAppointment.this,
android.R.layout.simple_list_item_1, edit);
removeAdapter = new ArrayAdapter<String>(ManageAppointment.this,
android.R.layout.simple_list_item_1, delete);
rowLi.setAdapter(rowAdapter);
whenLi.setAdapter(whenAdapter);
postedLi.setAdapter(postedAdapter);
detailsLi.setAdapter(detailsAdapter);
editLi.setAdapter(editAdapter);
removeLi.setAdapter(removeAdapter);
}
}
The delete method:
public void delete(int position) {
theDatabase.beginTransaction();
try {
theDatabase
.delete(DATABASE_TABLE, KEY_ROWID + "=" + position, null);
theDatabase.setTransactionSuccessful();
} catch (SQLiteException e) {
// TODO: handle exception
e.printStackTrace();
} finally {
theDatabase.endTransaction();
theDatabase.close();
}
}
before notifyDataSetChanged you need to remove the entry from the List
Did you see any exception when deleting from database. and you also need to delete pos entry from global list before notifying.
I'm using an AutoCompleteTextView to suggest user some words from my sqlite db as they type the input string to search.
I try to make the suggestion look friendly by using simple_list_item_2, here's my code:
package com.suit.kamus;
import android.app.Activity;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class SuitAuto extends Activity implements TextWatcher{
AutoCompleteTextView auto; TextView result;
Button search; Button add; Spinner chooser;
String input; static String selection; String main;
String[] options = {"en to ina", "ina to en"};
SimpleCursorAdapter simple;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
auto = (AutoCompleteTextView)findViewById(R.id.auto);
auto.addTextChangedListener(this);
result = (TextView)findViewById(R.id.result);
chooser = (Spinner)findViewById(R.id.chooser);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, options);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
chooser.setAdapter(adapter);
KamusDbAdapter dbHelper = new KamusDbAdapter(getApplicationContext());
dbHelper.open();
String status = dbHelper.getstatedb();
selection = status;
dbHelper.close();
if (selection.equalsIgnoreCase("en")){
chooser.setSelection(0);
} else {chooser.setSelection(1);}
Log.d("statelang", selection);
add = (Button)findViewById(R.id.add);
add.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startAdding(main);
}
});
chooser.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
if (chooser.getSelectedItemId() == 0){
selection = "en";
select();
updateDb();
}else{
selection = "ina";
select();
updateDb();
}
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
auto.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
main = auto.getText().toString();
//Log.v("CURSOR",finish);
result.setText("");
auto.setText("");
}
});
}
public void startAdding(String dWord) {
// TODO Auto-generated method stub
KamusDbAdapter adding = new KamusDbAdapter(getApplicationContext());
adding.open();
adding.Favorite(dWord);
adding.close();
}
protected void updateDb() {
// TODO Auto-generated method stub
KamusDbAdapter save = new KamusDbAdapter(getApplicationContext());
save.open();
save.updatestatedb(selection);
save.close();
}
public static String select() {
// TODO Auto-generated method stub
Log.v("STRING",selection);
return selection;
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
input = auto.getText().toString();
KamusDbAdapter x = new KamusDbAdapter(getApplicationContext());
x.open();
Cursor cur = x.getCall(input, selection);
//getCall is in KamusDbAdapter class, it used to return result cursor from sqlite db
//i use rawQuery "SELECT * FROM en_to_ina WHERE word LIKE 'input%'"
x.close();
String[] displayFields = new String[] {"word", "meaning"};
int[] displayViews = new int[] { android.R.id.text1,android.R.id.text2 };
simple = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, cur,displayFields, displayViews);
auto.setAdapter(simple);
}
}
I got a problem with retrieving the string from clicked item. It is in:
auto.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
main = auto.getText().toString();
//Log.v("CURSOR",finish);
result.setText("");
auto.setText("");
}
});
I need both strings from word and meaning fields.
Any response would be great...
You need to use http://developer.android.com/reference/android/widget/CursorAdapter.html#getItem(int).
Cursor cursor = (Cursor) simple.getItem(position);
// retrieve the data from the cursor
This seems to be a problem with SimpleCursorAdapter on 2.1, on 2.2 the cursor is positioned on the requested item and you can retrieve the column data but in 2.1 the cursor position is 0 and cursor.move(itemIndex) and cursor.moveToFirst() both return false.
I plan to do a RYO database adapter.
Getting string from SimpleCurstor Adapter using cursor
#Override
public boolean onSuggestionClick(int position) {
//First get cursor from your Adapter,
Cursor cursor = (Cursor) mAdapter.getItem(position);
/* Then get string data from cursor's column, I am getting it from column 0 in this case. You can use your own column index. */
String s=cursor.getString(0);
//Then set the searchview or autotextview with that string
mSearchView.setQuery(s, true); //true will submit the query
}