Good morning guys!
Quick question, I am using file Input/Output in Java to save data into a String when the "Save" Button in my program is pressed. But whenever I hit the "Save" button, the program stops working.
I am also new to Java and Android, so I can't really tell yet if the problem is very specific to my code or a more general one which is why I am posting this question even if there are many others that are similar.
Using comment-outs "//, /*, /" I was able to locate the line in my code that causes the program to stop working, I have emphasised this line by placing "" at the beginning and at the end of it so you won't have trouble looking for it. I just want to know why this line is causing my app to stop and if possible, how it can be fixed.
Thanks guys. Your assistance will be very much appreciated.
Please take a look at my code snippet:
public class MainActivity extends ActionBarActivity {
EditText sharedData;
FileOutputStream fos;
String FILENAME = "InternalString";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
Button save = (Button) findViewById(R.id.btn_save);
save.setOnClickListener(onSave);
ListView list = (ListView) findViewById(R.id.restaurants);
adapter = new RestaurantAdapter();
list.setAdapter(adapter);
}
public View.OnClickListener onSave = new View.OnClickListener (){
#Override
public void onClick(View v) {
Info r = new Info();
EditText name = (EditText) findViewById(R.id.field_name);
EditText address = (EditText) findViewById(R.id.field_address);
TextView total= (TextView)findViewById(R.id.total);
RadioGroup types = (RadioGroup) findViewById(R.id.rgrp_types);
switch (types.getCheckedRadioButtonId()) {
case R.id.rbtn_sit_down:
r.setType("sit_down");
break;
case R.id.rbtn_take_out:
r.setType("take_out");
break;
}
r.setName(name.getText().toString());
r.setAddress(address.getText().toString());
r.setTotal(total.getText().toString());
String data = sharedData.getText().toString();*** <----- This line causes it to stop running
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(data.getBytes());
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String collected = null;
FileInputStream fis = null;
try {
fis = openFileInput(FILENAME);
byte[] dataArray = new byte[fis.available()];
while (fis.read(dataArray) != -1){
collected = new String(dataArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
fis.close();
total.setText("Balance Total: " + collected +"Php");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Log.d("FoodTripActivity", "Name: " + r.getName() + "Address: " + r.getAddress() + "Type: " + r.getType());
adapter.add(r);
}
};
}
sharedData is not initialized. You need to initialize it before calling getText.
You have only declared it EditText sharedData;
sharedData =(EditText) findViewById(R.id.idforshareddata);
String data = sharedData.getText().toString();
Related
Background:
I am using three fragments and one activity in my application. Two fragments use recyclerViews and the other uses an expandableListView.
Problem:
I am trying to properly program the onPause(), onResume(), onStop(), and onRestart() methods to save the state of my application when the home, back, or switch views buttons are pressed.
To save the state of the program and load it when it comes back I have created the save() and load() methods in my one and only activity.
//from the end of onCreate
load();
}
#Override
protected void onStart() {
super.onStart();
mRef = new Firebase("https://sure-7856d.firebaseio.com/");
}
#Override
protected void onStop(){
super.onStop();
save();
}
#Override
protected void onPause(){
super.onPause();
save();
}
#Override
protected void onResume(){
super.onResume();
load();
}
#Override
protected void onRestart(){
super.onRestart();
load();
}
In the save method I get the adapters from my 2 recyclerViews and my expandableListView`s ArrayList that keeps track of which checkboxes are checked.
After that I put them each into a temporary Arraylist then I add each of those ArrayLists to a single arraylist that will be saved to the file.
private void save(){
//saved_data = new File("saved_data");
/*try {
if(saved_data.exists()==false){
//saved_data.createNewFile();
saved_data.setWritable(true);
}
} catch (IOException e) {
e.printStackTrace();
}*/
File myFile;
try{
myFile = new File(getFilesDir().getAbsolutePath(), "dir/save_data.bin");
myFile.mkdirs();
myFile.createNewFile();
FILENAME = myFile.getName();
}catch (IOException e){
e.printStackTrace();
}
OneFragment f20 = (OneFragment) frags.get(0);
TwoFragment f21 = (TwoFragment) frags.get(1);
ThreeFragment f22 = (ThreeFragment) frags.get(2);
ArrayList saveTasks = f20.adapter.getList();
ArrayList saveReqs = f21.adapter.getList();
ArrayList saveMap = new ArrayList<String>();
if(f22.listAdapter!=null) {
if (f22.listAdapter.getExport() != null) {
saveMap = f22.listAdapter.getExport();
}
}
ArrayList results = new ArrayList();
results.add(saveTasks);
results.add(saveReqs);
results.add(saveMap);
ObjectOutputStream oos1 = null;
FileOutputStream fos1 = null;
try {
fos1 = openFileOutput(FILENAME, Context.MODE_PRIVATE);
oos1 = new ObjectOutputStream(fos1);
oos1.writeObject(results);
oos1.close();
fos1.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(oos1 != null){
try {
oos1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
In the load code I get the object from the file and update the adapters to their previous state.
private void load(){
//saved_data = new File("saved_data");
ArrayList results = new ArrayList();
FileInputStream fis = null;
ObjectInputStream ois = null;
if(FILENAME==null){
return;
}
try {
fis = new FileInputStream(FILENAME);
ois = new ObjectInputStream(fis);
}catch (FileNotFoundException e) {
e.printStackTrace();
return;
}catch (IOException e) {
e.printStackTrace();
}
try {
while (true) {
results = (ArrayList)(ois.readObject());
}
} catch (OptionalDataException e) {
if (!e.eof) try {
throw e;
} catch (OptionalDataException e1) {
e1.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ois.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
for(int i = 0; i < results.size();i++){
if(i == 0){
frags.set(0,results.get(i));
}
else if(i == 1){
frags.set(1,results.get(i));
}
else if(i == 2){
frags.set(2,results.get(i));
}
else{
}
}
}
When I press the square button at the bottom of the emulator and go back to it one of a few things happen
It crashes saying the file could not be found
W/System.err: Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
And this error points to the load method as the point of failure specifically
FileInputStream fis = null;
When I hit the triangle button nothing happens in logcat, everything is gone upon returning, and the app loses its functions of adding strings to lists on both recyclerViews and displaying both lists in the expandableListView.
Hitting the center circle button and going back to the app is fine nothing breaks.
Since Im getting a file not found error I think that the file isnt getting written
I have searched Stack for a solution and I am new to File IO and fragments, so I have no idea where to go from here.
I'm trying to build an app which displays fun facts from a text file. To do this I get a random number and then display that specific line number from the file.When I run the app and try and press the button all I get is a blank text field. Here is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fun_facts);
// Declare and assign variables
final TextView factLabel = (TextView) findViewById(R.id.factTextView);
Button showFactButton = (Button) findViewById(R.id.showFactButton);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
/*
code here runs when button click is detected by line 29
code shows new fact
*/
String fact = "";
//get a random number to select a fact
Random randomNumberGenrator = new Random();//construct random object
int randomNumber = randomNumberGenrator.nextInt(391);
FileReader fr = null;
try {
fr = new FileReader("facts.txt ");//construct filereader and assign file
} catch (FileNotFoundException e) {
e.printStackTrace();//exception raised
}
LineNumberReader getFact = new LineNumberReader(fr);//construct lineNumberReader
getFact.setLineNumber(randomNumber);//set current line number to random number
try {
fact = getFact.readLine();//read current line and assign it to fact
} catch (IOException e) {
e.printStackTrace();
}
factLabel.setText(fact);
try {
getFact.close();//close lineReader
} catch (IOException e) {
e.printStackTrace();
}
try {
fr.close();//close fileReader
} catch (IOException e) {
e.printStackTrace();
}
}
};
showFactButton.setOnClickListener(listener);
}
Do you getting any errors?
check this line, maybe its typo but worth check it and remove that space from path.
OLD:
fr = new FileReader("facts.txt ");
NEW:
fr = new FileReader("facts.txt");
Ive created an app that is just making data accessible on mobile devices. This is what should happen.
1) connect to MySQL db
2) pull data from MySQL db
3) save data to SQLite db
4) display data from SQLite db
This all works good and well when I have net access. but it seems the moment I loose my connectivity I can no longer access data from my SQLite db.... and the whole point of the app is to make data accessible anywhere, with or without internet, hence the local db. Hope someone can help me with this...
public class MainActivity extends Activity {
SQLiteDatabase HRdb;
InputStream isr = null;
String result = "";
TextView resultView;
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HRdb=openOrCreateDatabase("HRdb",MODE_PRIVATE,null);
HRdb.execSQL("CREATE TABLE IF NOT EXISTS HRinfotbl (lname VARCHAR, fname VARCHAR, email VARCHAR, contact VARCHAR);");
try {
result = new httprRequest().execute().get();
HRdb.delete("HRinfotbl", null, null);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
resultView = (TextView) findViewById(R.id.result);
getData();
}
/*
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
*/
//function to print data from SQLite array
public String SQLitePrint(String n)
{
String info = "";
Cursor c=HRdb.rawQuery("SELECT * from "+n+";", null);
int count = c.getCount();
c.moveToFirst();
for (Integer j = 0; j < count; j++)
{
info = info +
"Surname : "+c.getString(c.getColumnIndex("lname"))+"\n"+
"Name : "+c.getString(c.getColumnIndex("fname"))+"\n"+
"Email : "+c.getString(c.getColumnIndex("email"))+"\n"+
"Contact : "+c.getString(c.getColumnIndex("contact"))+"\n\n";
c.moveToNext() ;
}
HRdb.close();
return info;
}
public String Search(String n)
{
String info = "";
Cursor cu = HRdb.rawQuery("SELECT * FROM HRinfotbl WHERE (lname LIKE '%||"+n+"||%' OR fname LIKE '%||"+n+"||%';",null);
int count = cu.getCount();
cu.moveToFirst();
for (Integer j = 0; j < count; j++)
{
info = info +
"Surname : "+cu.getString(cu.getColumnIndex("lname"))+"\n"+
"Name : "+cu.getString(cu.getColumnIndex("fname"))+"\n"+
"Email : "+cu.getString(cu.getColumnIndex("email"))+"\n"+
"Contact : "+cu.getString(cu.getColumnIndex("contact"))+"\n\n";
cu.moveToNext() ;
}
HRdb.close();
return info;
}
public void getData(){
String name,surname,email,contact;
//parse json data
try {
JSONArray jArray = new JSONArray(result);
for(int i=0; i<jArray.length();i++){
JSONObject json = jArray.getJSONObject(i);
surname = json.getString("surname");
name = json.getString("name");
email = json.getString("email");
contact = json.getString("contact");
HRdb.execSQL("INSERT INTO HRinfotbl VALUES ('"+surname+"','"+name+"','"+email+"','"+contact+"');");
resultView.setText("Succesfully updated your database.");
}
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data "+e.toString());
}
}
private class httprRequest extends AsyncTask<String,Integer,String>{
#Override
public String doInBackground(String... params){
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("pvt");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
if(response.getStatusLine().getStatusCode()!=200){
Log.d("MyApp", "Server encontered an error.");
}
HttpEntity entity = response.getEntity();
isr = entity.getContent();
}catch(Exception e){
Log.e("log_entity", "Error in http connection: "+e.toString());
}
//conversion happening here..
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result = sb.toString();
}
catch(Exception e){
Log.e("log_buf", "Error converting result "+e.toString());
}
return result;
}
}
}
here is where I display most data.
public class Human_Resources extends MainActivity{
TextView dbView;
EditText searchtxt;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.human_resources);
dbView = (TextView) findViewById(R.id.showdb);
searchtxt = (EditText) findViewById(R.id.searchtxt);
dbView.setMovementMethod(new ScrollingMovementMethod());
dbView.setText(SQLitePrint("HRinfotbl"));
Button search = (Button) findViewById(R.id.searchbtn);
search.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v)
{
dbView.setText(Search(searchtxt.getText().toString()));
}
});
}
}
also I am very new to android, started last week. So just keep that in mind when giving an answer ;) thanks!
here is my error log. regarding when I try display for SQLite. db
01-15 08:47:16.856: W/ResourceType(7501): Failure getting entry for 0x01080a03 (t=7 e=2563) in package 0 (error -75)
01-15 08:47:16.876: E/log_entity(7501): Error in http connection: java.net.UnknownHostException: Unable to resolve host "www.deltabec.com": No address associated with hostname
01-15 08:47:16.876: E/log_buf(7501): Error converting result java.lang.NullPointerException: lock == null
01-15 08:47:16.876: E/log_tag(7501): Error Parsing Data org.json.JSONException: End of input at character 0 of
The reason is that you are deleting the table in main activity without checking. The following lines are the problem for you. What is happening here is you delete the table data, when ever you start your app. So don't delete the table data blindly unless you dont have internet connection.
try {
result = new httprRequest().execute().get();
HRdb.delete("HRinfotbl", null, null);// This cause the problem.
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You can check for the internet if internet is avialable then delete and get the data otherwise dont delete the data so you might check here
so you have to check here like
try {
result = new httprRequest().execute().get();
// A work around to fix the problem
if(internet avialable) {
HRdb.delete("HRinfotbl", null, null);
} else {
getData();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
So I'm making an Android soundboard app and get this exception and my app crashes when I click the last button of the soundboard app.
[THE CODE]
public class newBoard extends Activity {
int selectedSoundId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer player = new MediaPlayer();
final Resources res = getResources();
// just keep them in the same order, e.g. button01 is tied to backtoyou
final int[] buttonIds = { R.id.button1, R.id.button2, R.id.button3,
R.id.button4, R.id.button5, R.id.button6, R.id.button7,
R.id.button8, R.id.button9, R.id.button10, R.id.button11,
R.id.button12, R.id.button13, R.id.button14, R.id.button15,
R.id.button16, R.id.button16, R.id.button17, R.id.button18,
R.id.button19, R.id.button20, R.id.button21, R.id.button22,
R.id.button23, R.id.button24, R.id.button25, R.id.button26,
R.id.button27, R.id.button28, R.id.button29, R.id.button30,
R.id.button31, R.id.button32 };
final int[] soundIds = { R.raw.bengalka, R.raw.cista_psihologija,
R.raw.da_ne, R.raw.dejo_narkomane, R.raw.dizi_se,
R.raw.fejslifting, R.raw.fotomale, R.raw.gladan_sam,
R.raw.jasna_pero, R.raw.jeben_vam_mater, R.raw.kae_ivanisevic,
R.raw.kae_to_fora, R.raw.kaj_gledas, R.raw.kaj_vi_gledate,
R.raw.kineza_crnaca, R.raw.kozo_nepodojena, R.raw.marino,
R.raw.mater_zbrgljavu, R.raw.muha, R.raw.nema_papira,
R.raw.nered, R.raw.ne_spominji_majku, R.raw.nisam_se_uroko,
R.raw.odfurati_doktoru, R.raw.pljacka, R.raw.pusi_ke,
R.raw.sava_sava, R.raw.tebe_i_magazin, R.raw.tog_vani_nema,
R.raw.za_dom_spremni, R.raw.zrigati };
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
// find the index that matches the button's ID, and then reset
// the MediaPlayer instance, set the data source to the
// corresponding
// sound effect, prepare it, and start it playing.
for (int i = 0; i < buttonIds.length; i++) {
if (v.getId() == buttonIds[i]) {
selectedSoundId = soundIds[i];
AssetFileDescriptor afd = res
.openRawResourceFd(soundIds[i]);
player.reset();
try {
player.setDataSource(afd.getFileDescriptor(),
afd.getStartOffset(), afd.getLength());
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
player.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
player.start();
break;
}
}
}
};
// set the same listener for every button ID, no need
// to keep a reference to every button
for (int i = 0; i < buttonIds.length; i++) {
Button soundButton = (Button) findViewById(buttonIds[i]);
registerForContextMenu(soundButton);
soundButton.setOnClickListener(listener);
}
}
}
The exception shows on this line:
selectedSoundId = soundIds[i];
selectedSoundId = soundIds[i];
final int[] buttonIds = 33 Value - you have two R.id.button16 in your buttonIds
final int[] soundIds = 31 Value
So it is crash.
Off-by-two: There are 33 button ids and 31 sound ids. Button 16 is duplicated.
For mapping resource ids and other integers, consider a map, such as SparseIntArray.
I'm trying to read a random line from a file. My code doesn't have error, just comes up with a force close as soon as it runs in the emulator and I can't work out why!
public class filereader extends Activity {
TextView t = (TextView)findViewById(R.id.text);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
Scanner s = new Scanner(getResources().openRawResource(R.raw.lev1)); {
try {
while (s.hasNext()) {
String word = s.next();
t.setText(word);
}
}
finally {
s.close();
}
}
}
TextView t = (TextView)findViewById(R.id.text);
you can not run findViewById until the setContentView has been called:
TextView t = null; #Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
t = (TextView)findViewById(R.id.text);
}
please be sure that you declare text inside the main.xml
do this
BufferedReader myReader = null;
try
{
fIn = openFileInput("customer_number.txt");
myReader = new BufferedReader(new InputStreamReader(fIn));
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
String aDataRow = "";
//String aBuffer = "";
try
{
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
// TO display Whole Data of File
Toast.makeText(getBaseContext(),aBuffer,Toast.LENGTH_SHORT).show();
}
// To display Last Entered Number
Toast.makeText(getBaseContext(),last_number,Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public void readfromfile(){
try {
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[READ_BLOCK_SIZE];
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
// char to string conversion
String readstring=String.copyValueOf(inputBuffer,0,charRead);
String s +=readstring;
}
InputRead.close();
Toast.makeText(getBaseContext(), s,Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
It will read the text file named "mytext.txt" string by string and store it by appending it to string variable s. So the variable "s" contains final string taken from file.