android listview onclick opens textfiles in raw folder - android

I have a listView that I want to display text files in the row folder corresponding to the list item that has been clicked. My code so far:
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
String displaytxt = "";
int fileLen = 0;
try {
InputStream text = null;
switch(position) {
case 1:
text = getResources().openRawResource(R.raw.books1);
break;
case 2:
text = getResources().openRawResource(R.raw.books2);
break;
case 3:
text = getResources().openRawResource(R.raw.books3);
break;
default:
break;
}
fileLen = text.available();
byte[] fileBuffer = new byte[fileLen];
text.read(fileBuffer);
text.close();
displaytxt = new String (fileBuffer);
}
catch (IOException e) {
}
tv.setText(displaytxt);
}
But when I click the first item on the list I get an error in the emulator

Try to change:
switch(position) {
case 0:
text = getResources().openRawResource(R.raw.books1);
break;
case 1:
text = getResources().openRawResource(R.raw.books2);
break;
case 2:
text = getResources().openRawResource(R.raw.books3);
break;
default:
text = getResources().openRawResource(R.raw.books1); // paste default book
break;
}

Related

How can I determine what causes app to stop running

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

Moving some functions from mainactivity into another class

I have a addAllToGroup click function and I use the DialogWithRadioButtonM in many different places, is it possible to place DialogWithRadioButtonM() and redioGroup1() functions in a separate file(class)? Here is my code:
i tried to put it in a class but i get error for onclicklistener in it and also i dont know how to use context in a nonActivity java file. sorry, I am new in android and java thanks for help.
public void addAllToGroup(View view) {
csM = new String[6];
//dialogTitle="Add This to Group";
csM[0] = "Add to Group 1";
csM[1] = "Add to Group 2";
csM[2] = "Add to Group 3";
csM[3] = "Add to Group 4";
csM[4] = "Add to Group 5";
csM[5] = "Remove Grouping";
DialogWithRadioButtonM("Add Selected to Group");
}
public void DialogWithRadioButtonM(String str){
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle(str);
builder.setSingleChoiceItems(csM, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Log.i("TAG2", "onCreate: "+item);
switch(item)
{
case 0: backFromDialogM=0; break;
case 1: backFromDialogM=1; break;
case 2: backFromDialogM=2; break;
case 3: backFromDialogM=3; break;
case 4: backFromDialogM=4; break;
case 5: backFromDialogM=5; break;
case 6: backFromDialogM=6; break;
case 7: backFromDialogM=7; break;
}
redioGroup1(backFromDialogM);
alertDialogM.dismiss();
}
});
alertDialogM = builder.create();
alertDialogM.show();
}
public void redioGroup1(int group) {
int iCount = myRecycler.getAdapter().getItemCount();
MyDateBase mydbM = new MyDateBase(MainActivity.this);
final SQLiteDatabase databaseM = mydbM.getWritableDatabase();
String strCL = "cl" + "0";
String rawQueryM="";
for (int i = 0; i < iCount; i++) {
if (mAdapter.itemList.get(i).isChecked()) {
mAdapter.itemList.get(i).getuSentId();
rawQueryM ="UPDATE wp_words SET " + strCL + " =" + group + " WHERE wid= " + mAdapter.itemList.get(i).getuSentId();
databaseM.execSQL(rawQueryM);
Log.i("tog", "" + mAdapter.itemList.get(i).getuSentId());
}
}
Log.i("togf", "" + rawQueryM);
}
thanks
Your "DialogWithRadioButtonM" Class depends of the outer class in which it is.
You have to make "DialogWithRadioButtonM" not dependant of other variables/objects outside it, or you cannot move it in a stand alone Class file.
For example: "backFromDialogM" and "alertDialogM" are not declared INSIDE DialogWithRadioButtonM but somewhere else in the same file.

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();
}
}
});

EditText set selector position doesn't works

When I delete text inside EditText with clrFunc() I lost cursor (I see it flashing, but nothing happens if I type). I can't type back in. I have to click back onEditText and then I can type in.
/* WORKS PERFECT */
private void delFunc(){
String str = display.getText().toString();
if(str.length() > 0){
String strStart = str.substring(0, SELECTOR_POSITION-1);
String strEnd = str.substring(SELECTOR_POSITION);
display.setText(strStart + strEnd);
display.requestFocus();
display.setSelection(--SELECTOR_POSITION);
}
}
/* NOT FULLY WORKING */
private void clrFunc(){
display.setText(""); //text is set to ""
display.requestFocus(); //not working
display.setSelection(display.getText().length()); //not working
}
EDIT: Added more code, I'm building simple calculator.
private EditText display;
private Button b0, b1, b2, b3, b4, b5, b6, b7, b8, b9;
private Button bDec, bEquals, bAdd, bSub, bMultiply, bDivide, bClear, bBracket, bBackBracket, bDel, bClrH;
private Button bSin, bAsin, bCos, bAcos, bTan, bAtan, bLn, bLog, bPow, bPow2, bSqrt, bPi, bE, bToRad, bToDeg;
private TextView history;
private int SELECTOR_POSITION;
private void implementGUI(){
/* EditText */
display = (EditText) findViewById(R.id.etDisplay);
display.setOnTouchListener(this);
/* ... */
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.bZero: insert("0"); break;
case R.id.bOne: insert("1"); break;
case R.id.bTwo: insert("2"); break;
case R.id.bThree: insert("3"); break;
case R.id.bFour: insert("4"); break;
case R.id.bFive: insert("5"); break;
case R.id.bSix: insert("6"); break;
case R.id.bSeven: insert("7"); break;
case R.id.bEight: insert("8"); break;
case R.id.bNine: insert("9"); break;
case R.id.bDecPoint: insert("."); break;
case R.id.bAdd: insert("+"); break;
case R.id.bSub: insert("-"); break;
case R.id.bMultiply: insert("*"); break;
case R.id.bDivide: insert("/"); break;
case R.id.bBracket: insert("("); break;
case R.id.bBackBracket: insert(")"); break;
case R.id.bDel: delFunc(); break;
case R.id.bC: clrFunc(); break;
case R.id.bEquals: calcFunc(); break;
case R.id.bClrH: clrHistory(); break;
case R.id.bSin: insert("sin("); break;
case R.id.bAsin: insert("asin("); break;
case R.id.bCos: insert("cos("); break;
case R.id.bAcos: insert("acos("); break;
case R.id.bTan: insert("tan("); break;
case R.id.bAtan: insert("atan("); break;
case R.id.bLn: insert("ln("); break;
case R.id.bLog: insert("log("); break;
case R.id.bPow: insert("^"); break;
case R.id.bPow2: insert("^2"); break;
case R.id.bSqrt: insert("sqrt("); break;
case R.id.bPi: insert("(PI)"); break;
case R.id.bE: insert("(E)"); break;
case R.id.bToRad: insert("toRadians("); break;
case R.id.bToDeg: insert("toDegrees("); break;
}
}
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
v.onTouchEvent(event);
InputMethodManager imm = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
SELECTOR_POSITION = display.getSelectionStart();
return true;
}
private void delFunc(){
String str = display.getText().toString();
if(str.length() > 0){
String strStart = str.substring(0, SELECTOR_POSITION-1);
String strEnd = str.substring(SELECTOR_POSITION);
display.setText(strStart + strEnd);
display.requestFocus();
display.setSelection(--SELECTOR_POSITION);
}
}
/* NOT FULLY WORKING */
private void clrFunc(){
display.setText("");
display.requestFocus();
display.setSelection(display.getText().length());
}
private void clrHistory(){
history.setText("");
}
private void calcFunc(){
try{
MathEval math = new MathEval();
String input = display.getText().toString();
history.setText(String.format("%s = %s%n%s", input, math.evaluate(input), history.getText()));
}catch(Exception e){
e.printStackTrace();
history.setText(String.format("%s%n%s", "ERROR", history.getText()));
}
clrFunc();
}
private void insert(String midStr){
try{
String input = display.getText().toString();
String startStr = input.substring(0,SELECTOR_POSITION);
String endStr = input.substring(SELECTOR_POSITION);
String retStr = startStr + midStr + endStr;
SELECTOR_POSITION += midStr.length();
display.setText(retStr);
display.setSelection(SELECTOR_POSITION);
}catch(Exception e){
e.printStackTrace();
}
}
P.S.: Sorry for my bad language.
If you want to directly type into the EditText you are missing the following in your method:
display.requestFocus();
EDIT
This is the method I am using to show the keyboard with focus, the different focus call could do the trick.
protected void showKeyboard(EditText edit) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(edit, 0);
edit.requestFocusFromTouch();
}

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