How to get string from selected item of SimpleCursorAdapter? - android

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
}

Related

multiple order entries in android application

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.

Get database ID and put it in on clickview on ListView

I get data from database (id, name) and I display (name) in a ListView. When user clicks I need to get database (id) to perform an action
KoiskesdataActivity.java
package koisk.data;
import java.util.ArrayList;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.os.StrictMode;
import android.widget.AdapterView.OnItemClickListener;
public class KoiskesdataActivity extends Activity {
/** Called when the activity is first created. */
ProgressDialog pd;
private ListView koisksListView;
private EditText myfilter;
// private ArrayAdapter <String> koiskarrayAdapter;
String koiskArray[];
Button autocompletekoisksname;
int textlength=0;
private ArrayList<String> array_sort= new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
///
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
///
koisksListView=(ListView) findViewById(R.id.koiskslist);
myfilter=(EditText) findViewById(R.id.myFilter);
///////
pd = new ProgressDialog(this);
pd.setMessage("loading...");
pd.show();
/////
getarrayofnamekoisk namekoisk=new getarrayofnamekoisk();
koiskArray=namekoisk.WW();
ArrayAdapter <String> koiskarrayAdapter=new ArrayAdapter <String>(KoiskesdataActivity.this, android.R.layout.simple_list_item_1,koiskArray);
koisksListView.setAdapter(koiskarrayAdapter);
pd.dismiss();
koisksListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
});
myfilter.addTextChangedListener(new TextWatcher() {
#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 s, int start, int before, int count)
{
// TODO Auto-generated method stub
textlength = myfilter.getText().length();
array_sort.clear();
for (int i = 0; i < koiskArray.length; i++)
{
if (textlength <= koiskArray[i].length())
{
//subSequence returns the specified word between the begien and end
//equalsIgnoreCase compares this String to another String, ignoring case considerations. Two strings are considered equal ignoring case if they are of the same length, and corresponding characters in the two strings are equal ignoring case
if (myfilter.getText().toString().equalsIgnoreCase((String)koiskArray[i].subSequence(0, textlength)))
{
array_sort.add(koiskArray[i]);
}
}
}
//KoiskesdataActivity.this.koiskarrayAdapter.getFilter().filter(s);
koisksListView.setAdapter(new ArrayAdapter<String>(KoiskesdataActivity.this,android.R.layout.simple_list_item_1,array_sort));
}
});
}
}
getarrayofnamekoisk.java
package koisk.data;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.xml.transform.Templates;
import android.R.array;
import android.R.integer;
import android.widget.ArrayAdapter;
import android.widget.Toast;
public class getarrayofnamekoisk{
private int i;
private String[] koiskname ;
private int num_rows;
private ArrayAdapter arrayAdapterdata;
List<String[]> names = new ArrayList<String[]>();
ArrayList<String> arr = new ArrayList<String>();
public String[] WW() {
// TODO Auto-generated method stub
connecttodatabase qq=new connecttodatabase();
qq.dbconnect();
if (qq.con !=null)
{
try
{
Statement st = qq.con.createStatement();
ResultSet rs = st.executeQuery("SELECT Name,id FROM Device where DeviceTypeId=4 and IsDeleted =0 and name is not null ");
while(rs.next())
{
arr.add(rs.getString("name"));
}
koiskname= new String [arr.size()];
arr.toArray(koiskname);
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//Toast.makeText(ConnectbyprocedureActivity.this, e.toString() , Toast.LENGTH_SHORT).show();
}
qq.closeConnection();
}
return koiskname;
}
}
connecttodatabase.java //to connect to sql server
package koisk.data;
import java.sql.DriverManager;
public class connecttodatabase {
public java.sql.Connection con = null;
private final String userName="sa";
private final String pass="123";
/////////
private final String url = "jdbc:jtds:sqlserver://";
private final String serverName= "192.168.1.200";
private final String portNumber = "1433";
private final String databaseName= "loadshedding";
////////////
/**
* #param args
*/
private String getConnectionUrl(){
//jdbc:jtds:sqlserver://192.168.1.200:1433/loadShedding
//return url+serverName+":"+portNumber+";databaseName="+databaseName+";selectMethod="+selectMethod+";";
return url+serverName+":"+portNumber+"/"+databaseName;
}
public java.sql.Connection dbconnect() {
// TODO Auto-generated method stub
try {
//Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Class.forName("net.sourceforge.jtds.jdbc.Driver");
//jdbc:jtds:sqlserver://192.168.1.200:1433/loadShedding
con = DriverManager.getConnection(getConnectionUrl(), userName, pass);
// if(con!=null) System.out.println("Connection Successful!");
}
catch(Exception e) {
e.printStackTrace();
// tv.setText(e.toString());
}
return con ;
}
// public void displayDb(){
// java.sql.DatabaseMetaData dm = null;
// java.sql.ResultSet rs = null;
// try{
// con=this.dbConnect();
// }
// catch(Exception e){
// e.printStackTrace();
// }
// }
public void closeConnection(){
try{
if(con!=null)
con.close();
con=null;
}catch(Exception e){
e.printStackTrace();
}
}
}
please i need help ..... thanks guys
You get the id from the database, but you never store it anywhere.. you first need to store it in an Array or ArrayList (lets say, idList). You have to do it similar to how you store the names in a list. then:
You can get the position of the item which is clicked inside the onItemClick method as
follows:
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
int position = arg2;
clickedID = idList.get(position);
// do something with the clicked id.
}

Android spinner calculation with variables

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) {
}
}

populate spinner from string array

I'm pretty new to this, and I have a question that is probably pretty simple.
I have 3 spinners, and I want to populate each spinner from an array based on the choice the user made on the previous spinners.
Right now i have it set up to display a toast with the selected data, but I want to set up an activity to open up, but that's later. Right now I need to know how to populate the spinner from an array from the strings.xml.
.Java
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
/**
* #author madonk
*
*/
public class Region extends Activity {
Spinner sp1,sp2,sp3;
ArrayAdapter<String> reg_adp,sw_city_adp,sw_lake_charles_adp;
List<String> regions,sw_cities,sw_lake_charles;
int pos;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_region);
regions=new ArrayList<String>();
regions.add("Select a Region");
regions.add("Southwest");
sp1= (Spinner) findViewById(R.id.regions_spinner);
sp2= (Spinner) findViewById(R.id.sw_city_spinner);
sp3= (Spinner) findViewById(R.id.sw_lake_charles_spinner);
reg_adp=new ArrayAdapter<String> (this,android.R.layout.simple_dropdown_item_1line,regions);
reg_adp.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
sp1.setAdapter(reg_adp);
sp1.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
pos=arg2;
add();
}
private void add() {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), ""+pos, Toast.LENGTH_SHORT).show();
switch(pos)
{
case 0:
sw_cities= new ArrayList<String>();
sw_cities.add("Select a City");
sw_city_adp=new ArrayAdapter<String>(Region.this,
android.R.layout.simple_dropdown_item_1line,sw_cities);
sw_city_adp.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
sp2.setAdapter(sw_city_adp);
select();
break;
case 1:
sw_cities= new ArrayList<String>();
sw_cities.add("Select a City");
sw_cities.add("Lake Charles");
sw_cities.add("Iowa");
sw_cities.add("Lake Arthur");
sw_city_adp=new ArrayAdapter<String>(Region.this,
android.R.layout.simple_dropdown_item_1line,sw_cities);
sw_city_adp.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
sp2.setAdapter(sw_city_adp);
select();
break;
}
}
private void select() {
// TODO Auto-generated method stub
sp2.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelectedregions(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
}
public void onNothingSelectedregions(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
public void onNothingSelectedcities(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
stings.xml
<resources>
<string name="app_name">Louisiana Festivals</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_region">Select a Region</string>
<string-array name="regions_array">
<item >Southwest</item>
</string-array>
<string name="select_a_region">Select a Region</string>
<string-array name="southwest_cities">
<item >Lake Charles</item>
<item >Iowa</item>
</string-array>
<string name="sw_select_a_city">Select a City</string>
<string-array name="lake_charles">
<item>Contraband days Pirate Festival</item>
<item>Other festival to be determined</item>
</string-array>
</resources>
You can get a string array from strings.xml using getStringArray(). So the code snippet you want is:
String[] regionsArray = getResources().getStringArray(R.array.regions_array);
regions = new ArrayList<String>(Arrays.asList(regionsArray));
Now whatever you enter into regions_array will end up in the regions ArrayList.

ListView not updated after database is changed

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.

Categories

Resources