I have a spinner that show my array data list and delete button.
What I am trying to do is when I click on the delete button, it automatically deletes a selected spinner value, but I'm not certain how to do this.
In the delete button click function, deleted the selected spinner value after debugging my activity again but I want delete automatically a selected spinner value when I click on the delete button.
package quesansw.the1;
import java.util.ArrayList;
import android.app.Activity;
import android.app.Dialog;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.NetworkInfo.State;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
public class View1 extends Activity {
SQLiteDatabase db;
ArrayAdapter adapter;
private String array_spinner[];
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = openOrCreateDatabase("mydatabase.db",
SQLiteDatabase.CREATE_IF_NECESSARY, null);
final Dialog d1 = new Dialog(this);
Window window = d1.getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,
WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
//d1.setTitle("Login");
d1.setContentView(R.layout.view);
d1.show();
Button Click = (Button) d1.findViewById(R.id.Click);
Button Save = (Button) d1.findViewById(R.id.Save);
Button Delete = (Button) d1.findViewById(R.id.Delete);
ArrayList<String> list = new ArrayList<String>();
Cursor cursor = db.rawQuery("select * from records", null);
list.add("");
if (cursor.moveToFirst())
{
do
{
list.add(cursor.getString(0));
}
while (cursor.moveToNext());
}
/*array_spinner=new String[20];
array_spinner[0]=list.get(0);*/
Spinner s = (Spinner) d1.findViewById(R.id.tittle_spinner);
adapter = new ArrayAdapter<Object>(this,android.R.layout.simple_spinner_item, list.toArray());
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(adapter);
/*Save.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Spinner s = (Spinner) d1.findViewById(R.id.tittle_spinner);
String str = s.getSelectedItem().toString();
System.out.println("********"+str);
Cursor cur1=db.rawQuery("select * from records where tittle='"+str+"' ",null);
cur1.moveToNext();
String str1=cur1.getString(1);
EditText ans = (EditText) d1.findViewById(R.id.text);
ans.setText(str1);
}
});*/
Delete.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Spinner s = (Spinner) d1.findViewById(R.id.tittle_spinner);
String str = s.getSelectedItem().toString();
db.execSQL("delete from records where tittle='"+str+"' ");
}
});
Click.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Spinner s = (Spinner) d1.findViewById(R.id.tittle_spinner);
String str = s.getSelectedItem().toString();
System.out.println("********"+str);
Cursor cur1=db.rawQuery("select * from records where tittle='"+str+"' ",null);
cur1.moveToNext();
String str1=cur1.getString(1);
EditText ans = (EditText) d1.findViewById(R.id.text);
ans.setText(str1);
}
});
}
}
1) Here is my activity screen shot
2) Another screen shot with spinner values:
Why are you declaring and initializing your Spinner so many times? Just do it once
public class View1 extends Activity {
SQLiteDatabase db;
ArrayAdapter adapter;
private String array_spinner[];
Spinner spinner; // Declare your spinner here
then in onCreate()
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db = openOrCreateDatabase("mydatabase.db",
SQLiteDatabase.CREATE_IF_NECESSARY, null);
spinner = (Spinner) d1.findViewById(R.id.tittle_spinner); //initialize your spinner here
final Dialog d1 = new Dialog(this);
then when you click delete button call adapter.notifyDataSetChanged() to update your Array and spinner
In deleteButton's onClickListener, remove the selected spinner value from the array data list and call onnotifydatasetChanges or again setSpinner adapter with the new array list after deletion.
public class MainActivity extends Activity {
Spinner spin;
Button delete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
delete = (Button) findViewById(R.id.button1);
spin = (Spinner) findViewById(R.id.spinner1);
final ArrayList<String> spinneritems = new ArrayList<String>();
spinneritems.add("item 1");
spinneritems.add("item 2");
spinneritems.add("item 3");
spinneritems.add("item 4");
spinneritems.add("item 5");
final ArrayAdapter<String> adp = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,spinneritems );
adp.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(adp);
delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String selectedSpinner = spin.getSelectedItem().toString();
spinneritems.remove(selectedSpinner);
adp.notifyDataSetChanged();
}
});
}
}
}
On delete button click listener add following code
Spinner s = (Spinner) d1.findViewById(R.id.tittle_spinner);
String str = s.getSelectedItem().toString();
adapter.remove(str);
adapter.notifyDataSetChanged();
s.setSelection(0);
Related
I can't make the spinner write to the database. I read the docs about spinner, but I'm definitely doing something wrong. Can someone give some advice?
I've read many tutorials but I'm getting confused. How can I make the spinner write to database in the onClick in which I have already on input and want to add 1 more including the spinner.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class AddActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
DatabaseHelper mylogsDB;
Button btn_save;
EditText etHours;
Spinner etShift;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
etHours = (EditText) findViewById(R.id.editText);
etShift = (Spinner) findViewById(R.id.spinner);
btn_save = (Button) findViewById(R.id.btn_save);
mylogsDB = new DatabaseHelper(this);
AddData();
// Spinner click listener
etShift.setOnItemSelectedListener(this);
// Spinner Drop down elements
List<String> categories = new ArrayList<>();
categories.add("Πρωί");
categories.add("Μεσημέρι");
categories.add("Νύχτα");
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
etShift.setAdapter(dataAdapter);
}
public void onItemSelected (AdapterView <?> parent, View view,int position, long id) {
// On selecting a spinner item
String item = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "Έχετε επιλέξει: " + item, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
public void AddData() {
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String hours = etHours.getText().toString();
String shift = etShift.getSelectedItem().toString();
boolean insertData = mylogsDB.addData(hours, shift);
if (insertData == true) {
Toast.makeText(AddActivity.this, "Η αποθήκευση ολοκληρώθηκε επιτυχώς.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(AddActivity.this, "Ώχ,Κάτι πήγε στραβά.", Toast.LENGTH_LONG).show();
}
}
});
}
}
You need to keep the selected value from the Spinner and then use it in the method of which you use to insert into database
Also you should call AddData(); in your btn_save onClick event !
public class AddActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
DatabaseHelper mylogsDB;
Button btn_save;
EditText etHours;
Spinner etShift;
private String spinnerSelectedItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
etHours = (EditText) findViewById(R.id.editText);
etShift = (Spinner) findViewById(R.id.spinner);
btn_save = (Button) findViewById(R.id.btn_save);
mylogsDB = new DatabaseHelper(this);
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddData();
}
});
// Spinner click listener
etShift.setOnItemSelectedListener(this);
// Spinner Drop down elements
List<String> categories = new ArrayList<>();
categories.add("Πρωί");
categories.add("Μεσημέρι");
categories.add("Νύχτα");
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
etShift.setAdapter(dataAdapter);
}
public void onItemSelected (AdapterView <?> parent, View view,int position, long id) {
// On selecting a spinner item
spinnerSelectedItem = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "Έχετε επιλέξει: " + spinnerSelectedItem, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
public void AddData() {
String hours = etHours.getText().toString();
//spinnerSelectedItem should have a value
if(!hours.equals("") && !spinnerSelectedItem.equals("")){
boolean insertData = mylogsDB.addData(hours, spinnerSelectedItem);
if (insertData == true) {
Toast.makeText(AddActivity.this, "Η αποθήκευση ολοκληρώθηκε επιτυχώς.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(AddActivity.this, "Ώχ,Κάτι πήγε στραβά.", Toast.LENGTH_LONG).show();
}
}else{
//do something
}
}
}
I got an activity that is called from main activity. In the activity, i got database connections established and i fill a spinner according to db data. When a user selects one of the spinner items and press the button, the activity finishes and returns a value to the main activity (activity on result). But the button in the activity doesnt work, so the activity never returns a value to main activity. Here is the code:
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
public class mySpinnerClass extends Activity implements
OnItemSelectedListener {
private VeriTabani veritabani;
private SQLiteDatabase db;
Spinner spinner;
Button btnAdd;
String dataBaseName;
int selectedValue;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.spinner);
dataBaseName = "";
selectedValue = -1;
Intent i = getIntent();
dataBaseName = i.getStringExtra("dataBaseName");
veritabani = new VeriTabani(this);
db = veritabani.getWritableDatabase();
// Spinner element
spinner = (Spinner) findViewById(R.id.mySpinner);
// add button
btnAdd = (Button) findViewById(R.id.addButton);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Loading spinner data from database
loadSpinnerData();
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
if (dataBaseName == "phoneOrientation") {
Intent intent = getIntent();
intent.putExtra("phoneOrientation", selectedValue);
setResult(RESULT_OK, intent);
finish();
}
else if(dataBaseName== "phonePosition") {
Intent intent = getIntent();
intent.putExtra("phonePosition", selectedValue);
setResult(RESULT_OK, intent);
finish();
}
else if(dataBaseName =="Label"){
Intent intent=getIntent();
intent.putExtra("label",selectedValue);
setResult(RESULT_OK, intent);
finish();
}
}
});
}
private void loadSpinnerData() {
// Spinner Drop down elements
List<String> lables = getAllLabels();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
public List<String> getAllLabels() {
List<String> labels = new ArrayList<String>();
// Select All Query
String selectQuery = "SELECT * FROM " + dataBaseName;
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(cursor.getColumnIndex("isim")));
} while (cursor.moveToNext());
}
// closing connection
// returning lables
return labels;
}
public int returnID(String item) {
int toBereturnedID;
Cursor myCursor = db.rawQuery("SELECT _id from " +dataBaseName+ " WHERE isim="+"'"+item+"'", null);
myCursor.moveToFirst();
toBereturnedID = myCursor.getInt(0);
return toBereturnedID;
}
public void onItemSelected(AdapterView<?> parent, View arg1, int position, long arg3) {
// TODO Auto-generated method stub
String label = parent.getItemAtPosition(position).toString();
selectedValue = returnID(label);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
You are calling loadSpinnerData(); method in onCreate() of activity so dataBaseName is always going to be empty, so you want to have value of spinner at time click you need to call that with on onClick() method of button, which will give you correct dataBaseName and use dataBaseName.equals("phoneOrientation") instead of dataBaseName == "phoneOrientation"
Try creating a new Intent instead of getIntent().
Intent intent=new Intent();
intent.putExtra("label",selectedValue);
setResult(RESULT_OK, intent);
finish();
Hope it helps.
I newbie in this field.
my application have 6 buttons with different category. when i click on one of the button it will go to another page for displaying listView for particular category in my database.
my problem is, I don't know how do switch case for this method.
Log.d("Reading", "Reading all Kategori ..");
List<UkmLocation> kategori = db.getCategoryFaculty();
for(UkmLocation k : kategori) {
results.add(k.getName());
results_id.add(k.getID());
}
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.textView1,results);
setListAdapter(adapter);
I want to include getCategoryHall, getCategoryFacilty,and getCategoryAdmin in this QSFacultyLocation.java. so that, i no need to create another activity merely to get getCategoryHall, getCategoryFacilty,and getCategoryAdmin (listView).Because it just using same coding.
below is my full code for:
QSFacultyLocation.java
package com.example.ukmlocationsearching;
import java.util.ArrayList;
import java.util.List;
import com.example.ukmlocationsearching.R;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class QSFacultyLocation extends ListActivity {
//------------------------------------------------------------------
// Declaration
public static UkmLocation selectedPOI = null;
final DatabaseHandler db = new DatabaseHandler(this);
private EditText filterText = null;
ArrayAdapter<String> adapter = null;
final ArrayList<String> results = new ArrayList<String>();
final ArrayList<String> results_id = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.qs_faculty_location);
final Intent c = new Intent(QSFacultyLocation.this, QSLocationDetail.class);
//------------------------------------------------------------------
// Link editText to layout item
filterText = (EditText) findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
//------------------------------------------------------------------
// Reading Poi
/*SearchKategori searchKategori = new SearchKategori();
UkmLocation selectedKategori = searchKategori.getSelectedKategori();
List<UkmLocation> locationList = null;*/
Log.d("Reading", "Reading all Kategori ..");
List<UkmLocation> kategori = db.getCategoryFaculty();
//------------------------------------------------------------------
// Determine list POI with category
for(UkmLocation k : kategori) {
results.add(k.getName());
results_id.add(k.getID());
}
//------------------------------------------------------------------
// Set list arrayAdapter to adapter
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.textView1,results);
setListAdapter(adapter);
//------------------------------------------------------------------
// Set ListView from ListActivity
ListView lv = getListView();
lv.setTextFilterEnabled(true);
//------------------------------------------------------------------
// Set click event from listView
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
Log.d("test", "position:" + position);
Log.d("test", "actualname:" + db.getUkmLocationByName(adapter.getItem(position)).getName());
// String poiID = results_id.get(position);
String poiID = db.getUkmLocationByName(adapter.getItem(position)).getID();
setSelectedPoi(poiID);
startActivity(c);
}
});
//------------------------------------------------------------------
// Closing db (if any)
// db.close();
}
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s);
}
};
#Override
protected void onDestroy() {
super.onDestroy();
filterText.removeTextChangedListener(filterTextWatcher);
}
public UkmLocation getSelectedPoi() {
return selectedPOI;
}
public void setSelectedPoi(String poiID) {
selectedPOI = db.getUkmLocation(poiID);
Log.d("test2", "_id:" + db.getUkmLocation(poiID).getID());
Log.d("test2", "Name:" + db.getUkmLocation(poiID).getName());
// Closing db
db.close();
}
}
QuickSearchMenu.java
package com.example.ukmlocationsearching;
import java.io.IOException;
import com.example.ukmlocationsearching.R;
import com.example.ukmlocationsearching.R.id;
import com.example.ukmlocationsearching.R.layout;
import com.example.ukmlocationsearching.R.menu;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.SQLException;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class QuickSearchMenu extends Activity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
//---------------------------------------------------------------------------
// Initiate database data
initiateDb();
//---------------------------------------------------------------------------
super.onCreate(savedInstanceState);
setContentView(R.layout.quick_search_menu);
View faculty = findViewById(R.id.button2);
faculty.setOnClickListener(this);
View researchInstitute = findViewById(R.id.button1);
researchInstitute.setOnClickListener(this);
View college = findViewById(R.id.button3);
college.setOnClickListener(this);
View admin = findViewById(R.id.button4);
admin.setOnClickListener(this);
View facility = findViewById(R.id.button5);
facility.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.quick_search_menu, menu);
return true;
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1:
Intent b1 = new Intent(this, QSResearch.class);
startActivity(b1);
break;
case R.id.button2:
Intent b2 = new Intent(this,QSFacultyLocation.class);
startActivity(b2);
break;
/*case R.id.button3:
Intent b3 = new Intent(this,QuickSearchCollege.class);
startActivity(b3);
break;
case R.id.button4:
Intent b4 = new Intent(this,QuickSearchFaculty.class);
startActivity(b4);
break;
case R.id.button5:
Intent b5 = new Intent(this,QuickSearchCollege.class);
startActivity(b5);
break;*/
}
}
//---------------------------------------------------------------------------
// Initiate database data
public void initiateDb() {
DatabaseHandler myDbHandler = new DatabaseHandler(this);
try {
myDbHandler.createDataBase();
}
catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHandler.openDataBase();
}
catch(SQLException sqle) {
throw sqle;
}
Log.d("Initiate", "UKM Location Count: " + myDbHandler.getUkmLocationCount());
/*Log.d("Initiate", "Kategori Count: " + myDbHandler.getKategoriCount());
Log.d("Initiate", "KategoriPoi Count: " + myDbHandler.getKategoriPoiCount());*/
myDbHandler.close();
}
//------------------------------------------------------------------------------
}
please do help me solve this. thank you
First,pass a query or simply any key value such as department id or department name as an intent with each button click using
intentname.putExtra(keyname_used_to_retrieve_value,value_to_be_passed_to_next_activity);
case R.id.button1:
String query="select * from table_name where something='xyz'";
Intent b1 = new Intent(this, QSResearch.class);
b1.putExtra("myextrakey",query);
startActivity(b1);
Then, receive the intent in the onCreate method of list activity as follows,initialise database and call user defined mylist() and setuplist() functions
Intent i=getIntent();
String x=i.getStringExtra("myextrakey");//this assigns the query to string x
//open database here
mylist();//call myList function which i have defined in the following lines
setUpList();//call setUpList function which i have defined in the following lines
This is the myList function:
private void myList() {
myownlist= new ArrayList<String>();
Cursor myCursor = database.rawQuery(x,null);
myCursor.moveToFirst();
if(!myCursor.isAfterLast()) {
do {
//selects data in column 2 to be displayed on list
String listitem= myCursor.getString(2);
myownlist.add(listitem);
} while (myCursor.moveToNext());
}
myCursor.close();
}
This is the setUpList() function:
private void setUpList() {
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, myownlist));
ListView lv = getListView();
}
I can't get my ListView work. When i run emulator it doesn't display ListView with data from databse wihich I created.
I would like to insert data to database through EditText and then display data
Main Program
package test.test;
import java.util.ArrayList;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class TestActivity extends Activity {
/** Called when the activity is first created. */
private ListView listview;
private TextView textview;
private Button button;
private EditText edittext;
SQLiteDatabase databas;
//private String[] test = {"abc","abc","abc", "abc", "abc", "abc"};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<String> test2 = new ArrayList<String>();
listview = (ListView)findViewById(R.id.test);
textview = (TextView)findViewById(R.id.mm);
button = (Button)findViewById(R.id.kanp);
edittext = (EditText)findViewById(R.id.textetid);
databas = (new dbHelper(this)).getWritableDatabase();
final ContentValues values = new ContentValues();
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Editable ord = edittext.getText();
String ordDb = ord.toString();
//String sql = "INSERT INTO ordlista (ord) " +
//"VALUES (" + ordDb + ")";
//databas.rawQuery(sql, null);
values.put("ord", ordDb);
long varde = databas.insert("ordlista", null, values);
String varde2 = Long.toString(varde);
textview.setText(varde2);
}
});
//#############################TORSDAG###############################
Cursor c = databas.rawQuery( "select ord from ordlista", null);
startManagingCursor(c);
int n = 1;
while(c.isBeforeFirst() == false){
String dbVarde = c.getString(n);
test2.add(dbVarde);
c.moveToNext();
n++;
}
ArrayAdapter<String> aa;
aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, test2);
listview.setAdapter(aa);
//listview.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, test));
}
}
You could try using a SimpleCursorAdapter and save the overhead of maintaining an ArrayAdapter. Rather than having to populate an ArrayList all the time, you can just create a Cursor against the query when you need it updated and set the ListView's adapter. A SimpleCursorAdapter also has the added benefit of handling the list item's population for you based on the columns you provide.
For example:
String[] fieldsFromDB = new String[] {"ord"};
int[] fieldsOnListItem = new int[] {android.R.id.text1};
Cursor c = databas.rawQuery("select ord from ordlista", null);
listview.setAdapter(new SimpleCursorAdapter(this,android.R.layout.simple_list_item_1,c,fieldsFromDB,fieldsOnListItem));
Something is wrong with my code. In the application, when I "add item", it doesn't show anything, and if I am clicking somewhere around the Android application, then "item" sometimes comes.
Can somebody help me?
package com.example.proov;
import java.util.ArrayList;
import com.example.proov.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class proovin extends Activity {
private ListView LView;
ArrayList <String>ar = new ArrayList<String>();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LView = (ListView) findViewById(R.id.ListView01);
// Set option as Multiple Choice. So that user can able to select more the one option
LView.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, ar));
LView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Button b = (Button) findViewById(R.id.add_item);
final EditText d = (EditText) findViewById(R.id.title);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ar.add(d.getText().toString());
}
});
}
}
Use below code instead of your code.
public class proovin extends Activity {
private ListView LView;
ArrayList <String>ar = new ArrayList<String>();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LView = (ListView) findViewById(R.id.ListView01);
// Set option as Multiple Choice. So that user can able to select more
// the one option
final ArrayAdapter<String> adpt=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, ar);
LView.setAdapter(adpt);
LView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Button b = (Button) findViewById(R.id.add_item);
final EditText d = (EditText) findViewById(R.id.title);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ar.add(d.getText().toString());
adpt.setNotifyOnChange(true);
LView.setAdapter(adpt);
}
});
}
}
The item is likely getting added to the ArrayList, but that is different from getting added to the ListView. You need to tell the ListView that you updated the data model so that it knows to look. See ArrayAdapter.notifyDatasetChanged()
you can use this add string to list on a button click
final String a[]={"hello","world"};
final ArrayAdapter<String> at=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,a);
final ListView sp=(ListView)findViewById(R.id.listView1);
sp.setAdapter(at);
final EditText et=(EditText)findViewById(R.id.editText1);
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
int k=sp.getCount();
String a1[]=new String[k+1];
for(int i=0;i<k;i++)
a1[i]=sp.getItemAtPosition(i).toString();
a1[k]=et.getText().toString();
ArrayAdapter<String> ats=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,a1);
sp.setAdapter(ats);
}
});