How can I determine what causes app to stop running - android

My app compiles without issue, other than a warning about cursor deprecation, and is deployed and runs correctly but stops after a few minutes and asks 'open app again?'. It reopens correctly.
The crash report is below but I have no idea how to interpret it.
The app is a simple database that shows steel section properties.
Any suggestions on where to start looking gratefully received.
The code of all 3 activities is here
http://silverfernsolutions.com/Code_for_stackoverflow_55308480.txt
Min version code is below. I can only test this on the Studio AVD by getting to the DisplaySectionProperties screen and then turning the emulator off and on. The display reverts to ShowSelectedSource screen when turned back on and sometimes triggers the error message.
UPDATE-RESOLVED The problem goes away when the lines
c.close();
mDbHelper.close();
in DisplaySectionProperties onCreate() are removed. This implies it is a problem with the way the DB is being used and that is a different question.
a java.lang.RuntimeException:
at android.app.ActivityThread.performResumeActivity (ActivityThread.java:3790)
at android.app.ActivityThread.handleResumeActivity (ActivityThread.java:3830)
at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1746)
at android.os.Handler.dispatchMessage (Handler.java:105)
at android.os.Looper.loop (Looper.java:164)
at android.app.ActivityThread.main (ActivityThread.java:6944)
at java.lang.reflect.Method.invoke (Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run (Zygote.java:327)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1374)
Caused by: java.lang.IllegalStateException:
at android.app.Activity.performRestart (Activity.java:7322)
at android.app.Activity.performResume (Activity.java:7353)
at android.app.ActivityThread.performResumeActivity (ActivityThread.java:3765)
CODE
public class MainActivity extends AppCompatActivity{
String DB_NAME = "SteelSectionProperties";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.drawable.icon);
setSupportActionBar(toolbar);
// Display icon in the toolbar
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayUseLogoEnabled(true);
deleteDatabase(DB_NAME); //7Aug2011. Reload each time to pick up any upgrades
DataBaseHelperReign myDbHelper;// = new DataBaseHelperReign(this);
myDbHelper = new DataBaseHelperReign(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
//Toast.makeText(MainActivity.this, "Unable to create DB", Toast.LENGTH_LONG).show();
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
} catch (SQLException sqle) {
//Toast.makeText(MainActivity.this, "Unable to open DB", Toast.LENGTH_LONG).show();
throw sqle;
}
myDbHelper.close();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String units = prefs.getString("displayunitskey", "1");
if (units == "1") {
//first use. Set mm as initial default setting
SharedPreferences.Editor editor = prefs.edit();
editor.putString("displayunitskey", "mm");
editor.commit();
}
}//end oncreate
public void onClick(View v) {
// Perform action on click
int Idx = 0;
int id = v.getId();
switch (id) {
case R.id.btn0: Idx = 0; break;
case R.id.btn1: Idx = 1; break;
case R.id.btn2: Idx = 2; break;
case R.id.btn3: Idx = 3; break;
case R.id.btn4: Idx = 4; break;
case R.id.btn5: Idx = 5; break;
case R.id.btn6: Idx = 6; break;
case R.id.btn7: Idx = 7; break;
} //end switch
runIntents(Idx);
}//end onClick
/**/
private void runIntents(int idx) {
if (idx == 0) {
//Intent i = new Intent(this, UserSectionInput.class);
//startActivity(i);
} else {
Intent i = new Intent(this, ShowSelectedSource.class);
i.putExtra("ButtonID", idx);
startActivity(i);
} //endif
}//end runintents
}
public class ShowSelectedSource extends ListActivity{
long mSelSectionID;
String mSource, mSourceFile;
String mTable;
private SectionsDbAdapter mDbHelper;
private SectionsUserDbAdapter mDbUserHelper;
private int BtnId;
TextView tv_section, lblListSection;
ImageView imgListSection;
ImageView imgIcon;
Button btn6; //Tee shape
String mSorting ="DESC"; //ASC or DESC (default)
String mShape="A"; //default
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_selected_source);
Bundle bundle = getIntent().getExtras();
BtnId = bundle.getInt("ButtonID");
lblListSection= findViewById(R.id.lblListSection);
imgListSection= findViewById(R.id.imgListSection);
btn6 = findViewById(R.id.btn6);
mDbHelper = new SectionsDbAdapter(this);
mDbUserHelper = new SectionsUserDbAdapter(this);
//Button clicked on opening screen
switch (BtnId){
case 0://custom, already gone in Main to section input screen
case 1: mSource="CU"; mSourceFile="Saved user sections"; break; //user saved sections
case 2: mSource="US"; mSourceFile="American "; break;
case 3: mSource="AU"; mSourceFile="Australian "; break;
case 4: mSource="UK"; mSourceFile="British "; break;
case 5: mSource="EU"; mSourceFile="European "; break;
case 6: mSource="JA"; mSourceFile="Japan "; break;
case 7: mSource="TU"; mSourceFile="Tubes "; break;
}//end switch
if ( BtnId == 1){
mTable="SectionUser";
mDbUserHelper.open();
}else{
mTable="SectionProps";
mDbHelper.open();
btn6.setVisibility(View.GONE); //turn off Tee button
}
initialDisplay();
} // end onCreate ///////////////////////////////////////////////
private void initialDisplay(){
//open display
lblListSection.setText(mSourceFile);
Cursor c=null;
try{
if ( BtnId == 1){
c = mDbUserHelper.fetchRecordsbySource(mTable, mSource);
}else{
c = mDbHelper.fetchRecordsbySourceReverse(mTable, mSource,mSorting);
}
startManagingCursor(c);
} catch (SQLException e){
e.printStackTrace();
}
String[] from = new String[] {SectionsDbAdapter.KEY_DESC }; //The column(s) that the data are from
int[] to = new int[] { R.id.tv_full_width }; // int array containing references to the views that we'll bind the data into (the R.id.text1 TextView).
SimpleCursorAdapter records =
new SimpleCursorAdapter(this, R.layout.section_row_full_width, c, from, to); //the .xml file containing the R.id.xxxx
setListAdapter(records);
//c.close(); don't close, it stuffs up the buttons for some reason
}
private void loadListView(){
setImage();
Cursor c=null;
try{
if (mShape.equals("A")){
if ( BtnId == 1){
c = mDbUserHelper.fetchRecordsbySourceReverse(mTable, mSource,mSorting);
}else{
c = mDbHelper.fetchRecordsbySourceReverse(mTable, mSource, mSorting);
}
}else{
if ( BtnId == 1){
c = mDbUserHelper.fetchRecordsbySourceShapeReverse(mTable, mSource, mShape, mSorting);
}else{
c = mDbHelper.fetchRecordsbySourceShapeReverse(mTable, mSource, mShape, mSorting);
}
}
startManagingCursor(c);
String[] from = new String[] {SectionsDbAdapter.KEY_DESC }; //The column(s) that the data are from
int[] to = new int[] { R.id.tv_full_width }; // int array containing references to the views that we'll bind the data into (the R.id.text1 TextView).
SimpleCursorAdapter records =
new SimpleCursorAdapter(this, R.layout.section_row_full_width, c, from, to); //the .xml file containing the R.id.xxxx
setListAdapter(records);
//c.close(); don't close, it stuffs up the buttons for some reason
} catch (SQLException e){
e.printStackTrace();
}
}//end loadview
//get button clicks for filtering
public void onButtonClick(View v) {
switch ( v.getId()) {
case R.id.btn0: mShape="A" ;break; //all
case R.id.btn1: mShape="I";break;
case R.id.btn2: mShape="["; break;
case R.id.btn3: mShape="[]"; break;
case R.id.btn4: mShape="O";break;
case R.id.btn5: mShape="L";break;
case R.id.btn6: mShape="T";break;
case R.id.btnsort:
if (mSorting.equals("DESC")){
mSorting="ASC";
} else {
mSorting="DESC";
}
break;
} //end switch
loadListView();
}//end onClick buttons
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id); // Get the item that was clicked
v.setBackgroundColor(Color.rgb(127, 255, 0));
// next screen to display properties
Intent i = new Intent(this, DisplaySectionProperties.class);
i.putExtra("ButtonID",BtnId);
i.putExtra("Table",mTable);
i.putExtra("TablerowID", id);
Log.e("in select, Tablerow", " id = " +id);
startActivity(i);
}// end onclick listview
} //end class
public class DisplaySectionProperties extends AppCompatActivity {
private String mTable;
private long mTablerowID;
private int mBtnId;
private String mShape;
private String mDescription;
private double mDepth, mtw,mb1, mt1, mb2, mt2;
private String mDisplayUnits; // the units the user wants displayed
private String mSectionUnits; //the units that mS is currently using
private TextView txtDescription;
private ImageView imgShape;
//The section object
private cSectionProperties mS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_section_properties);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.drawable.icon);
setSupportActionBar(toolbar);
mS= new cSectionProperties();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences (this);
mDisplayUnits=prefs.getString("displayunitskey","1");
txtDescription= findViewById(R.id.lblDisplaySection);
imgShape= findViewById(R.id.imgDisplaySection);
Bundle bundle = getIntent().getExtras();
mBtnId = bundle != null ? bundle.getInt("ButtonID") : 0;
mTable = bundle != null ? bundle.getString("Table") : null;
mTablerowID= bundle.getLong("TablerowID");
Toast.makeText(this, "Disp Sect TablerowID := " + mTablerowID, Toast.LENGTH_LONG) .show();
if (mTablerowID == 0){
//user input section
mDescription=bundle.getString("Description");
mDepth=bundle.getDouble("Depth");
mtw=bundle.getDouble("tw");
mb1=bundle.getDouble("B1");
mt1=bundle.getDouble("T1");
mb2=bundle.getDouble("B2");
mt2=bundle.getDouble("T2");
mShape=bundle.getString("Shape");
mSectionUnits=bundle.getString("Units");
//createUserSection();
}else{
Cursor c;
try{
if(mTable.equals("SectionUser") ){
SectionsUserDbAdapter mDbHelper = new SectionsUserDbAdapter(this);
mDbHelper.open();
c = mDbHelper.fetchRecordbyID(mTable, mTablerowID+""); //convert int to string (v= v + "")= int V is now string
startManagingCursor(c);
mDescription= c.getString(c.getColumnIndex("Description"));
mDepth= c.getDouble(c.getColumnIndex("Depth"));
mtw = c.getDouble(c.getColumnIndex("tweb_wall"));
mb1= c.getDouble(c.getColumnIndex("Bf1"));
mt1= c.getDouble(c.getColumnIndex("Tf1"));
mb2= c.getDouble(c.getColumnIndex("Bf2"));
mt2= c.getDouble(c.getColumnIndex("Tf2"));
mShape= c.getString(c.getColumnIndex("Shape"));
mSectionUnits= c.getString(c.getColumnIndex("Units"));
c.close();
mDbHelper.close();
//createUserSection();
}else{
// section from the standard DB, mSectionUnits will be mm
SectionsDbAdapter mDbHelper = new SectionsDbAdapter(this);
mDbHelper.open();
c = mDbHelper.fetchRecordbyID(mTable, mTablerowID+""); //convert int to string (v= v + "")= int V is now string
startManagingCursor(c);
mDbHelper.close();
// createSection(c);
c.close();
}
} catch (SQLException e){
e.printStackTrace();
}
}//endif
// displayProperties();
} //end oncreate

Related

How to Get search value set only in arrylist

When a Search one value ,get the same value set all show ,,how to do this..
Example.. search value is one,Then click search button showing all values,, one,two,three.
UI Design
cancel = (Button) findViewById(R.id.btncancel);
search = (Button) findViewById(R.id.btnsearch);
textView = (TextView) findViewById(R.id.adapterPhone);
final String[] startplacesearchArrayList = { "one ","two","three" };
final String[] startplacesearchArrayList1 = { "Cat ","Dog","Cow" };
final String[] startplacesearchArrayList2 = { "Carrot ","Pottato","cake" };
final ArrayList<String>f=new ArrayList<String>();
f.addAll( Arrays.asList(startplacesearchArrayList) );
f.addAll( Arrays.asList(startplacesearchArrayList1) );
f.addAll( Arrays.asList(startplacesearchArrayList2) );
final AutoCompleteDogsAdapter endadapter = new AutoCompleteDogsAdapter(this, android.R.layout.simple_list_item_1, android.R.id.text1, f);
start.setAdapter(endadapter);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String startval = start.getText().toString();
if (TextUtils.isEmpty(startval)) {
Toasty.warning(getApplicationContext(), "Enter The Places").show();
} else {
if (f.contains(startval)) {
for(int i=0;i<f.size();i++)
Toast.makeText(getApplicationContext(),"values is :- "+f.get(i).toString(),Toast.LENGTH_LONG).show();
} else {
Toasty.warning(getApplicationContext(), "Account not founds").show();
}
}
}
});
You should not relay on ArrayList.contains("") it some time does not return true as it check for exact string match, which might not be the case when use types it manually.
Apply this code,
cancel = (Button) findViewById(R.id.btncancel);
search = (Button) findViewById(R.id.btnsearch);
textView = (TextView) findViewById(R.id.adapterPhone);
final String[] startplacesearchArrayList = { "one ","two","three" };
final String[] startplacesearchArrayList1 = { "Cat ","Dog","Cow" };
final String[] startplacesearchArrayList2 = { "Carrot ","Pottato","cake" };
final ArrayList<String>f=new ArrayList<String>();
f.addAll( Arrays.asList(startplacesearchArrayList) );
f.addAll( Arrays.asList(startplacesearchArrayList1) );
f.addAll( Arrays.asList(startplacesearchArrayList2) );
final AutoCompleteDogsAdapter endadapter = new AutoCompleteDogsAdapter(this, android.R.layout.simple_list_item_1, android.R.id.text1, f);
start.setAdapter(endadapter);
search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String startval = search.getText().toString();
if (TextUtils.isEmpty(startval)) {
Toasty.warning(getApplicationContext(), "Enter The Places").show();
} else {
boolean isExist = false;
for (int i = 0; i < f.size(); i++) {
if (f.get(i).toLowerCase().equals(startval.toLowerCase())) {
isExist = true;
String toastMessage = "";
switch (i) {
case 0:
case 1:
case 2:
toastMessage = getToastMessage(startplacesearchArrayList);
break;
case 3:
case 4:
case 5:
toastMessage = getToastMessage(startplacesearchArrayList1);
break;
case 6:
case 7:
case 8:
toastMessage = getToastMessage(startplacesearchArrayList2);
break;
}
Toast.makeText(getApplicationContext(), "values is :- " + toastMessage, Toast.LENGTH_LONG).show();
break;
}
}
if (isExist)
Toasty.warning(getApplicationContext(), "Account not founds").show();
}
}
});
getToastMessage() goes like this,
private String getToastMessage(String[] arrayList) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < arrayList.length; i++) {
stringBuilder.append(arrayList[i]);
if (i != arrayList.length - 1)
stringBuilder.append(",");
}
return stringBuilder.toString();
}

getSelectedItemPosition() of a spinner always returns 0

I'm trying to make the alert box show the selected item on the spinner and I'll need the position later on the code. I tested and the spiAli.getSelectedItemPosition() only returns 0 even before the switch. Here is my string:
private static final String[] listaAlimentos =
{"Arroz","Feijão","Bife"};
ArrayAdapter<String> alistaAlimentos;
And the function that's not working:
butFinalizar.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
String escolhaAlimento = null;
String escolhaExercicio = null;
if (cbAlimento.isChecked()) {
int selected = spiAli.getSelectedItemPosition();
switch (selected) {
case (0):
escolhaAlimento = "Arroz";
break;
case (1):
escolhaAlimento = "Feijão";
break;
case (2):
escolhaAlimento = "Bife";
break;
}
AlertDialog.Builder dialogo = new
AlertDialog.Builder(MainActivity.this);
dialogo.setTitle("Aviso");
dialogo.setMessage("Escolha:" + escolhaAlimento);
dialogo.setNeutralButton("OK", null);
dialogo.show();
}
}
});

Remove: complete action using

I made two applications that use the bluetooth in the same way. When I click on the "Connect" button I get the message "complete action using..." with the choice of my two applications. How do I delete it and launch only the activity of the application that I am using?
Thanks.
public class MainActivity extends Activity implements View.OnClickListener{
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
if (Bluetooth.connectedThread != null) {
Bluetooth.connectedThread.write(" ");}//Stop streaming
super.onBackPressed();
}
//toggle Button
static boolean Lock;//whether lock the x-axis to 0-5
static boolean AutoScrollX;//auto scroll to the last x value
static boolean Stream;//Start or stop streaming
boolean dark = true;
//Button init
Button bXminus;
Button bXplus;
Button bYminus;
Button bYplus;
ToggleButton tbScroll;
ToggleButton tbStream;
RadioButton ch1,ch2,ch3,ch4;
//GraphView init
static LinearLayout GraphView, GraphView1;
//graph value
private static double graph2LastXValue = 0;
private static int Xview=10;
Button bConnect, bDisconnect;
Button cambia;
Button bBackground;
int switches = 0;
int range = 1;
int counter = 0;
byte prova = (byte) 187; //188 e 168
Handler mHandler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
switch(msg.what){
case Bluetooth.SUCCESS_CONNECT:
Bluetooth.connectedThread = new Bluetooth.ConnectedThread((BluetoothSocket)msg.obj);
Toast.makeText(getApplicationContext(), "Connected!", 0).show();
String s = "successfully connected";
Bluetooth.connectedThread.start();
Bluetooth.connectedThread.write(new byte[]{(byte) prova});
break;
case Bluetooth.MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
int valore_a_16 = ((readBuf[1] & 0xFF) << 8) | (readBuf[0] & 0xFF);
int valore_a_16_2 = ((readBuf[3] & 0xFF) << 8) | (readBuf[2] & 0xFF);
int valore_a_16_3 = ((readBuf[5] & 0xFF) << 8) | (readBuf[4] & 0xFF);
int valore_a_16_4 = ((readBuf[7] & 0xFF) << 8) | (readBuf[6] & 0xFF);
String strIncom = new String(readBuf); // create string from bytes array
String str = String.valueOf(valore_a_16);
String str2 = String.valueOf(valore_a_16_2);
String str3 = String.valueOf(valore_a_16_3);
String str4 = String.valueOf(valore_a_16_4);
Log.d("SHORT", str);
Log.d("strIncom", strIncom);
Log.d("SHORT CH 2", str2);
Log.d("SHORT CH 3", str3);
Log.d("SHORT CH 4", str4);
char c = strIncom.charAt(0);
long foo = Integer.parseInt(str);
long foo2 = Integer.parseInt(str2);
long foo3 = Integer.parseInt(str3);
long foo4 = Integer.parseInt(str4);
//String provola = Integer.toString(foo);
//Log.d("AAAAAAAAAAAAAA", provola);
// int decVal = (int) c;
long risultato = (long) (foo * 5000000)/(65535*150);
long risultato2 = (long) (foo2 * 5000000)/(65535*150);
long risultato3 = (long) (foo3 * 5000000)/(65535*150);
long risultato4 = (long) (foo4 * 5000000)/(65535*150);
String prova = Float.toString(risultato);
String prova2 = Float.toString(risultato2);
String prova3 = Float.toString(risultato3);
String prova4 = Float.toString(risultato4);
Log.d("prova", prova);
// Log.d("testing2", String.valueOf(decVal));
break;
}
}
public boolean isFloatNumber(String num){
//Log.d("checkfloatNum", num);
try{
Double.parseDouble(num);
} catch(NumberFormatException nfe) {
return false;
}
return true;
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
requestWindowFeature(Window.FEATURE_NO_TITLE);//Hide title
this.getWindow().setFlags(WindowManager.LayoutParams.
FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);//Hide Status bar
setContentView(R.layout.activity_main);
//set background color
LinearLayout background = (LinearLayout)findViewById(R.id.bg);
background.setBackgroundColor(Color.BLACK);
init();
ButtonInit();
}
void init(){
Bluetooth.gethandler(mHandler);
}
void ButtonInit(){
bConnect = (Button)findViewById(R.id.bConnect);
bConnect.setOnClickListener(this);
bDisconnect = (Button)findViewById(R.id.bDisconnect);
bDisconnect.setOnClickListener(this);
//X-axis control button
bXminus = (Button)findViewById(R.id.bXminus);
bXminus.setOnClickListener(this);
bXplus = (Button)findViewById(R.id.bXplus);
bXplus.setOnClickListener(this);
bYminus = (Button)findViewById(R.id.bYminus);
bYminus.setOnClickListener(this);
bYplus = (Button)findViewById(R.id.bYplus);
bYplus.setOnClickListener(this);
//
tbScroll = (ToggleButton)findViewById(R.id.tbScroll);
tbScroll.setOnClickListener(this);
tbStream = (ToggleButton)findViewById(R.id.tbStream);
tbStream.setOnClickListener(this);
tbStream.setEnabled(false);
bBackground = (Button)findViewById(R.id.button1);
bBackground.setOnClickListener(this);
//init toggleButton
ch1 = (RadioButton)findViewById(R.id.radioButton1);
ch1.setOnClickListener(this);
ch1.setChecked(true);
ch2 = (RadioButton)findViewById(R.id.radioButton2);
ch2.setOnClickListener(this);
ch3 = (RadioButton)findViewById(R.id.radioButton3);
ch3.setOnClickListener(this);
ch4 = (RadioButton)findViewById(R.id.radioButton4);
ch4.setOnClickListener(this);
Lock=false;
AutoScrollX=true;
Stream=true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.bConnect:
startActivity(new Intent("android.intent.action.BT1"));
break;
case R.id.bDisconnect:
Intent myIntent = new Intent(MainActivity.this, RacerGameActivity.class);
MainActivity.this.startActivity(myIntent);
break;
case R.id.bXminus:
if (Xview>1) Xview=Xview/10;
break;
case R.id.bXplus:
if (Xview<100) Xview=Xview*10;
break;
case R.id.bYminus:
if (range==1)
{
range=0;
}
else if (range==0)
{
range=0;
}
else if(range==2)
{
range=1;
}
else if(range==3)
{
range=2;
}
else if(range==4)
{
range=3;
}
break;
case R.id.bYplus:
if (range==1)
{
range=2;
}
else if (range==0)
{
range=1;
}
else if(range==2)
{
range=3;
}
else if(range==3)
{
range=4;
}
else if(range==4)
{
range=4;
}
break;
case R.id.tbScroll:
if (tbScroll.isChecked()){
AutoScrollX = true;
}else{
AutoScrollX = false;
}
break;
case R.id.radioButton1:
ch1.setChecked(true);
ch2.setChecked(false);
ch3.setChecked(false);
ch4.setChecked(false);
switches=0;
break;
case R.id.radioButton2:
ch1.setChecked(false);
ch2.setChecked(true);
ch3.setChecked(false);
ch4.setChecked(false);
switches=1;
break;
case R.id.radioButton3:
ch1.setChecked(false);
ch2.setChecked(false);
ch3.setChecked(true);
ch4.setChecked(false);
switches=2;
break;
case R.id.radioButton4:
ch1.setChecked(false);
ch2.setChecked(false);
ch3.setChecked(false);
ch4.setChecked(true);
switches=3;
break;
/* case R.id.tbStream:
if (tbStream.isChecked()){
if (Bluetooth.connectedThread != null)
Bluetooth.connectedThread.write("E");
}else{
if (Bluetooth.connectedThread != null)
Bluetooth.connectedThread.write("Q");
}
break;
// case R.id.button1:
// GraphView.setBackgroundColor(Color.WHITE);
// break;
case R.id.button1:
switches=1;
break;*/
}
}
}

save state of changed database in android application

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.

Reading items from directory to listview in android

I am making an android application that needs to display all of the items in a specific directory on the sd-card onto a listview. I have gone though several tutorials but none seemed to give me any help. I have managed to add and delete things from my sd card and listview. But i need to show the items(files) from a directory onto the listview. I am using a dynamic listview. Please help and thanks SO much in advance! This is the code that i am using so far and i need to read the items on the onCreate method.
public class NotesActivity extends ListActivity implements OnClickListener {
/** Called when the activity is first created. */
List<String> myList = new ArrayList<String>();
EditText AddItemToListViewEditText;
Button AddItemToListView, AddItemToListViewButton, CancelButton, DeleteButton,CancelButton2, DeleteAllButton;
LinearLayout AddItemToListViewLinearLayout, DeleteItemFromListViewLinearLayout, DeleteAllItemsFromListViewLinearLayout;
public int DeleteIndexNumber;
public String NameOfSaveItemToSdCard = "";
public String NameOfDeleteItemFromSdCard = "";
public int DeleteIndexNumber2;
static final String[] COUNTRIES = new String[] {
"Matte på A1 med Ole", "Engelsk på klasserommet", "Film på A1 etter friminuttet"
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notes);
setListAdapter((ListAdapter) new ArrayAdapter<String>(this, R.layout.list_item, COUNTRIES));
setListAdapter((ListAdapter) new ArrayAdapter<String>(this, R.layout.list_item, myList));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), "Note: " + ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
DeleteIndexNumber = position;
DeleteIndexNumber2 = position;
NameOfDeleteItemFromSdCard = myList.get(position);
DeleteItemFromListViewLinearLayout = (LinearLayout)findViewById(R.id.DeleteItemFromListViewLinearLayout);
DeleteItemFromListViewLinearLayout.setVisibility(View.VISIBLE);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu meny) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.listviewmenubuttons, meny);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.AddItemToListView:
AddItemToListViewButton = (Button)findViewById(R.id.AddItemToListViewButton);
CancelButton = (Button)findViewById(R.id.CancelButton);
DeleteButton = (Button)findViewById(R.id.DeleteButton);
CancelButton.setOnClickListener(this);
DeleteButton.setOnClickListener(this);
AddItemToListViewLinearLayout = (LinearLayout)findViewById(R.id.AddItemToListViewLinearLayout);
AddItemToListViewButton.setOnClickListener(this);
AddItemToListViewLinearLayout.setVisibility(View.VISIBLE);
break;
case R.id.DeleteAllNotes:
DeleteAllItemsFromListViewLinearLayout = (LinearLayout)findViewById(R.id.DeleteAllItemsFromListViewLinearLayout);
DeleteAllItemsFromListViewLinearLayout.setVisibility(View.VISIBLE);
CancelButton2 = (Button)findViewById(R.id.CancelButton2);
DeleteAllButton = (Button)findViewById(R.id.DeleteAllButton);
CancelButton2.setOnClickListener(this);
DeleteAllButton.setOnClickListener(this);
break;
}
return true;
}
public void onClick(View src) {
switch(src.getId()) {
case R.id.AddItemToListViewButton:
AddItemToListViewEditText = (EditText)findViewById(R.id.AddItemToListViewEditText);
myList.add(AddItemToListViewEditText.getText().toString());
NameOfSaveItemToSdCard = AddItemToListViewEditText.getText().toString();
((ArrayAdapter)getListView().getAdapter()).notifyDataSetChanged();
AddItemToListViewEditText.setText("");
AddItemToListViewEditText.clearFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput (InputMethodManager.SHOW_FORCED, InputMethodManager.RESULT_HIDDEN);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
AddItemToListViewLinearLayout.setVisibility(View.GONE);
//Check if directory exists
checkIfDirectoryExist();
break;
case R.id.CancelButton:
DeleteItemFromListViewLinearLayout = (LinearLayout)findViewById(R.id.DeleteItemFromListViewLinearLayout);
DeleteItemFromListViewLinearLayout.setVisibility(View.INVISIBLE);
break;
case R.id.DeleteButton:
myList.remove(DeleteIndexNumber);
((ArrayAdapter)getListView().getAdapter()).notifyDataSetChanged();
File f = new File(Environment.getExternalStorageDirectory() + "/SchoolAppNotes/" + NameOfDeleteItemFromSdCard);
if(f.exists()) {
boolean deleted = f.delete();
}
DeleteItemFromListViewLinearLayout = (LinearLayout)findViewById(R.id.DeleteItemFromListViewLinearLayout);
DeleteItemFromListViewLinearLayout.setVisibility(View.INVISIBLE);
break;
case R.id.DeleteAllButton:
myList.removeAll(myList);
((ArrayAdapter)getListView().getAdapter()).notifyDataSetChanged();
DeleteAllItemsFromListViewLinearLayout = (LinearLayout)findViewById(R.id.DeleteAllItemsFromListViewLinearLayout);
DeleteAllItemsFromListViewLinearLayout.setVisibility(View.INVISIBLE);
break;
case R.id.CancelButton2:
DeleteAllItemsFromListViewLinearLayout = (LinearLayout)findViewById(R.id.DeleteAllItemsFromListViewLinearLayout);
DeleteAllItemsFromListViewLinearLayout.setVisibility(View.INVISIBLE);
break;
}
}
private void checkIfDirectoryExist() {
// TODO Auto-generated method stub
File f = new File(Environment.getExternalStorageDirectory() + "/SchoolAppNotes");
if(f.exists()) {
try {
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory()
+ "/SchoolAppNotes/" + NameOfSaveItemToSdCard);
Toast.makeText(getApplicationContext(), "File created:-)",
Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "We failed to create the file",
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
else {
//Create directory
File folder = new File(Environment.getExternalStorageDirectory() + "/SchoolAppNotes");
boolean success = false;
if(!folder.exists())
{
success = folder.mkdir();
}
if (!success)
{
// Do something on success
//Writing file...(It doesn't work)
}
else
{
// Do something else on failure
}
checkIfDirectoryExist();
}
}
}
I assume that myList is supposed to be holding the file names from your directory? It looks like you never instantiated it.
To do that you'll need to get a list of your file names and load it in to there before you use it to make an adapter.
So add something like this before your .setAdapter() calls:
File mFile = new File(Environment.getExternalStorageDirectory() + "yourDirectory");
myList = mFile.list();
You should be good to go if that fills your array correctly.
p.s. File.list() docs
EDIT:
Whoops, didn't notice the type on myList. Use this instead
myList = Arrays.asList(mFile.list());

Categories

Resources