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));
Related
this is my saveddata.java page who can I solve
when I want to update data its say number expectation
and data insert but not update
I am trying to take the input values from EditText and I want to save it to SQLite Database. I don't know how to use the logcat [also please explain how can I read the errors from the LogCat].
package com.turningpoint.currencycounter;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class saveddata extends Activity{
DBHelper mydb;
private ListView obj;
ListViewAdapter lviewAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.saveditem);
ListViewAdapter arrayAdapter;
mydb = new DBHelper(this);
List<String> friendsnames= mydb.getAllCotacts();
List<String> friendsnames2= mydb.getAllCotacts2();
String frnames[]=friendsnames.toArray(new String[friendsnames.size()]);
String frnames2[]=friendsnames2.toArray(new String[friendsnames2.size()]);
arrayAdapter = new ListViewAdapter(this, frnames, frnames2);
obj = (ListView)findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
obj.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
// TODO Auto-generated method stub
int id_To_Search = arg2;
List array_list = mydb.getAllCotacts();
String s = array_list.get(id_To_Search).toString();
Cursor c2 = mydb.getData4(s);
while (c2.moveToNext()) {
String id = c2.getString(0);
String code = c2.getString(1);
// String code ..give me Number inut Expetation
int id2 = Integer.parseInt(id);
int code2 = Integer.parseInt(code);
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id2);
int update=1;
dataBundle.putInt("update", update);
dataBundle.putInt("code", code2);
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
intent.putExtras(dataBundle);
Toast.makeText(getApplicationContext(), code, Toast.LENGTH_SHORT).show();
startActivity(intent);
}
Toast.makeText(getApplicationContext(), s,Toast.LENGTH_SHORT).show();
}
});
}
}
Use android:inputType="number" in EditText to make sure that the input is a number not a string or a charater like this
<EditText
.
.
.
android:inputType="number"
/>
Another solution:
Check if it is a number programmatically
boolean digitsOnly = TextUtils.isDigitsOnly(editText.getText());
Read this article. You will know how to use the logcat
https://guides.codepath.com/android/Debugging-Exceptions-within-your-App
I solve this problem
int code2 = Integer.parseInt(code);
this c2.getString(1) could not Int its give me String
I have a database with for Columns {id,eng,kurd,ar} and I have populated a listview from it that shows only {eng} from the databse. I want to pass the {eng,kurd,ar} which have the same {id} when the user clicks an item in the listview, but when I click an item my app crashes, but everything else works fine there is no error in non of the other classes[adapter,sqliteopenhelper]
MainActivity.class
package com.rawa.rawadict;
import android.content.Intent;
import android.database.Cursor;
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.ListView;
import android.widget.TextView;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Adapter adapter;
ArrayList<Item> myList = new ArrayList<Item>();
ListView myListView;
Databasehelper myDbHelper = new Databasehelper(this);
String engRes,kurdRes,arRes;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
myDbHelper.createDatabase();
myDbHelper.openDatabase();
} catch (IOException e) {
throw new Error("Unable to create database");
}
Cursor cursor = myDbHelper.QueryData("select * from zankodict");
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
Item itemm = new Item();
itemm.setId(cursor.getString(0));
itemm.setEng(cursor.getString(1));
myList.add(itemm);
} while (cursor.moveToNext());
}
}
adapter = new Adapter(this, R.layout.single_row, myList);
myListView = (ListView) findViewById(R.id.lView);
myListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView text_id = (TextView) view.findViewById(R.id.tid);
String sel_id = text_id.getText().toString();
Cursor cursor = myDbHelper.QueryData("SELECT * FROM zankodict WHERE id =" + sel_id);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
engRes = cursor.getString(1);
kurdRes=cursor.getString(2);
arRes= cursor.getString(3);
} while (cursor.moveToNext());
}
}
// create intent to start another activity
Intent intent = new Intent(MainActivity.this, Result.class);
// add the selected text item to our intent.
Bundle extras = new Bundle();
extras.putString("eng",engRes);
extras.putString("kurd",kurdRes);
extras.putString("ar",arRes);
intent.putExtras(extras);
startActivity(intent);
}
}) ;
}
}
Result.class
package com.rawa.rawadict;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import java.io.IOException;
import java.util.ArrayList;
public class Result extends AppCompatActivity {
TextView etView2,ktView2,atView2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_view);
etView2 = (TextView) findViewById(R.id.etextView2);
ktView2 = (TextView) findViewById(R.id.ktextView2);
atView2 = (TextView) findViewById(R.id.atextView2);
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String enG = extras.getString("eng");
String kurD = extras.getString("kurd");
String aR = extras.getString("ar");
etView2.setText(enG);
etView2.setText(kurD);
etView2.setText(aR);
}
}
I want to pass the Bundle to Result.class
The best approach to passing data from activity to activity and particularly from your database is to pass an (id) as an intent extra then when you arrive at the destination activity, extract it and use it to query your database based on that id.
This will reduce the amount of data you will have to pass through your intent instance.
If you only want to pass 3 items however, you can use intent extras instead of a Bundle like this:
Intent intent = new Intent(MainActivity.this, Result.class);
intent.putExtra("eng",engRes);
intent.putExtra"kurd",kurdRes);
intent.putExtra("ar",arRes);
startActivity(intent);
To extract this in your Results activity;
Intent intent = getIntent();
String enG = intent.getExtras().getString("eng");
String kurD = intent.getExtras().getString("kurd");
String aR = intent.getExtras().getString("ar");
I hope this helps and good luck!
In my Android app, I made an SQLite database containig
(_id, FRIEND_NAME, FRIEND_PLACE(detailed address), FRIEND_PHONE, FRIEND_LOC(location), FRIEND_CATEG)
Also i implemented a List View wich displays all the FRIEND_NAMEs (from the database).
I want to call the selected friend when i click his name.
Infortunatly in despite of calling his number, the app calls always this number "74663".
In fact, I think that the problem is in the assignement of the variable "phone" so when i use (Intent.ACTION_CALL, Uri.parse(phone)) , it gives everytime this same number(74663) (maybe when it does "parse uri" or in the cursor of the database's listview).
1) Where is the problem?
2) Why it always gives the number 74663 to dial
3) can you (please) tell me how to assign the variable phone to get the FRIEND_PHONE of the clicked FRIEND_NAME?
this is the code of the class
`package com.softeq.prepopdb.activity;
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.softeq.android.prepopdb.R;
import com.softeq.prepopdb.dbhelper.ExternalDbOpenHelper;`
//������� ��������� �������� ������� ���� ����� ��
public class PrepopSqliteDbActivity extends ListActivity {
private static final String DB_NAME = "yourdb.sqlite";
private static final String TABLE_NAME = "friends";
private static final String FRIEND_ID = "_id";
private static final String FRIEND_NAME = "name";
public static final String FRIEND_PLACE = "place";
public static final String FRIEND_PHONE = "phone";
public static final String FRIEND_LOC = "loc";
public static final String FRIEND_CATEG = "categ";
private SQLiteDatabase database;
private ListView listView;
private ArrayList<String> friends;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//��� �������� ������
ExternalDbOpenHelper dbOpenHelper = new ExternalDbOpenHelper(this, DB_NAME);
database = dbOpenHelper.openDataBase();
//��� ���� ����������
fillFreinds();
setUpList();
}
//filling the list with friends//
private void fillFreinds() {
friends = new ArrayList<String>();
Cursor friendCursor = database.query(TABLE_NAME,
new String[]
{FRIEND_ID, FRIEND_NAME,FRIEND_PLACE,FRIEND_PHONE,FRIEND_LOC,FRIEND_CATEG},
null, null,null,null, FRIEND_CATEG);
friendCursor.moveToFirst();
if(!friendCursor.isAfterLast()) {
do {
String name = friendCursor.getString(1);
String phone= friendCursor.getString(3);
friends.add(name);
friends.add(phone);
} while (friendCursor.moveToNext());
}
friendCursor.close();
}
//setting up the list to call (or dial) a friend's number onItemClick
private void setUpList() {
setListAdapter(new ArrayAdapter<String>(this,android.R.layout. simple_expandable_list_item_1 , friends));
listView = getListView();
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position,long id) {
String phone = "tel:" + FRIEND_PHONE.toString().trim();
Intent i = new Intent(Intent.ACTION_CALL, Uri.parse(phone));
startActivity(i);
}
});
}
}
Create two separate lists for names and phones.
ArrayList<String> names;
ArrayList<String> phones;
Change this portion of your code:
do {
String name = friendCursor.getString(1);
String phone = friendCursor.getString(3);
names.add(name);
phones.add(phone);
} while (friendCursor.moveToNext());
Set names as the data source of your adapter.
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, names));
And access the appropriate phone number in the list like this:
String phone = "tel:" + phones.get(position);
Intent i = new Intent(Intent.ACTION_CALL, Uri.parse(phone));
startActivity(i);
Obviously you will give same value.
use getItemAtPosition(position); to get the exact item on which you have clicked.
i want to populate my userinterface elements with data from my database
reading the database happens over my according database class (AbezoeAdapter)
populating my userinterface is done by my mainclass (Bezoekrapporten)
now i am struggling with following code to get my idea working
package com.example.deceunincktechniekers;
import java.util.Date;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.content.res.*;
import android.database.Cursor;
#SuppressLint("SimpleDateFormat") public class bezoekrapporten extends Activity
{
TextView controlelijn;
EditText scanzonedata;
String scanzonestring;
String sScan;
String Bezoeknummer;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.bezoekrapporten);
//////////////////////// here is some code missing///////////////////////////
private void vulbezoekrapportboxin(String bezoeknummer) {
ABezoeAdapter bezoe = new ABezoeAdapter(this);
TextView bezoekrapportnummer;
bezoekrapportnummer = (TextView) findViewById(R.id.boxbrBrnum);
TextView servicenummer;
servicenummer = (TextView) findViewById(R.id.boxbrServicenum);
TextView datum;
datum = (TextView) findViewById(R.id.boxbrBrdatum);
TextView klantnaam;
klantnaam = (TextView) findViewById(R.id.boxbrKlant);
TextView straatnaam;
straatnaam = (TextView) findViewById(R.id.boxbrAdres);
TextView gemeente;
gemeente = (TextView) findViewById(R.id.boxbrGemeente);
TextView machinenummer;
machinenummer = (TextView) findViewById(R.id.boxbrMachinenr);
TextView merk;
merk = (TextView) findViewById(R.id.boxbrMerk);
TextView serienummer;
serienummer = (TextView) findViewById(R.id.boxbrSerial);
if(bezoeknummer == null)
{
bezoekrapportnummer.setText("-----");
}
else
{
Cursor c =bezoe.leesgegevens(bezoeknummer);
if (c.moveToFirst()){
while(!c.isAfterLast()){
String data = c.getString(c.getColumnIndex("bezoekrapportdatum"));
controlelijn.setText(data);
c.moveToNext();
}
}
c.close();
bezoekrapportnummer.setText(bezoeknummer);
}
return;
}
and the code snippet from AbezoeAdapter
package com.example.deceunincktechniekers;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.*;
import android.util.Log;
public class ABezoeAdapter extends ADbAdapter {
public static final String recordnummer = "RECNUM";
public static final String bezoekrapportnummer = "Z01";
public static final String bezoekrapportdatum = "Z02";
public static final String herstellingsoort = "Z03";
//////////////////here is some code missing///////////////////////////:
public static final String basisservicenummer = "Z27";
public static final String verzonden = "Z28";
public static final String[] allekolommen = new String[] {bezoekrapportnummer + " AS _id", bezoekrapportdatum,
herstellingsoort, totaleduur, servicenummer, ONBEKEND, klantnaam, adres, machinenummer, omschrijving,
duur, postcode, gemeente, merk, model, serienummer, opmerkingen, werkgereed, extratijd, urenstand, gecontroleerdbureel,
onderhoudsfiche, uitsplitsen, opmerkingbureel, ONBEKEND2, orderverwerkdatum, ordernummer, basisservicenummer, verzonden};
//////////////////////////////here is some code missing/////////////////////////////////////////////
public Cursor leesgegevens(String bezoeknummer) {
open();
Cursor c = onzedatabase.query(true, databasetabel, allekolommen,
"_id" + "=?", new String[] { bezoeknummer }, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
Log.i("cursor leesgegevens", c.toString());
sluit();
return c;
/////////////////////////////////////here is some code missing//////////////////
can anybody inform me with the best way of working to get the data from the database to my UI?
if i am already able to compile my code i get an error in my logcat that looks as follows:
11-24 15:58:34.089: E/AndroidRuntime(785): FATAL EXCEPTION: main
11-24 15:58:34.089: E/AndroidRuntime(785): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.deceunincktechniekers/com.example.deceunincktechniekers.bezoekrapporten}: java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
Here's how I did one of my adapters. First, here's the code that does the query:
private void query (long uuid)
{
// Fill list using adapter
String cols[] = { Instances.TITLE }; // dummy field; we will set all fields together in ViewBinder
int fields[] = { R.id.node_text };
cursorAdapter = new CursorAdapter (this,
R.layout.row_view,
null, // no cursor yet
cols,
fields,
Adapter.NO_SELECTION);
cursorAdapter.setViewBinder (new MyViewBinder(this));
// Setup the adapter filter - this does the query work.
cursorAdapter.setFilterQueryProvider (new FilterQueryProvider()
{
#Override
public Cursor runQuery (CharSequence constraint)
{
Cursor cursor = getContentResolver().query (...your params...);
return cursor;
}
});
listView.setAdapter (cursorAdapter);
listView.setTextFilterEnabled (true);
// Force initial query - notice we setup an adapter with a null cursor.
cursorAdapter.getFilter().filter (null);
}
Notice I did not subclass the adapter. Instead, I subclassed ViewBinder. Normally one lets each call to ViewBinder set one view at a time. I thought it would be more efficient to do all the views together. Here's how I did it:
private class MyViewBinder implements ViewBinder
{
#Override
public boolean setViewValue (View view, Cursor cursor, int column)
{
// Do all columns in one pass.
if (column != SelectAndroidEvent.instancesTitleCol)
throw new IllegalStateException ("viewbinder should only be called for title; " +
"col: " + column);
// Find encompassing layout.
ViewGroup parentView = (ViewGroup)view.getParent();
// Get fields from parentView.
TextView titleView = (TextView)view;
TextView field2 = (TextView)parentView.findViewById (R.id.field2);
...
// set all fields together - easier.
view.setText (cursor.getString (column);
field2.setText (cursor.getString (FIELD2_COL);
...
return true;
}
}
Hope this helps.
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);