i have a Activity Called "SecondActivity" below is full code
package br.exemplosqlite;
import android.app.Activity;
import android.content.Intent;
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 org.w3c.dom.Text;
public class SecondActivity extends Activity implements AdapterView.OnItemSelectedListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
//referencia a Spinner
//Spinner coligada;
//final TextView nome = (TextView)findViewById(R.id.txvNome);
//final TextView sobrenome = (TextView)findViewById(R.id.txvSobrenome);
//final Spinner pday = (Spinner)findViewById(R.id.spinner);
final Spinner spcoligada = (Spinner) findViewById(R.id.coligada);
//spinner = (Spinner)findViewById(R.id.spinner);
ArrayAdapter adaptercoligada = ArrayAdapter.createFromResource(this, R.array.coligada, android.R.layout.simple_spinner_item);
spcoligada.setAdapter(adaptercoligada);
Button ok = (Button)findViewById(R.id.btnok);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//chamada para a nova Activity
Intent intent = new Intent(SecondActivity.this, ListUsersActivity.class);
intent.putExtra("coligada", spcoligada.getSelectedItem().toString());
//intent.putExtra("nomePessoa", nome.getText().toString());
//intent.putExtra("sobrenomePessoa", sobrenome.getText().toString());
//intent.putExtra("day", pday.getSelectedItem().toString());
startActivity(intent);
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
}
But , what i really want is , pass the item selected on Spinner , go to my BD.class on query , below is my "BD.class"
package br.exemplosqlite;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.provider.SyncStateContract;
import android.widget.Spinner;
public class BD {
private SQLiteDatabase bd;
public BD(Context context){
BDCore auxBd = new BDCore(context);
bd = auxBd.getWritableDatabase();
}
public void inserir(Produtos produtos){
ContentValues valores = new ContentValues();
valores.put("item", produtos.getItem());
valores.put("coligada", produtos.getColigada());
valores.put("filial", produtos.getFilial());
bd.insert("produtos2", null, valores);
}
public void atualizar(Produtos produtos){
ContentValues valores = new ContentValues();
valores.put("item", produtos.getItem());
valores.put("coligada", produtos.getColigada());
valores.put("filial", produtos.getFilial());
bd.update("produtos2", valores, "_id = ?", new String[]{""+produtos.getId()});
}
public void deletar(Produtos produtos){
bd.delete("produtos2", "_id = "+produtos.getId(), null);
}
public List<Produtos> buscar(){
List<Produtos> list = new ArrayList<Produtos>();
String[] colunas = new String[]{"_id", "item", "coligada","filial"};
Cursor cursor = bd.rawQuery("select * from produtos2",null);
if(cursor.getCount() > 0){
cursor.moveToFirst();
do {
Produtos p = new Produtos();
p.setId(cursor.getLong(0));
p.setItem(cursor.getString(1));
p.setColigada(cursor.getString(2));
p.setFilial(cursor.getString(3));
list.add(p);
} while(cursor.moveToNext());
}
return(list);
}
}
so , i want change this : Cursor cursor = bd.rawQuery("select * from produtos2",null);
to this :
Cursor cursor = bd.rawQuery("select * from "+itemselected,null);
That is the code for your solution.
Spinner spcoligada = (Spinner) findViewById(R.id.coligada);
private static final String itemSelected=spcoligada.getSelectedItem();
Cursor cursor = bd.query(itemSelected, new String[]{ColumnName1, ColumnName2, Column2,ColumnName3,ColumnName4},
null, null, null, null, null);
I have found the Solution.
I create a class Global , and after this i assing the value of global variable to my Spiner on Select .
Related
when I click delete it doesn't delete or edit the row I created
so my MainActivity is
package com.frolicfreak.bhushan.memo;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import static com.frolicfreak.bhushan.memo.DatabaseHelper.Table_Name;
import static com.frolicfreak.bhushan.memo.DatabaseHelper.col1;
import static com.frolicfreak.bhushan.memo.DatabaseHelper.col2;
public class MainActivity extends AppCompatActivity implements
View.OnClickListener{
FloatingActionButton fab;
DatabaseHelper mydb;
ListView listView;
ArrayAdapter<String> mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mydb =new DatabaseHelper(this);
fab= (FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(this);
ListView listView = (ListView)findViewById(R.id.list);
registerForContextMenu(listView);
}
#Override
public void onResume() {
super.onResume();
ArrayList<String> theList =new ArrayList<>();
Cursor data= mydb.getAllData();
listView = (ListView)findViewById(R.id.list);
listView.setAdapter(null);
if (data.getCount()==0){
Toast.makeText(MainActivity.this,"data not inserted",Toast.LENGTH_LONG).show();
}
else
{
while(data.moveToNext()){
theList.add(data.getString(1));
ListAdapter listAdapter=new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,theList);
listView.setAdapter(listAdapter);
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId()==R.id.list) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch(item.getItemId()) {
case R.id.edit:
// int count= mydb.updaterow(getString(col2),EditText.)
return true;
case R.id.delete:
int count=mydb.deleterow(getString(item.getItemId()));
onResume();
return true;
default:
return super.onContextItemSelected(item);
}
}
#Override
public void onClick(View v) {
Intent intent= new Intent(this,Main2Activity.class);
startActivity(intent);
}
}
My DataBasehelper class
package com.frolicfreak.bhushan.memo;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.EditText;
import java.util.ArrayList;
/**
* Created by BHUSHAN on 24-08-2017.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String Database_Name = "Memo.db";
public static final String Table_Name = "Memo";
public static final String col1 = "ID";
public static final String col2 = "data";
//DatabaseHelper mydb;
public DatabaseHelper(Context context) {
super(context, Database_Name, null, 1);
//mydb=new DatabaseHelper(context);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + Table_Name + "(ID integer primary key autoincrement, data text)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists " + Table_Name);
onCreate(db);
}
public boolean insertData(String data, String Data) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(col2, Data);
long result = db.insert(Table_Name, null, contentValues);
if (result==-1)
return false;
else
return true;
}
public ArrayList<String> getList(){
ArrayList<String> taskList = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor= db.query(Table_Name,new String[]{col1},new String(col2),null,null,null,null);
while (cursor.moveToNext()){
int index= cursor.getColumnIndex(col1);
taskList.add(cursor.getString(index));
}
cursor.close();
db.close();
return taskList;
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("SELECT * FROM " + Table_Name, null);
return res;
}
public int deleterow(String col1) {
String whereClause = "ID = ?";
String[] whereArgs = {String.valueOf(col1)};
SQLiteDatabase db = this.getWritableDatabase();
int count = db.delete(Table_Name, whereClause, whereArgs);
db.close();
return count;
}
/* public int updaterow(String oldname, String newdata){
SQLiteDatabase db= mydb.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(DatabaseHelper.col2,newdata);
String[] whereargs={oldname};
int count = db.update(Table_Name,cv, DatabaseHelper.col2+"=?" , whereargs);
return count;
}*/
}
my Main2Activity class where I edit and insert data
package com.frolicfreak.bhushan.memo;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class Main2Activity extends AppCompatActivity {
DatabaseHelper db;
EditText Data;
FloatingActionButton add;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
db = new DatabaseHelper(this);
Data = (EditText)findViewById(R.id.edit);
add =(FloatingActionButton)findViewById(R.id.add);
AddData();
}
public void AddData(){
add.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted =
db.insertData(Data.getText().toString(),
Data.getText().toString() );
if (isInserted==true)
Toast.makeText(Main2Activity.this,"data
inserted",Toast.LENGTH_LONG).show();
else
Toast.makeText(Main2Activity.this,"data not
inserted",Toast.LENGTH_LONG).show();
}
}
);
}
}
please help me I'm new to programming so I'm trying to learn here
thankyou in advance
and I actually need help with editing and saving the data too I wrote the code but I saved it in the comments
Your delete function is working fine according to the code. Check the return is greater than 0 or not.
But you won't be able to see the changes in the ListView because you have to populate the list again.
Set an CursorAdapter since you're using a database to link to the listview and use CursorAdapter.notifyDataSetChanged()
Or create a method that will recreate the listview when a delete occurs.
ArrayList<String> COUNTRIES = new ArrayList<>();
public void refreshView() {
MyDatabase database = new MyDatabase(ViewList.this);
Cursor cursor = database.fetchAllData();
COUNTRIES.clear();
while (cursor.moveToNext()) {
String temp = cursor.getString(cursor.getColumnIndex(database.COL1));
COUNTRIES.add(temp);
}
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, COUNTRIES);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(arrayAdapter);
}
When deleting, you are calling this
int count=mydb.deleterow(getString(item.getItemId()));
onResume();
You are not passing the id of selected item, but you are passing menu item's string fetched by getString(...) method, which is weird. There are so much unused code in your class.
I advice you to work on BaseAdapter and ListView.
It's not a good programming pattern to call onResume() method. You should extract it to different method and call it in onResume().
Anyway, in this case notifyDataSetChanged() is a solution what you are looking for.
i'm trying to get value from 2nd column in the database and put it into textview by clicking listview item.
DBConnection class
package com.prodev;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
/**
* Created by Dev_Mohamed_Sayed on 7/21/2017.
*/
public class DBConnection extends SQLiteOpenHelper {
public static final String DbName="azkar.db";
public static final int Version=1;
public DBConnection(Context context){
super(context,DbName,null,Version);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS azkar_main ( ID INTEGER, Name TEXT, Number INTEGER, PRIMARY KEY(ID) )");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS azkar_main");
onCreate(db);
}
public void InsertRowAdmin(String Name,Integer Number){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("Name", Name);
contentValues.put("Number", Number);
db.insert("azkar_main", null, contentValues);
}
public ArrayList getAllRecord2(){
ArrayList array_list2 = new ArrayList();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery("select * from azkar_main", null);
res.moveToFirst();
while (res.isAfterLast() == false){
array_list2.add(res.getString(res.getColumnIndex("ID"))+ " - " + res.getString(res.getColumnIndex("Name"))+ " .. " + res.getString(res.getColumnIndex("Number")));
res.moveToNext();
}
return array_list2;
}
public void delete(Integer ID){
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from azkar_main where ID="+ Integer.toString(ID));
}
}
and here is my Acivity where we should work in.
package com.prodev;
import android.content.Intent;
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.EditText;
import android.widget.ListView;
import android.R.layout;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import java.util.ArrayList;
public class ListActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
setContentView(R.layout.activity_list);
DBConnection db = new DBConnection(this);
ListView ls =(ListView)findViewById(R.id.ls);
ArrayList<String> arrlist = db.getAllRecord2();
ls.setAdapter(new ArrayAdapter<>(this, layout.simple_list_item_1, arrlist));
ListView lv = (ListView) findViewById(R.id.ls);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(ListActivity.this, MainActivity.class);
startActivity(i);
ListView lv = (ListView) findViewById(R.id.ls);
TextView tv = (TextView) findViewById(R.id.textView);
// The Missing Part
}
});
}
public void btn_save(View view){
EditText editText =(EditText)findViewById(R.id.editText);
ListView ls =(ListView)findViewById(R.id.ls);
DBConnection db = new DBConnection(this);
db.InsertRowAdmin(editText.getText().toString(), 0);
ArrayList<String> arrlist = db.getAllRecord2();
ls.setAdapter(new ArrayAdapter<>(this, layout.simple_list_item_1, arrlist));
editText.setText("");
}
public void btn_delete(View view){
EditText txt = (EditText)findViewById(R.id.del);
ListView ls = (ListView)findViewById(R.id.ls);
DBConnection db = new DBConnection(this);
db.delete(Integer.parseInt(txt.getText().toString()));
ArrayList<String> arrlist=db.getAllRecord2();
ls.setAdapter(new ArrayAdapter<>(this, layout.simple_list_item_1, arrlist));
txt.setText("");
}
}
MainActivity
package com.prodev;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.crash.FirebaseCrash;
public class MainActivity extends AppCompatActivity {
private FirebaseAnalytics mFirebaseAnalytics;
private static final String TAG = "MainActivity";
private AdView mAdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
FirebaseCrash.log("Activity created");
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.mipmap.ic_launcher);
getSupportActionBar().setDisplayUseLogoEnabled(true);
setContentView(R.layout.activity_main);
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// action with ID action_refresh was selected
case R.id.action_azkar:
Intent i = new Intent(MainActivity.this, ListActivity.class);
startActivity(i);
break;
case R.id.action_settings:
break;
default:
break;
}
return true;
}
}
Also i want to save number from variable will be declared later into database col Number..
i don't know how but i'll worry about that later..
On you list item click event,
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(ListActivity.this, MainActivity.class);
i.putExtra("keyText","value to be passed!");
startActivity(i);
}
and in you main activity,
Intent i = getIntent();
String text = i.getStringExtra("keyText");
TextView tv = (TextView) findViewById(R.id.textView);
tv.setText(text);
I am working on a sql listview , however I want to display the listview which is in an activity class (CountryListActivity.java) as a fragment in a tablayout . dbManager=newDBManager(this) gives an error when I change it to getActivity , how do I fix this?
package com.trinitytabnavigationdrawer;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
public class CountryListActivity extends ActionBarActivity {
private DBManager dbManager;
private ListView listView;
private SimpleCursorAdapter adapter;
final String[] from = new String[] {
DatabaseHelper._ID,
DatabaseHelper.SUBJECT, DatabaseHelper.DESC
};
final int[] to = new int[] {
R.id.id, R.id.title, R.id.desc
};
#
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_emp_list);
dbManager = new DBManager(this);
dbManager.open();
Cursor cursor = dbManager.fetch();
listView = (ListView) findViewById(R.id.list_view);
listView.setEmptyView(findViewById(R.id.empty));
adapter = new SimpleCursorAdapter(this, R.layout.activity_view_record, cursor, from, to, 0);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
// OnCLickListiner For List Items
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {#
Override
public void onItemClick(AdapterView <? > parent, View view, int position, long viewId) {
TextView idTextView = (TextView) view.findViewById(R.id.id);
TextView titleTextView = (TextView) view.findViewById(R.id.title);
TextView descTextView = (TextView) view.findViewById(R.id.desc);
String id = idTextView.getText().toString();
String title = titleTextView.getText().toString();
String desc = descTextView.getText().toString();
Intent modify_intent = new Intent(getApplicationContext(), ModifyCountryActivity.class);
modify_intent.putExtra("title", title);
modify_intent.putExtra("desc", desc);
modify_intent.putExtra("id", id);
startActivity(modify_intent);
}
});
}
#
Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#
Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.add_record) {
Intent add_mem = new Intent(this, AddCountryActivity.class);
startActivity(add_mem);
}
return super.onOptionsItemSelected(item);
}
}
And the database manager class is as follows :
package com.trinitytabnavigationdrawer;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class DBManager {
private DatabaseHelper dbHelper;
private Context context;
private SQLiteDatabase database;
public DBManager(Context c) {
context = c;
}
public DBManager open() throws SQLException {
dbHelper = new DatabaseHelper(context);
database = dbHelper.getWritableDatabase();
return this;
}
public void close() {
dbHelper.close();
}
public void insert(String name, String desc) {
ContentValues contentValue = new ContentValues();
contentValue.put(DatabaseHelper.SUBJECT, name);
contentValue.put(DatabaseHelper.DESC, desc);
database.insert(DatabaseHelper.TABLE_NAME, null, contentValue);
}
public Cursor fetch() {
String[] columns = new String[] {
DatabaseHelper._ID, DatabaseHelper.SUBJECT, DatabaseHelper.DESC
};
Cursor cursor = database.query(DatabaseHelper.TABLE_NAME, columns, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public int update(long _id, String name, String desc) {
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.SUBJECT, name);
contentValues.put(DatabaseHelper.DESC, desc);
int i = database.update(DatabaseHelper.TABLE_NAME, contentValues, DatabaseHelper._ID + " = " + _id, null);
return i;
}
public void delete(long _id) {
database.delete(DatabaseHelper.TABLE_NAME, DatabaseHelper._ID + "=" + _id, null);
}
}
Please I have no clue what else to do ! Been trying for a week now , sorry I'm not good at this , just following some tutorials ! :(
Initialize the dbManager and other objects which require context inside onAttach (Context context) rather than onCreateView() method of Fragment.
I am trying to get database from SQLite database and trying to populate the ListView and also adding data in ArrayList<String> . The ListView is populated nicely but problem is ArrayList<String> is not populated nicely.
Suppose I have data in database like:
A
B
C
D
E
F
G
H
I
J
K
L
M
N
........
My ListView Showing data in this way. But ArrayList<String> add the data this way:
A
B
C
D
E
F
A
B
C
D
E
F
G
H
......
That means my ArrayList<String> takes first 6 value then repeat it and then it takes next 6 value then again repeat it ..... . That means When I click item "H" from list view the ArrayList<String> shows me "B". I don't know why it is happening?
My Code, CustomList which extends CursorAdapter
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CursorAdapter;
import android.widget.TextView;
public class CustomList extends CursorAdapter {
CheckBox favoriteBox;
TextView cityName, countryName;
ArrayList<String> city_name;
ArrayList<String> country_name;
ArrayList<String> country_short;
ArrayList<CheckBox> check_box;
public CustomList(Context context, Cursor c, ArrayList<String> city_name,
ArrayList<String> country_name, ArrayList<String> country_short,
ArrayList<CheckBox> check_box) {
super(context, c, 0);
this.city_name = city_name;
this.country_name = country_name;
this.country_short = country_short;
this.check_box = check_box;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.all_city_list, parent, false);
return retView;
}
#Override
public void bindView(final View view, Context context, Cursor cursor) {
cityName = (TextView) view.findViewById(R.id.cityName);
String cityS = cursor.getString(cursor.getColumnIndex("city_name"));
cityName.setText(cityS);
city_name.add(cityS);//adding value to ArrayList<String>
countryName = (TextView) view.findViewById(R.id.countryName);
String conS = cursor.getString(cursor.getColumnIndex("country_name"));
countryName.setText(conS);
country_name.add(conS);//adding value to ArrayList<String>
country_short.add(""
+ cursor.getString(cursor.getColumnIndex("country_short")));//adding value to ArrayList<String>
favoriteBox = (CheckBox) view.findViewById(R.id.favoriteCheckBox);
check_box.add(favoriteBox);
if (cursor.getInt(cursor.getColumnIndex("favorite")) == 0) {
favoriteBox.setChecked(false);
} else {
favoriteBox.setChecked(true);
}
}
}
Class AllCityListFragment which extends Fragment
import java.io.IOException;
import java.util.ArrayList;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.Toast;
public class AllCityListFragment extends Fragment {
private CustomList customAdapter;
private DatabaseHelper databaseHelper;
ArrayList<String> city_name = new ArrayList<String>();
ArrayList<String> country_name = new ArrayList<String>();
ArrayList<String> country_short = new ArrayList<String>();
ArrayList<CheckBox> check_box = new ArrayList<CheckBox>();
public static final String ARG_OS = "OS";
int pos;
String sql = "";
ListView list;
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.all_city_layout, null);
databaseHelper = new DatabaseHelper(view.getContext());
try {
databaseHelper.createDataBase();
databaseHelper.openDataBase();
} catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(view.getContext(), "Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
list = (ListView) view.findViewById(R.id.citylist);
list.setFocusable(false);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View myview,
int position, long id) {
Toast.makeText(getActivity(),
position + " " + city_name.get(position),
Toast.LENGTH_LONG).show();
}
});
sql = "SELECT _id, city_name, country_name, country_short, favorite FROM city order by country_name asc;";
new Handler().post(new Runnable() {
#Override
public void run() {
customAdapter = new CustomList(getActivity(), databaseHelper
.getResult(sql), city_name, country_name,
country_short, check_box);
list.setAdapter(customAdapter);
}
});
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
In this picture I clicked "Shirajganj" but the Toast shows me "230 Thakurgaon" position =230 is correct but city_name.get(230) should be "Shirajganj" . I think it is doing wrong when I am trying to add value to ArrayList<String> in binView in CustomList. How can I solve this problem?
It's not a good idea to fill that array in bindView method. The Android doesn't create separate view for each row in the list, it's utilize already created ones, that's why you will always receive unexpected results in your arraylist. The better is to fill the array in your activity, instead of the adapter. Just query your database for the same result like this:
Cursor cursor = getContentResolver().query(
uri,
projection,
selectionClause
selectionArgs,
sortOrder);
while (cursor.moveToNext ()){
arrayList.add(cursor.getAsString(cursor.getColumnIndex('column_name')));
}
cursor.close()
package lab.ex1;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import lab.ex1.HospitalDatabase.Patient;
public class DisplayPatient extends HospitalActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
displayData();
}
private void displayData()
{
final List<Integer> myList = new ArrayList<Integer>();
final Intent me = new Intent(DisplayPatient.this,UpdatePatient.class);
final Bundle b = new Bundle();
//Build new Patient
PatientData build = new PatientData();
final TableLayout viewData = (TableLayout)findViewById(R.id.tblDisplay);
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(Patient.patientTableName);
SQLiteDatabase db = mDatabase.getReadableDatabase();
String asColumnsToReturn[] = {Patient.patientTableName + "." + Patient.ID,
Patient.patientTableName + "." + Patient.firstName,
Patient.patientTableName + "." + Patient.lastName,
Patient.patientTableName + "." + Patient.room,
Patient.patientTableName + "." + Patient.department};
Cursor c = queryBuilder.query(db,asColumnsToReturn,null,null,null,null,Patient.DEFAULT_SORT_ORDER);
if (c.moveToFirst())
{
for (int i=0; i< c.getCount(); i++)
{
final TableRow newRow = new TableRow(this);
Button update = new Button(this);
TextView display = new TextView(this);
display.setTextSize(15);
update.setX(15);
update.setY(10);
update.setTextSize(10);
Button deleteButton = new Button(this);
deleteButton.setX(100);
deleteButton.setY(100);
deleteButton.setTextSize(10);
deleteButton.setText("Delete");
update.setText("Update");
deleteButton.setTag(c.getInt(c.getColumnIndex(Patient.ID)));
update.setTag(c.getInt(c.getColumnIndex(Patient.ID)));
newRow.setTag(c.getInt(c.getColumnIndex(Patient.ID))); // set the tag field on the TableRow view so we know which row to delete
myList.add(c.getInt(c.getColumnIndex(Patient.ID)));
build.setID(Integer.parseInt(c.getString(c.getColumnIndex((Patient.ID)))));
build.setFirstName((c.getString(c.getColumnIndex(Patient.firstName))));
build.setLastName(c.getString(c.getColumnIndex(Patient.lastName)));
build.setDepartment(c.getString(c.getColumnIndex(Patient.department)));
build.setRoom(Integer.parseInt(c.getString(c.getColumnIndex(Patient.room))));
deleteButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Integer id = (Integer) v.getTag();
deletePatient(id);
final TableLayout patientTable = (TableLayout) findViewById(R.id.tblDisplay);
View viewToDelete = patientTable.findViewWithTag(id);
viewData.removeView(viewToDelete);
}
});
update.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Integer id = (Integer)v.getTag();
final TableLayout patientRmv = (TableLayout)findViewById(R.id.tblDisplay);
for (Integer delete : myList )
{
View viewToDelete = patientRmv.findViewWithTag(delete);
viewData.removeView(viewToDelete);
}
b.putString("key", Integer.toString(id));
me.putExtras(b);
startActivity(me);
}
});
display.setText(build.toString());
newRow.addView(display);
newRow.addView(update);
//newRow.addView(deleteButton);
viewData.addView(newRow);
c.moveToNext();
}
}
else
{
TableRow newRow = new TableRow(this);
TextView noResults = new TextView(this);
noResults.setText("No results to show.");
newRow.addView(noResults);
viewData.addView(newRow);
}
c.close();
db.close();
}
public void deletePatient(Integer id)
{
SQLiteDatabase db = mDatabase.getWritableDatabase();
String astrArgs[] = { id.toString() };
db.delete(Patient.patientTableName, Patient.ID+ "=?",astrArgs );
db.close();
}
}
package lab.ex1;
import lab.ex1.HospitalDatabase.Patient;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
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.TextView;
import android.widget.Toast;
public class UpdatePatient extends HospitalActivity {
Spinner spinner;
TextView update;
String up;
Button check;
EditText entry;
String setPosition;
TextView updateID;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.updatepatient);
check = (Button)findViewById(R.id.btnUpdate);
entry = (EditText)findViewById(R.id.editUpdate);
updateID = (TextView)findViewById(R.id.txtIDUpdate);
Bundle accept = getIntent().getExtras();
up = accept.getString("key","0");
updateID.setText(null);
updateID.setText("ID: " + up);
update = (TextView)findViewById(R.id.txtUpdateMessage);
update.setText(null);
// update.setText(up);
spinner = (Spinner) findViewById(R.id.spnChoice);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.arrFields, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
check.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
updateDB(entry.getText().toString(),setPosition,up);
}
});
}
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> adapterView,
View view, int pos, long id) {
update.setText(null);
update.setText("I will update On " + adapterView.getItemAtPosition(pos).toString());
setPosition = adapterView.getItemAtPosition(pos).toString();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
public void updateDB(String valuesToUpdate, String field,String ID)
{
SQLiteDatabase db = mDatabase.getWritableDatabase();
db.beginTransaction();
try
{
ContentValues updatePatient = new ContentValues();
if (field == "First Name")
{
updatePatient.put(Patient.firstName, valuesToUpdate);
String astrArgs[] = { up.toString() };
db.update(Patient.patientTableName,updatePatient, Patient.ID+"=?", astrArgs);
//
db.setTransactionSuccessful();
}
}
finally
{
db.endTransaction();
}
db.close();
Intent me = new Intent(UpdatePatient.this,DisplayPatient.class);
startActivity(me);
}
}
I am using Android SQLite Database. In my display class, it reads all the entries from the database and displays them along with an update button next to each entry. That entries update button's tag has entries Patient.ID. When the user clicks update, they are taken to the update class where they can select what they want to update, First Name, Last Name, Apartment, Room. Afterward they click update, to which they are taken back to the Display class and they should see there changes. However, when they are taken back, the previous value is still there, the changes do not show up, what am I missing?
Move your displaydata() call from onCreate to onResume.