Im trying to do an application that, on the first activity, user can mark several checkbox, from 1 to seven or eight (it depends on final version). When user have marked his options and he click on a "search" button, I want to show a list showing diferent objects depending on the marked items.
My objects are custom objects "ground",it have many characteristics, like strings or int-boolean (1 or 0), stored in a database sqlite.
In my main activity, I use a lot of if else to know how many of checkbox are checked, I put this information into intent via extras, and in my second activity (list) I retrieve this extras and I do another if else to know what list the app must show.
I think this method is such rudimentary because i have to do a lot of if else on both activities.
I have tried to make in the first activity a dbquery returning a list, and send this list via intent, but I have followed a lot of tutorials and always I have a list of correct number of objects but always the same overwrited object!
Any ideas of what to do?
Thank you in advance!
FIRST ACTIVITY
public class MainActivity extends Activity {
Button bafegeix, bcerca, bneteja;
ListView llista;
RadioGroup grup;
RadioButton casa, terreny;
CheckBox cbaigua, cblavabos, cbcobert, cbdutxes, cbcuina, cbadap;
protected Activity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prova__db);
bcerca = (Button) findViewById (R.id.cerca);
bneteja = (Button) findViewById (R.id.neteja);
grup = (RadioGroup)findViewById (R.id.grup);
casa = (RadioButton)findViewById (R.id.casa);
terreny = (RadioButton)findViewById (R.id.terreny);
cbaigua = (CheckBox)findViewById (R.id.aigua);
cblavabos = (CheckBox)findViewById (R.id.lavabos);
cbcobert = (CheckBox)findViewById (R.id.cobert);
cbdutxes = (CheckBox)findViewById (R.id.dutxes);
cbcuina = (CheckBox)findViewById (R.id.cuina);
cbadap = (CheckBox)findViewById (R.id.adaptada);
bcerca.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(terreny.isChecked()){
Intent iterreny = new Intent(getApplicationContext(), LlistaTerrenys.class);
iterreny.putExtra("aigua", "aigua");
iterreny.putExtra("lavabos", "lavabos");
iterreny.putExtra("cobert", "cobert");
iterreny.putExtra("dutxes", "dutxes");
startActivity(iterreny);
}else if (cbaigua.isChecked()&& cblavabos.isChecked()&&cbcobert.isChecked()&&cbdutxes.isChecked()) {
Intent iterreny = new Intent(getApplicationContext(), LlistaTerrenys.class);
iterreny.putExtra("aigua", "aigua");
iterreny.putExtra("lavabos", "lavabos");
iterreny.putExtra("cobert","cobert");
iterreny.putExtra("dutxes", "dutxes");
startActivity(iterreny);
} else if(cbaigua.isChecked()&&cblavabos.isChecked()&&cbcobert.isChecked()){
Intent iterreny = new Intent(getApplicationContext(), LlistaTerrenys.class);
iterreny.putExtra("aigua", "aigua");
iterreny.putExtra("lavabos", "lavabos");
iterreny.putExtra("cobert","cobert");
startActivity(iterreny);
}else if(cblavabos.isChecked()&&cbcobert.isChecked()&&cbdutxes.isChecked()){
Intent iterreny2 = new Intent(getApplicationContext(), LlistaTerrenys.class);
iterreny.putExtra("lavabos", "lavabos");
iterreny.putExtra("cobert", "cobert");
iterreny.putExtra("dutxes", "dutxes");
startActivity(iterreny);
}else if(cbaigua.isChecked()&&cbcobert.isChecked()&&cbdutxes.isChecked()){
Intent iterreny2 = new Intent(getApplicationContext(), LlistaTerrenys.class);
iterreny.putExtra("aigua", "aigua");
iterreny.putExtra("cobert", "cobert");
iterreny.putExtra("dutxes", "dutxes");
startActivity(iterreny);
}else if(cbaigua.isChecked()&&cblavabos.isChecked()&&cbdutxes.isChecked()){
Intent iterreny2 = new Intent(getApplicationContext(), LlistaTerrenys.class);
iterreny.putExtra("aigua", "aigua");
iterreny.putExtra("lavabos", "lavabos");
iterreny.putExtra("dutxes", "dutxes");
startActivity(iterreny);
}else if (cbaigua.isChecked()&&cblavabos.isChecked()){
Intent iterreny2 = new Intent(getApplicationContext(), LlistaTerrenys.class);
iterreny.putExtra("aigua", "aigua");
iterreny.putExtra("lavabos", "lavabos");
startActivity(iterreny);
SECOND ACTIVITY
public class LlistaTerrenys extends Activity {
ListView llista;
TextView numelements;
ArrayList<Terreny>list;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_list_contactos);
llista = (ListView)findViewById(R.id.listView1);
numelements = (TextView)findViewById(R.id.numelements);
Bundle extras = getIntent().getExtras();
String aigua = extras.getString("aigua");
String lavabos = extras.getString("lavabos");
String cobert = extras.getString("cobert");
String dutxes = extras.getString("dutxes");
String seleccio = extras.getString("noseleccio");
if (aigua!=null && lavabos!=null && cobert!=null && dutxes!=null) {
final UtilidadesSQL mydb = new UtilidadesSQL(getApplicationContext());
mydb.getAllDataTerrenyTotesCaracteristiques();
AdapterTerreny aa = new AdapterTerreny(this, mydb.getAllDataTerrenyTotesCaracteristiques());
llista.setAdapter(aa);
} else if(aigua!=null && lavabos!=null && cobert!=null){
final UtilidadesSQL mydb = new UtilidadesSQL(getApplicationContext());
AdapterTerreny aa = new AdapterTerreny(this, mydb.getAllDataTerrenyAiguaLavabosCobert());
llista.setAdapter(aa);
}else if(lavabos!=null && cobert!=null && dutxes!=null){
final UtilidadesSQL mydb = new UtilidadesSQL(getApplicationContext());
AdapterTerreny aa = new AdapterTerreny(this, mydb.getAllDataTerrenyLavabosCobertDutxes());
llista.setAdapter(aa);
}else if(aigua!=null && cobert!=null && dutxes!=null){
final UtilidadesSQL mydb = new UtilidadesSQL(getApplicationContext());
AdapterTerreny aa = new AdapterTerreny(this, mydb.getAllDataTerrenyAiguaCobertDutxes());
llista.setAdapter(aa);
}else if(aigua!=null && lavabos!=null && dutxes!=null){
final UtilidadesSQL mydb = new UtilidadesSQL(getApplicationContext());
AdapterTerreny aa = new AdapterTerreny(this, mydb.getAllDataTerrenyAiguaLavabosDutxes());
llista.setAdapter(aa);
}else if (aigua!=null && lavabos!=null ){
final UtilidadesSQL mydb = new UtilidadesSQL(getApplicationContext());
AdapterTerreny aa = new AdapterTerreny(this, mydb.getAllDataTerrenyAiguaLavabos());
llista.setAdapter(aa);
HERE DIFFERENT METHODS RETRIEVING DATA FROM SQL
public Cursor getAllDataTerrenyAigua () {
SQLiteDatabase db = getReadableDatabase();
String buildSQL = ("select * from terrenys where aigua = ?");
return db.rawQuery(buildSQL, new String[]{"1"});
}
public Cursor getAllDataTerrenyLavabos () {
SQLiteDatabase db = getReadableDatabase();
String buildSQL = ("select * from terrenys where lavabos = ?");
return db.rawQuery(buildSQL, new String[]{"1"});
}
public Cursor getAllDataTerrenyCobert () {
SQLiteDatabase db = getReadableDatabase();
String buildSQL = ("select * from terrenys where cobert = ?");
return db.rawQuery(buildSQL, new String[]{"1"});
}
public Cursor getAllDataTerrenyDutxes () {
SQLiteDatabase db = getReadableDatabase();
String buildSQL = ("select * from terrenys where dutxes = ?");
return db.rawQuery(buildSQL, new String[]{"1"});
}
public Cursor getAllDataTerrenyTotesCaracteristiques () {
SQLiteDatabase db = getReadableDatabase();
String buildSQL = ("select * from terrenys where aigua=? AND cobert=? AND dutxes=? AND lavabos=?");
return db.rawQuery(buildSQL, new String[]{"1","1","1","1"});
}
Related
I trying to Make One App in which I will be Using CSV to restore to Sqlite Database .
This Code is working Fine on Android Emulator But Not Working On Device.
Please Help I am stuck very badly from last 3 days I am unable to figured out and tried many solution from Google but none of them are working.
public class MainActivity extends ListActivity {
TextView lbl;
DBController controller;
Button btnimport;
ListView lv;
final Context context = this;
ListAdapter adapter;
ArrayList<HashMap<String, String>> myList;
public static final int requestcode = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
controller = new DBController(this);
lbl = (TextView) findViewById(R.id.txtresulttext);
btnimport = (Button) findViewById(R.id.btnupload);
lv = getListView();
btnimport.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent fileintent = new Intent(Intent.ACTION_GET_CONTENT);
fileintent.addCategory(Intent.CATEGORY_OPENABLE);
fileintent.setType("text/csv");
try {
startActivityForResult(Intent.createChooser(fileintent,"Open CSv"),requestcode);
} catch (ActivityNotFoundException e) {
lbl.setText("No activity can handle picking a file. Showing alternatives.");
}
}
});
myList = controller.getAllProducts();
if (myList.size() != 0) {
ListView lv = getListView();
ListAdapter adapter = new SimpleAdapter(MainActivity.this, myList,
R.layout.v, new String[]{"a", "b", "c"}, new int[]{
R.id.txtproductcompany, R.id.txtproductname, R.id.txtproductprice});
setListAdapter(adapter);
lbl.setText("");
}
}
/** you were wrong here
* R.id.txtjournalname, R.id.txtjournalissn, R.id.txtjournalif});
in v.xml its
R.id.txtproductcompany, R.id.txtproductname, R.id.txtproductprice});
*/
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data == null)
return;
switch (requestCode) {
case requestcode:
String filepath = data.getData().getPath();
controller = new DBController(getApplicationContext());
SQLiteDatabase db = controller.getWritableDatabase();
String tableName = "tbljournal";
db.execSQL("delete from " + tableName);
try {
if (resultCode == RESULT_OK) {
try {
FileReader file = new FileReader(filepath);
BufferedReader buffer = new BufferedReader(file);
ContentValues contentValues = new ContentValues();
String line = "";
db.beginTransaction();
buffer.readLine();
while ((line = buffer.readLine()) != null) {
String[] str = line.split(",", 4); // defining 3 columns with null or blank field //values acceptance
//Id, Company,Name,Price
String spinnerdata = str[0].toString();
String uniqueid = str[1].toString();
String melting = str[2].toString();
String weight = str[3].toString();
Log.e("data", spinnerdata);
contentValues.put("spinnerdata", spinnerdata);
contentValues.put("uniqueid", uniqueid);
contentValues.put("melting", melting);
contentValues.put("weight", weight);
db.insert(tableName, null, contentValues);
lbl.setText("Successfully Updated Database.");
}
db.setTransactionSuccessful();
db.endTransaction();
}catch (SQLException e)
{
Log.e("Error",e.getMessage().toString());
}
catch (IOException e) {
if (db.inTransaction())
db.endTransaction();
Dialog d = new Dialog(this);
d.setTitle(e.getMessage().toString() + "first");
d.show();
// db.endTransaction();
}
} else {
if (db.inTransaction())
db.endTransaction();
Dialog d = new Dialog(this);
d.setTitle("Only CSV files allowed");
d.show();
}
} catch (Exception ex) {
if (db.inTransaction())
db.endTransaction();
Dialog d = new Dialog(this);
d.setTitle(ex.getMessage().toString() + "second");
d.show();
// db.endTransaction();
}
}
myList = controller.getAllProducts();
if (myList.size() != 0) {
ListView lv = getListView();
ListAdapter adapter = new SimpleAdapter(MainActivity.this, myList,
R.layout.v, new String[]{"a", "b", "c"}, new int[]{
R.id.txtproductcompany, R.id.txtproductname, R.id.txtproductprice});
setListAdapter(adapter);
lbl.setText("Data Imported");
}
}
}
Below are LogCat
03-15 16:54:27.577 2559-2611/? E/AbstractTracker: Can't create handler inside thread that has not called Looper.prepare()
03-15 16:54:36.185 2559-2620/com.example.arnav.androidcsv.demo E/AbstractTracker: Can't create handler inside thread that has not called Looper.prepare()
03-15 16:54:46.556 2559-2763/com.example.arnav.androidcsv.demo E/AbstractTracker: Can't create handler inside thread that has not called Looper.prepare()
Once I select CSV file from file Manager Nothing Happening it get Stuck .
Hi I develop an application on android ADT. I am using sqlite to validate the registration. When the user registers are saved in a database and the database I want to check if a record already exists for the activity log is not open. This is the code that I used, not shown error but does not function.
public void onContinue(){
AdminSQLiteOpenHelper admin = new AdminSQLiteOpenHelper(this,
"pacman", null, 1);
SQLiteDatabase bd = admin.getReadableDatabase();
int total;
Cursor c = bd.rawQuery("SELECT * FROM numeros", null);
total = c.getCount();
Intent nu;
if(total == 1){
nu = new Intent (this, ContactListActivity.class);
startActivity(nu);
}
else
nu=new Intent(this, Bienvenido.class);
startActivity(nu);
finish();
}
EDIT2:
I believe you wanted to start 1 activity only but when (total == 1) you are starting 2.
You should change
if(total == 1){
nu = new Intent (this, ContactListActivity.class);
startActivity(nu);
}
else
nu=new Intent(this, Bienvenido.class);
startActivity(nu);
To
if(total == 1)
nu = new Intent (this, ContactListActivity.class);
else
nu = new Intent(this, Bienvenido.class);
startActivity(nu);
I am calling an activity namely LoginActivity.java in which i am getting values using Intent, storing data to SQLite, fetching data from SQLite and given a small condition, condition looks like this:
if(txtEvent.getText().toString().equals("") && txtOperative.getText().toString().equals(""))
{
Intent intentCall = new Intent(LoginActivity.this, LicenseListActivity.class);
startActivity(intentCall);
}
Now, how App works:-
Splash Screen > LoginActivity (if txtEvent and txtOperative equals to null) then calling > LicenseListActivity > GetEventsActivity > GetOperativesActivity (passing some values mainly EVENT & OPERATIVE name) to LoginActivity (also storing to database - checked using SQLite DB Viewer)
So issue is, instead of calling LoginActivity.java its calling LicenseListActivity.java again, after GetOperativesActivity.java ?
GetOperativesActivity.java:-
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
firstName = contactList.get(position).get(TAG_NAME);
Intent intent = new Intent(GetOperativesActivity.this, LoginActivity.class);
intent.putExtra("name", name);
intent.putExtra("deviceID", deviceID);
intent.putExtra("emailID", emailID);
intent.putExtra("firstName", firstName);
startActivity(intent);
}
});
LoginActivity.java:-
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_login);
btnLogout = (Button) findViewById(R.id.btnLogout);
btnCamera = (Button) findViewById(R.id.btnCamera);
btnGallery = (Button) findViewById(R.id.btnGallery);
txtDeviceID = (TextView) findViewById(R.id.txtDeviceID);
txtEmailID = (TextView) findViewById(R.id.txtEmailID);
txtEvent = (TextView) findViewById(R.id.txtEvent);
txtOperative = (TextView) findViewById(R.id.txtOperative);
txtEventOperator = (TextView) findViewById(R.id.txtEventOperator);
Intent intent = getIntent();
deviceID = intent.getStringExtra("deviceID");
emailID = intent.getStringExtra("emailID");
event = intent.getStringExtra("name");
operative = intent.getStringExtra("firstName");
txtDeviceID.setText(deviceID);
txtEmailID.setText(emailID);
txtEvent.setText(event);
txtOperative.setText(operative);
txtEventOperator.setText(event + " " + operative);
strEvent = txtEvent.getText().toString();
strOperative = txtOperative.getText().toString();
// Dialog
final AlertDialog.Builder adb = new AlertDialog.Builder(this);
AlertDialog ad = adb.create();
// new Class DB
final myDBClass myDb = new myDBClass(this);
// Save Data
long saveStatus = myDb.InsertData(
txtDeviceID.getText().toString(),
txtEmailID.getText().toString(),
txtEvent.getText().toString(),
txtOperative.getText().toString(),
txtEventOperator.getText().toString()
);
if(saveStatus <= 0)
{
ad.setMessage("Error!! ");
ad.show();
return;
}
// Show Data
String arrData[] = myDb.SelectData();
if(arrData != null)
{
txtDeviceID.setText(arrData[1]);
txtEmailID.setText(arrData[2]);
txtEvent.setText(arrData[3]);
txtOperative.setText(arrData[4]);
txtEventOperator.setText(arrData[5]);
}
if(txtEvent.getText().toString().equals("") && txtOperative.getText().toString().equals(""))
{
Intent intentCall = new Intent(LoginActivity.this, LicenseListActivity.class);
startActivity(intentCall);
}
}
If you have any question in your mind, please let me know ...
public class LoginActivity extends Activity{
static int counter = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_login);
btnLogout = (Button) findViewById(R.id.btnLogout);
btnCamera = (Button) findViewById(R.id.btnCamera);
btnGallery = (Button) findViewById(R.id.btnGallery);
txtDeviceID = (TextView) findViewById(R.id.txtDeviceID);
txtEmailID = (TextView) findViewById(R.id.txtEmailID);
txtEvent = (TextView) findViewById(R.id.txtEvent);
txtOperative = (TextView) findViewById(R.id.txtOperative);
txtEventOperator = (TextView) findViewById(R.id.txtEventOperator);
Intent intent = getIntent();
deviceID = intent.getStringExtra("deviceID");
emailID = intent.getStringExtra("emailID");
event = intent.getStringExtra("name");
operative = intent.getStringExtra("firstName");
txtDeviceID.setText(deviceID);
txtEmailID.setText(emailID);
txtEvent.setText(event);
txtOperative.setText(operative);
txtEventOperator.setText(event + " " + operative);
strEvent = txtEvent.getText().toString();
strOperative = txtOperative.getText().toString();
// Dialog
final AlertDialog.Builder adb = new AlertDialog.Builder(this);
AlertDialog ad = adb.create();
// new Class DB
final myDBClass myDb = new myDBClass(this);
// Save Data
long saveStatus = myDb.InsertData(
txtDeviceID.getText().toString(),
txtEmailID.getText().toString(),
txtEvent.getText().toString(),
txtOperative.getText().toString(),
txtEventOperator.getText().toString()
);
if(saveStatus <= 0)
{
ad.setMessage("Error!! ");
ad.show();
return;
}
// Show Data
String arrData[] = myDb.SelectData();
if(arrData != null)
{
txtDeviceID.setText(arrData[1]);
txtEmailID.setText(arrData[2]);
txtEvent.setText(arrData[3]);
txtOperative.setText(arrData[4]);
txtEventOperator.setText(arrData[5]);
}
if(counter==0&&txtEvent.getText().toString().equals("") && txtOperative.getText().toString().equals(""))
{
counter++;
Intent intentCall = new Intent(LoginActivity.this, LicenseListActivity.class);
startActivity(intentCall);
}
}//end onCreate
}//end class
I will go straight to the point. I have 1 class where I have 6 buttons. Each button saves to an SQLiteDatabase some parameters and then it launches an Activity.
The new Activity takes the parameters and queries the database to pull data accordingly. When the activity launches I clear the parameters in order to save them again if I press another or the same button.
If 1 table(which is linked to the button) is empty it returns the message I want. The problem is that if 1 is empty then all the tables return the message even if they have data!!
My 1st class
public class HRecords extends Activity {
SQLiteDatabase myDB=null;
Button tes,con,al,me,pr,va;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.records);
tes=(Button) findViewById(R.id.testbut);
con=(Button) findViewById(R.id.condbut);
al=(Button) findViewById(R.id.albut);
me=(Button) findViewById(R.id.medbut);
pr=(Button) findViewById(R.id.procbut);
va=(Button) findViewById(R.id.vacbut);
Database openHelper = new Database(this);//create new Database to take advantage of the SQLiteOpenHelper class
myDB = openHelper.getWritableDatabase(); // or getWritableDatabase();
myDB=SQLiteDatabase.openDatabase("data/data/com.example.login2/databases/aeglea", null, SQLiteDatabase.OPEN_READWRITE);//set myDB to aeglea
doclicks();
}
private void doclicks(){
tes.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
ContentValues values = new ContentValues();
values.put("ton", "Tests");
values.put("tazle","user_test");
myDB.insert("history_go",null, values);
//create new intent
Intent record = new Intent(getApplicationContext(), Record.class);
// Close all views before launching logged
record.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(record);
// Close Login Screen
onPause();
}});
con.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
ContentValues values = new ContentValues();
values.put("ton", "Medical Conditions");
values.put("tazle","user_cond");
myDB.insert("history_go",null, values);
//create new intent
Intent record = new Intent(getApplicationContext(), Record.class);
// Close all views before launching logged
record.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(record);
// Close Login Screen
onPause();
}});
al.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
ContentValues values = new ContentValues();
values.put("ton", "Allergies");
values.put("tazle","user_all");
myDB.insert("history_go",null, values);
//create new intent
Intent record = new Intent(getApplicationContext(), Record.class);
// Close all views before launching logged
record.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(record);
// Close Login Screen
onPause();
}});
me.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
ContentValues values = new ContentValues();
values.put("ton", "Medication");
values.put("tazle","user_med");
myDB.insert("history_go",null, values);
//create new intent
Intent record = new Intent(getApplicationContext(), Record.class);
// Close all views before launching logged
record.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(record);
// Close Login Screen
onPause();
}});
pr.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
ContentValues values = new ContentValues();
values.put("ton", "Medical Procedures");
values.put("tazle","user_proc");
myDB.insert("history_go",null, values);
//create new intent
Intent record = new Intent(getApplicationContext(), Record.class);
// Close all views before launching logged
record.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(record);
// Close Login Screen
onPause();
}});
va.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
ContentValues values = new ContentValues();
values.put("ton", "Vaccinations");
values.put("tazle","user_vacc");
myDB.insert("history_go",null, values);
//create new intent
Intent record = new Intent(getApplicationContext(), Record.class);
// Close all views before launching logged
record.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(record);
// Close Login Screen
onPause();
}});
}
}
The second class which as you can see it pulls data from the SQLite database(you can also see the message for empty results "Nothing Added here. Go to the site to add more.")
public class Record extends Activity{
SQLiteDatabase myDB=null;
TextView title=null;
Cursor cur,cur2=null;
ListView list=null;
private ArrayAdapter<String> listAdapter ;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.record);
title = (TextView) findViewById(R.id.recordTitle);
list = (ListView) findViewById(R.id.listView1);
Database openHelper = new Database(this);
myDB = openHelper.getReadableDatabase();
myDB=SQLiteDatabase.openDatabase("data/data/com.example.login2/databases/aeglea", null, SQLiteDatabase.OPEN_READONLY);
Database db = new Database(getApplicationContext());
cur = fetchOption("SELECT * FROM history_go");
title.setText(cur.getString(cur.getColumnIndex("ton")));
ArrayList<String> itemlist = new ArrayList<String>();
String[] names=null;
//do query
cur2=fetchOption("SELECT * FROM "+cur.getString(cur.getColumnIndex("tazle")));
//check for results
if (cur2.getCount()==0) {
names = new String[] { "Nothing Added here. Go to the site to add more."};
}else{
names = new String[] {cur2.getString(cur2.getColumnIndex("name"))};
}
//add the array as list to the ArrayList
itemlist.addAll( Arrays.asList(names) );
listAdapter = new ArrayAdapter<String>(this, R.layout.item, itemlist);
//if results add the rest
if(cur2.getCount()!=0){
for(int i=0;i<(cur2.getCount()-1);i++){
cur2.moveToNext();
listAdapter.add(cur2.getString(cur2.getColumnIndex("name")));
}
}
// Set the ArrayAdapter as the ListView's adapter.
list.setAdapter(listAdapter);
//remove the navigation history
db.resetHistoryNavigation();
cur.close();
cur2.close();
}
public Cursor fetchOption(String query) throws SQLException {
Cursor mCursor = myDB.rawQuery(query, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
}
EDIT
Also, I forgot to mention that if I set the verification conditions as cur2 == null the application crushes because the cursor goes out of bounds(the for loop fires)
I found what was wrong. The empty set was triggering the catch exception and nothing else was received afterwards. So every table was null.
I had to implement multiple try/catch
private void doclicks(){
hr.setOnClickListener(new View.OnClickListener() {
private Database db = new Database(getApplicationContext());
JSONArray allergy,condition,medication,procedure,test,vaccine;
public void onClick(View v) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("uid", cursor.getString(cursor.getColumnIndex("uid"))));
JSONObject response = null;
try {
CustomHttpTask asdf = new CustomHttpTask();
response = asdf.execute("http://192.168.1.4/aeglea/android/history.php", postParameters).get();
if(response.getString("success").equals("1")){
//get JSON Arrays
try{test = response.getJSONArray("test");}catch(Exception e){}
try{allergy = response.getJSONArray("allergy");}catch(Exception e){}
try{condition = response.getJSONArray("condition");}catch(Exception e){}
try{medication = response.getJSONArray("medication");}catch(Exception e){}
try{procedure = response.getJSONArray("procedure");}catch(Exception e){}
try{vaccine = response.getJSONArray("vaccine");}catch(Exception e){}
}
}catch (Exception e) {
Log.e("HHHERPT","YO MAMAA "+e);
}
//temp JSONOnject
JSONObject buffer=null;
//reset older values
db.resetHistory();
//Store values
try{
for(int i=0;i<allergy.length();i++){
buffer=allergy.getJSONObject(i);
db.addRecords("allergy",
Integer.parseInt(buffer.getString("id")),
Integer.parseInt(buffer.getString("uid")),
buffer.getString("name"),
1,
"",
(float) 0.1,
1,
1);
}
}catch(Exception e){
}
try{
for(int i=0;i<condition.length();i++){
buffer=condition.getJSONObject(i);
db.addRecords("condition",
Integer.parseInt(buffer.getString("id")),
Integer.parseInt(buffer.getString("uid")),
buffer.getString("name"),
Integer.parseInt(buffer.getString("year")) ,
"",(float) 0.1,
Integer.parseInt(buffer.getString("current")),
1);
}
}catch(Exception e){
}
try{
for(int i=0;i<medication.length();i++){
buffer=medication.getJSONObject(i);
db.addRecords("medication",
Integer.parseInt(buffer.getString("id")),
Integer.parseInt(buffer.getString("uid")),
buffer.getString("name"),
1,
"",
(float) 0.1,
Integer.parseInt(buffer.getString("current")),
1);
}
}catch(Exception e){
}
try{
for(int i=0;i<procedure.length();i++){
buffer=procedure.getJSONObject(i);
db.addRecords("procedure",
Integer.parseInt(buffer.getString("id")),
Integer.parseInt(buffer.getString("uid")),
buffer.getString("name"),
Integer.parseInt(buffer.getString("year")),
buffer.getString("comments"),
(float) 0.1,
0,
1);
}
}catch(Exception e){
}
try{
for(int i=0;i<vaccine.length();i++){
buffer=vaccine.getJSONObject(i);
db.addRecords("vaccine",
Integer.parseInt(buffer.getString("id")),
Integer.parseInt(buffer.getString("uid")),
buffer.getString("name"),
Integer.parseInt(buffer.getString("year")),
"",
(float) 0.1,
0,
1);
}
}catch(Exception e){
}
try{
for(int i=0;i<test.length();i++){
buffer=test.getJSONObject(i);
db.addRecords("test",
Integer.parseInt(buffer.getString("id")),
Integer.parseInt(buffer.getString("uid")),
buffer.getString("name"),
Integer.parseInt(buffer.getString("year")),
buffer.getString("comments"),
(float) Float.parseFloat(buffer.getString("value")),
1,
1);
}
}catch(Exception e){
}
//create new intent
Intent records = new Intent(getApplicationContext(), HRecords.class);
// Close all views before launching logged
records.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(records);
// Close Login Screen
onPause();
}
});
}
I am working on an android app, in which the first page is a homepage. On clicking on any item on the homepage, the user can view details in that item. The details are taken from an sqlite database and can be accepted or rejected in the app by the user. On accept or reject by the user, the detail gets deleted from the list of details. But, on clicking back button from the details page, when the user reaches the homepage again, there occurs this problem that when the user clicks on the same item again, it shows all the details without saving state.
E.g. if my item1 has 10 details within it..i view all the 10 details in the details page..then accept 2..so total remain 8..but when i click back and reach the homepage and again click on item1, it shows all 10 again...and does not record the change which occured when 2 were accepted.
How can this be solved?
This is the code that we are working on:
package com.sql.nigel;
import java.util.ArrayList;
public class listActivity extends ListActivity implements
android.view.View.OnClickListener,OnItemClickListener{
private ArrayList<listActivity2> m_orders = null;
private OrderAdapter m_adapter;
private Runnable viewOrders;
private SQLiteDatabase database;
private MySQLiteHelper dbHelper=new MySQLiteHelper(this);
private String[] leave_Col = {"Requester","LeaveType","No_of_Days","FromDate","ToDate"};
private String[] Cart_Col = {"CartNo","Date","Description","TotalValue","TotalTax","BudgetValue","UniqueNo"};
private String[] Time_Col = {"Name","Date","Project","Client","Tasks","FromDate","ToDate"};
private String[] Travel_Col = {"Requester","Purpose","Location","Cost","Date","Description","FromDate","ToDate","Hotel","Taxi","AdditionalExp"};
private String[] Invoice_Col = {"InvoiceNo","VendorName","Date","InvoiceValue","Date","VendorNo","PostingDate","FiscalYear","Pln_Group"};
private String[] Purchase_Col = {"PONo","Date","Vendor","OrderValue","PurchasingOrg","ApprovedVendor","Requester","Notes","RelatedInfo","QualityScore"};
String table_name;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listactivity);
database = dbHelper.getWritableDatabase();
table_name=this.getIntent().getExtras().getString("activity");
Button backButton = (Button)findViewById(R.id.back);
backButton.setOnClickListener(this);
Button selectButton = (Button)findViewById(R.id.select);
selectButton.setOnClickListener(this);
/* ImageView rightarrow = (ImageView)findViewById(R.id.rightarrow);
rightarrow.setOnClickListener(this);*/
m_orders = new ArrayList<listActivity2>();
this.m_adapter = new OrderAdapter(this, R.layout.listactivity2, m_orders);
setListAdapter(this.m_adapter);
ListView listView=(ListView)findViewById(android.R.id.list);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
if(table_name.compareTo("LeaveRequest")==0){
Intent intent = new Intent(listActivity.this, leavedetails.class);
Bundle b = new Bundle(); //Create bundle
b.putInt("key",position); //Your id
intent.putExtras(b); //Put your id to your next Intent
startActivity(intent); //Call intent
}else if(table_name.compareTo("Time")==0){
Intent intent = new Intent(listActivity.this, timedetails.class);
Bundle b = new Bundle(); //Create bundle
b.putInt("key",position); //Your id
intent.putExtras(b); //Put your id to your next Intent
startActivity(intent); //Call intent
}else if(table_name.compareTo("ShoppingCart")==0){
Intent intent = new Intent(listActivity.this, cartdetails.class);
Bundle b = new Bundle(); //Create bundle
b.putInt("key",position); //Your id
intent.putExtras(b); //Put your id to your next Intent
startActivity(intent); //Call intent
}else if(table_name.compareTo("Invoice")==0){
Intent intent = new Intent(listActivity.this, invoicedetails.class);
Bundle b = new Bundle(); //Create bundle
b.putInt("key",position); //Your id
intent.putExtras(b); //Put your id to your next Intent
startActivity(intent); //Call intent
}else if(table_name.compareTo("PurchaseOrder")==0){
Intent intent = new Intent(listActivity.this, purchasedetails.class);
Bundle b = new Bundle(); //Create bundle
b.putInt("key",position); //Your id
intent.putExtras(b); //Put your id to your next Intent
startActivity(intent); //Call intent
}else if(table_name.compareTo("Travel")==0){
Intent intent = new Intent(listActivity.this, traveldetails.class);
Bundle b = new Bundle(); //Create bundle
b.putInt("key",position); //Your id
intent.putExtras(b); //Put your id to your next Intent
startActivity(intent); //Call intent
}
}
});
viewOrders = new Runnable(){
public void run() {
getOrders();
}
};
Thread thread = new Thread(null, viewOrders, "MagentoBackground");
thread.start();
}
private Runnable returnRes = new Runnable() {
public void run() {
if(m_orders != null && m_orders.size() > 0){
m_adapter.notifyDataSetChanged();
for(int i=0;i<m_orders.size();i++)
m_adapter.add(m_orders.get(i));
}
m_adapter.notifyDataSetChanged();
}
};
private void getOrders(){
try{
m_orders = new ArrayList<listActivity2>();
if(table_name.compareTo("LeaveRequest")==0){display_Leave();
}else if(table_name.compareTo("Time")==0){display_Time();
}else if(table_name.compareTo("ShoppingCart")==0){display_Cart();
}else if(table_name.compareTo("Invoice")==0){display_Invoice();
}else if(table_name.compareTo("PurchaseOrder")==0){display_Purchase();
}else if(table_name.compareTo("Travel")==0){display_Travel();
}
Log.i("ARRAY", ""+ m_orders.size());
} catch (Exception e) {
Log.e("BACKGROUND_PROC", e.getMessage());
}
runOnUiThread(returnRes);
database.close();
}
public void display_Leave(){
TextView heading=(TextView)findViewById(R.id.heading);
heading.setText("Leave Request");
Cursor c_L = database.query("LeaveRequest",leave_Col, null, null, null, null, null);
c_L.moveToFirst();
while (!c_L.isAfterLast()) {
listActivity2 o1 = new listActivity2();
o1.setOrdertext1(""+c_L.getString(0));
o1.setOrdertext2(""+c_L.getString(2)+" days");
o1.setOrdertext3(""+c_L.getString(1)+" ");
o1.setOrdertext4(""+c_L.getString(3)+" to "+c_L.getString(4));
m_orders.add(o1);
c_L.moveToNext();
} c_L.close();
}
public void display_Time(){
TextView heading=(TextView)findViewById(R.id.heading);
heading.setText("Time Booking");
Cursor c_L = database.query("Time",Time_Col, null, null, null, null, null);
c_L.moveToFirst();
while (!c_L.isAfterLast()) {
listActivity2 o1 = new listActivity2();
o1.setOrdertext1(""+c_L.getString(0));
o1.setOrdertext2(""+c_L.getString(3));
o1.setOrdertext3(""+c_L.getString(2)+" ");
o1.setOrdertext4(""+c_L.getString(1));
m_orders.add(o1);
c_L.moveToNext();
} c_L.close();
}
public void display_Cart(){
TextView heading=(TextView)findViewById(R.id.heading);
heading.setText("Shopping Cart");
Cursor c_L = database.query("ShoppingCart",Cart_Col, null, null, null, null, null);
c_L.moveToFirst();
while (!c_L.isAfterLast()) {
listActivity2 o1 = new listActivity2();
o1.setOrdertext1(""+c_L.getString(0));
o1.setOrdertext2("");
o1.setOrdertext3(""+c_L.getString(2)+" ");
o1.setOrdertext4(""+c_L.getString(1));
m_orders.add(o1);
c_L.moveToNext();
} c_L.close();
}
public void display_Invoice(){
TextView heading=(TextView)findViewById(R.id.heading);
heading.setText("Invoice Approval");
Cursor c_L = database.query("Invoice",Invoice_Col, null, null, null, null, null);
c_L.moveToFirst();
while (!c_L.isAfterLast()) {
listActivity2 o1 = new listActivity2();
o1.setOrdertext1(""+c_L.getString(1));
o1.setOrdertext2("");
o1.setOrdertext3(""+c_L.getString(0)+" ");
o1.setOrdertext4(""+c_L.getString(2));
m_orders.add(o1);
c_L.moveToNext();
} c_L.close();
}
public void display_Purchase(){
TextView heading=(TextView)findViewById(R.id.heading);
heading.setText("Purchase Order");
Cursor c_L = database.query("PurchaseOrder",Purchase_Col, null, null, null, null, null);
c_L.moveToFirst();
while (!c_L.isAfterLast()) {
listActivity2 o1 = new listActivity2();
o1.setOrdertext1(""+c_L.getString(0));
o1.setOrdertext2(""+c_L.getString(3));
o1.setOrdertext3(""+c_L.getString(2)+" ");
o1.setOrdertext4(""+c_L.getString(1));
m_orders.add(o1);
c_L.moveToNext();
} c_L.close();
}
public void display_Travel(){
TextView heading=(TextView)findViewById(R.id.heading);
heading.setText("Travel Approval");
Cursor c_L = database.query("Travel",Travel_Col, null, null, null, null, null);
c_L.moveToFirst();
while (!c_L.isAfterLast()) {
listActivity2 o1 = new listActivity2();
o1.setOrdertext1(""+c_L.getString(1));
o1.setOrdertext2(""+c_L.getString(3));
o1.setOrdertext3(""+c_L.getString(2)+" ");
o1.setOrdertext4(""+c_L.getString(4));
m_orders.add(o1);
c_L.moveToNext();
} c_L.close();
}
private class OrderAdapter extends ArrayAdapter<listActivity2> {
private ArrayList<listActivity2> items;
public OrderAdapter(Context context, int textViewResourceId, ArrayList<listActivity2> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.listactivity2, null);
}
listActivity2 o = items.get(position);
if (o != null) {
TextView t1 = (TextView) v.findViewById(R.id.textList1);
TextView t2 = (TextView) v.findViewById(R.id.textList2);
TextView t3 = (TextView) v.findViewById(R.id.textList3);
TextView t4 = (TextView) v.findViewById(R.id.textList4);
if (t1 != null) {
t1.setText(o.getOrdertext1());
}
if(t2 != null){
t2.setText(o.getOrdertext2());
}
if(t3 != null){
t3.setText(o.getOrdertext3());
}
if(t4 != null){
t4.setText(o.getOrdertext4());
}
}
return v;
}
}
public void onClick(View v) {
switch(v.getId())
{
case R.id.back:
Intent backIntent = new Intent(listActivity.this, SqlTwoActivity.class);
startActivity(backIntent);
break;
case R.id.select:
Intent selectIntent = new Intent(listActivity.this, checkappear.class);
selectIntent.putExtra("checkappear", table_name);
startActivity(selectIntent);
break;
/*
case R.id.rightarrow:
Intent rightarrow = new Intent(listActivity.this, listActivity.class);
startActivity(rightarrow);
break;*/
}
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
}
Hard to find database calls in your code. Some general guidelines:
First you need to encapsulate all calls to the Database in separate threads.
Always close your cursors and DB connection after you're finished.
Best would be to use AsyncTask. Check out some tutorials for using SQLite with AsyncTask - it will handle the separate Thread automatically for you.
Second - read about the Activity Stack, so that what #Peter tells you makes sense.