I am very new to android development with a small amount of Java programming knowledge. I need help! I am making an app that allows you to enter the amount of money you spend and it calculates how much more you can spend. It also keeps track of the budget that you have left inside of a text file. It is made in android studio using Java.
Here is my error message:
2019-03-03 09:42:14.245 4178-4178/? E/SPPClientService: [PackageInfoChangeReceiver] [handlePkgRemovedEvent] PackageName : com.concretegames.budgettracker, true, false
2019-03-03 09:42:27.573 16961-16961/com.concretegames.budgettracker E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.concretegames.budgettracker, PID: 16961
java.lang.NumberFormatException: s == null
at java.lang.Integer.parseInt(Integer.java:570)
at java.lang.Integer.parseInt(Integer.java:643)
at com.concretegames.budgettracker.MainActivity$1.onClick(MainActivity.java:56)
at android.view.View.performClick(View.java:6935)
at android.widget.TextView.performClick(TextView.java:12738)
at android.view.View$PerformClick.run(View.java:26211)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:7000)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:441)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
And here is my code:
package com.concretegames.budgettracker;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import static java.lang.System.out;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView response = findViewById(R.id.response);
final Button calc = findViewById(R.id.Calculate);
Context context = this;
String filepath = "total_expense.txt";
String filestoragepath = "MyFileStorage";
final File edit_file = new File(getExternalFilesDir(filestoragepath), filepath);
EditText $box = findViewById(R.id.expenses);
final String $ = $box.getText().toString();
calc.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (edit_file.exists() && !edit_file.isDirectory()) {
try {
FileReader fr = new FileReader(edit_file);
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
out.println(str + "\n");
}
br.close();
int result = Integer.parseInt(str) - Integer.parseInt($);
FileWriter fw = new FileWriter(edit_file);
PrintWriter pw = new PrintWriter(fw);
pw.print("");
pw.print(result);
pw.close();
response.setText("Budget left over: "+result);
} catch (IOException e) {
out.println("ERROR: " + e.toString());
response.setText("ERROR: " + e.toString());
}
} else {
try {
edit_file.createNewFile();
FileWriter fw = new FileWriter(edit_file);
PrintWriter pw = new PrintWriter(fw);
pw.print("1500");
pw.close();
} catch (IOException e) {
out.println("ERROR: " + e.toString());
response.setText("ERROR: " + e.toString());
}
}
}
});
}
}
P.S. I'm only 13 and don't have experience with Java. I prefer HTML, python, and javascript. Any help is appreciated!
Integer.parseInt() throws an exception if it can't successfully parse the String into an int. But the exception that is thrown is a subclass of RuntimeException, so the java compiler does not force you to catch the exception. But it's still highly suggested that you do catch it. And the crash will be avoided. In general, do something like this when parsing Strings into ints:
int result;
try {
result = Integer.parseInt(someString);
} catch (NumberFormatException e) {
result = 0;
}
Problem is in the following line:
int result = Integer.parseInt(str) - Integer.parseInt($);
NumberFormatException is an Exception that might be thrown when you try to convert a String into a number. Here one of the strings is null (I think str is null).
When string is null, Integer.parseInt(null) would not be able to get integer value from null string. If string contains proper value, this exception will not come.
Hence to avoid this exception either apply null check before fetching value of integer from string or keep it in try catch (NumberFormatException e)
Related
I am trying to build an app, which takes the patient id as a shared preference and uses that id in another activity for getting the records of that id. In Main Activity I set the Shared Preferences, and it sets the value correctly. However, in FetchSinglePatientData, I am not able to get the same Shared Preference Value.
P.S : Before to that error, I was getting nothing at all. My codes at below:
public void getSinglePatient(View v)
{
etID = findViewById(R.id.editTextID);
SharedPreferences sharedPref = getSharedPreferences("patientId", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("patientId",etID.getText().toString());
editor.apply();
String xx = sharedPref.getString("patientId","hayamk");
Log.d("XX","DEGER" + xx);
//instantiate intent class
Intent intent=new Intent(MainActivity.this, GetSinglePatient.class);
//start the activity
startActivity(intent);
}
GetSinglePatient activity, this activity uses the fetchSinglePatientData in background.fetchSinglePatientData is like below:
package project.android.mapd713.college.centennial.com.mapd713application;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class fetchSinglePatientData extends AsyncTask<Void,Void,Void> {
String data = "";
String dataParsed = "";
String singleParsed = "";
JSONObject myObject;
private Context ctx;
public fetchSinglePatientData(Context ctx) {
this.ctx = ctx;
}
#Override
protected Void doInBackground(Void... voids) {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(ctx);
//String patientId = prefs.getString("patientId", "");
String xx = sharedPref.getString("patientId","fafafa");
Log.d("XX2","DEGE2R" + xx);
Log.i("fonksiyon","ICINE GIRDI");
try {
URL url = new URL("https://mapd713prjct.herokuapp.com/patients/5bf63c770fc33ea59c9c3a97");
Log.i("URL","URL ICINE GIRDI");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while(line != null) {
line = bufferedReader.readLine();
data = data + line;
}
myObject = new JSONObject(data);
myObject.getString("doctor");
Log.d("DOKTOR BU NE","hmm" + myObject.getString("doctor"));
} catch (MalformedURLException e) {
e.printStackTrace();
System.out.print("HATA 1: " + e);
} catch (IOException e) {
e.printStackTrace();
System.out.print("HATA 2: " + e);
} catch (JSONException e) {
e.printStackTrace();
System.out.print("HATA 3: " + e);
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
System.out.println("girdi");
Log.i("onPostExecute","GIRDI");
GetSinglePatient.mTextViewResult.setText(myObject.toString());
}
}
And the logs are like below with two different input, 1) jajaja and 2) hehehe
2018-12-01 22:38:12.360 7470-7470/project.android.mapd713.college.centennial.com.mapd713application D/XX: DEGERjajaja
2018-12-01 22:38:12.816 7470-
7497/project.android.mapd713.college.centennial.com.mapd713application D/XX2: DEGE2Rfafafa
2018-12-01 22:43:05.644 7470-7470/project.android.mapd713.college.centennial.com.mapd713application D/XX: DEGERhehehe
2018-12-01 22:43:05.815 7470-7547/project.android.mapd713.college.centennial.com.mapd713application D/XX2: DEGE2Rfafafa
Thank you very much!
You're using two different ways to obtain a SharedPreferences object. First you use the Context.getSharedPreferences() method that takes a preference file name. Then you use the static method PreferenceManager.getDefaultSharedPreferences(). This will result in two different SharedPreference files being used. Just pick one way or the other and be consistent and it should work much better.
for solving this problem , use a shared preference with define name and mode. for
example:
SharedPreferences SharedPreference = context.getSharedPreferences("defined
name" , Context.MODE_PRIVATE);
for inserting data in shared preference without any delay use commit() instead of apply()
editor.commit();
and send ApplicationContext to your asynctask class
I resolved my problem with changing my code below:
SharedPreferences sharedPref = getSharedPreferences("patientId", Context.MODE_PRIVATE);
with
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
It is true that I used two different SharedPreference method and therefore, I couldn't get the Patient id. However, changing
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(ctx);
with
SharedPreferences sharedPref = getSharedPreferences("patientId", Context.MODE_PRIVATE);
does not work since getSharedPreferences() needs a context to be accessed.
In my opinion, this is a little bit tricky with Android. I suggest those posts:
post1 post2
This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 5 years ago.
I want to call a POST request, to send some geo information from my android device to my server.
My server use PHP and I want use a php script to save all incoming post requests in my database. My php script works fine when I tried it with curl, but when I want to send some information from my android device I get some network errors.
Here is my error log
12-11 12:08:02.871 10241-10241/local.example.markus.geoapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: local.example.markus.geoapp, PID: 10241
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1448)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:102)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:90)
at java.net.InetAddress.getAllByName(InetAddress.java:787)
at com.android.okhttp.Dns$1.lookup(Dns.java:39)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:175)
at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:141)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:83)
at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:174)
at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:127)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:258)
at com.android.tools.profiler.support.network.httpurl.TrackedHttpURLConnection.getOutputStream(TrackedHttpURLConnection.java:288)
at com.android.tools.profiler.support.network.httpurl.HttpURLConnection$.getOutputStream(HttpURLConnection$.java:212)
at local.example.markus.geoapp.MapsListener.sendPost(MapsListener.java:121)
at local.example.markus.geoapp.MapsListener.onLocationChanged(MapsListener.java:77)
at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:291)
at android.location.LocationManager$ListenerTransport.-wrap0(Unknown Source:0)
at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:236)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Here is my java code
package local.example.markus.geoapp;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Timestamp;
/**
* Created by markus on 04.12.17.
*/
public class MapsListener implements LocationListener {
// Member Variablen
private GoogleMap googleMap;
// Konstruktor
public MapsListener() {
}
// Getter und Setter
public GoogleMap getGoogleMap() {
return googleMap;
}
public void setGoogleMap(GoogleMap googleMap) {
this.googleMap = googleMap;
}
// Interface Methods
#Override
public void onLocationChanged(Location location) {
// Print new Latitide and Logtitude into log
Log.d("INFO", "New Location! Latitude: '" + location.getLatitude() + "', '" + location.getLongitude() + "'");
// Define new Latitude and Logtitude object
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
// Add a new Marker to the Map
this.googleMap.addMarker(new MarkerOptions().position(latLng).title("Lat:" + location.getLatitude() + ", Lng: " + location.getLongitude()));
// Build ca,era position
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude())) // Sets the center of the map to location user
.zoom(17) // Sets the zoom
.bearing(0) // Sets the orientation of the camera to north
.tilt(40) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
// Animate camera to zoom to the new position with defined settings
this.googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
Log.d("Device ID", this.getDeviceId());
this.sendPost(location);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
private String getDeviceId() {
if (Build.VERSION.SDK_INT <= 25) {
return Build.SERIAL;
} else {
return Build.getSerial();
}
}
private void sendPost(Location location) {
URL url = null;
HttpURLConnection httpURLConnection = null;
OutputStream outputStream = null;
try{
url = new URL("http://example.local");
httpURLConnection = (HttpURLConnection) url.openConnection();
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
/*httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("d", this.getDeviceId());
httpURLConnection.setRequestProperty("lat", Double.toString(location.getLatitude()));
httpURLConnection.setRequestProperty("lon", Double.toString(location.getLongitude()));
httpURLConnection.setRequestProperty("t", timestamp.toString());
httpURLConnection.setDoOutput(true);*/
outputStream = new BufferedOutputStream(httpURLConnection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(Double.toString(location.getLongitude()));
writer.flush();
writer.close();
outputStream.close();
httpURLConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
How I can send some information about POST requests to my php script on http://example.local/gps.php?
The post Sending POST data in Android does not work.
The post Sending POST data in Android does not work.
The above should work absolutely fine else ans would have been not in accepted and upvoted state.
The error what you're getting obvious since missed how the network call is made in that ans
You missed below one.
public class CallAPI extends AsyncTask {
In android or other platforms most of the platforms also network call ui thread is not allowed. In Android AsyncTask is one way making network call off the ui thread.
This exception is thrown when an application attempts to perform a networking operation on its main thread. Run your code in AsyncTask.
public class HttpPost extends AsyncTask<String, String, String> {
protected String doInBackground(String... args) {
URL url = null;
HttpURLConnection httpURLConnection = null;
OutputStream outputStream = null;
try{
url = new URL("http://example.local");
httpURLConnection = (HttpURLConnection) url.openConnection();
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
/*httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("d", this.getDeviceId());
httpURLConnection.setRequestProperty("lat", Double.toString(location.getLatitude()));
httpURLConnection.setRequestProperty("lon", Double.toString(location.getLongitude()));
httpURLConnection.setRequestProperty("t", timestamp.toString());
httpURLConnection.setDoOutput(true);*/
outputStream = new BufferedOutputStream(httpURLConnection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(Double.toString(location.getLongitude()));
writer.flush();
writer.close();
outputStream.close();
httpURLConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
protected void onPostExecute(String result) {
//What you want to do with the result
//Call a callback function for instance
//You can also delete this method if you dont expect a result
}
}
I am new to Android programming I wrote a simple Server(VB.NET) / Client(Java/Android) program. Text from Android/Java is send successfully to VB.Net but Response from VB.Net is not received in Android/Java (buffer.readLine() returns null)
Am I missing something?
Here are my Codes
VB.NET (Server)
Imports System.Net.Sockets
Imports System.Text
Public Class Form1
Dim server As New TcpListener(9999)
Dim client As New TcpClient
Dim stream As NetworkStream
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Start_Click(sender As Object, e As EventArgs) Handles Start.Click
Me.Text = "Waiting...."
Dim str As String
server.Start()
client = server.AcceptTcpClient
stream = client.GetStream()
Dim r_byt(client.ReceiveBufferSize) As Byte
stream.Read(r_byt, 0, client.ReceiveBufferSize)
Str = Encoding.ASCII.GetString(r_byt)
Label1.Text = str
End Sub
Private Sub Responce_Click(sender As Object, e As EventArgs) Handles Responce.Click
Dim s_byt() As Byte = Encoding.ASCII.GetBytes("Got it" & vbCr)
stream.Write(s_byt, 0, s_byt.Length)
stream.Flush()
stream.Close()
client.Close()
server.Stop()
End Sub
Android/Java(Client)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class Main extends Activity {
Button buttonSend, buttonReceive;
private static Socket socket = null;
PrintStream stream = null;
BufferedReader buffer = null;
String string = "a";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonSend = (Button) findViewById(R.id.buttonSend);
buttonSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
try {
socket = new Socket("192.168.0.104", 9999);
stream = new PrintStream(socket.getOutputStream());
stream.println("Hi Server...");
buffer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
string = buffer.readLine();
Log.d("ServerActivity", " - " + string);
buffer.close();
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
It looks like you have a couple of issues:
In the server side, you are trying to read something from the socket
into r_byt, and you are not writing anything to it on cliente side.
When you press the send button on server side, r_byt still null and
that's what you receive on cliente side.
On client side the call to socket read is blocking and after a few
seconds will result in a ANR error (Application not Responding) in
the cliente. You should move the socket read to a different thread
from the UI. The newer Android versions don't even let you read from
a socket in the UI thread.
Regards.
this code is supposed to create a new user with the username and password he entered and then save that new object to phone memory with the file name matching his email so that in the login method I can look for the file matching the email entered deserialize it, and all his user info would be there... But I keep getting a FileNotFooundException... I really don't understand... please someone help me! :)
Here's the code:
package com.example.eventmanager;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class CreateAccount extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_account);
}
public void createUserAccount(View v) {
EditText username = (EditText) findViewById(R.id.editText1);
EditText password = (EditText) findViewById(R.id.editText2);
EditText secondPassword = (EditText) findViewById(R.id.editText3);
if (!(password.getText().toString().equals((secondPassword.getText()
.toString())))) {
Toast.makeText(this, "Passwords Don't Match", Toast.LENGTH_LONG).show();
} else {
User newUser = new User(username.getText().toString(), password.getText().toString());
String fileName = newUser.getEmail();
try {
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(fileName));
os.writeObject(newUser);
os.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Toast.makeText(this, "FileNotFoundException", Toast.LENGTH_LONG)
.show();
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(this, "IOException", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
Intent intent = new Intent(this, LoginScreen.class);
startActivity(intent);
Toast.makeText(this, "Account Created Successfully",
Toast.LENGTH_LONG).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_create_account, menu);
return true;
}
}
Per FileOutputStream documentation: it throws FileNotFoundException in below scenario:
FileNotFoundException - if the file exists but is a directory rather than a regular file OR does not exist but cannot be created, or cannot be opened for any other reason
Please make sure, String fileName = newUser.getEmail().toString(); results in valid file name, which I suspect is the case.
FileOutputStream uses an absolute path which (I think) will default to the root of the internal storage if you only provide a filename - on a normal device, the root of the internal storage will not be accessible.
You should use openFileOutput(String name, int mode) instead. This guarantees creating a file in the internal storage in the area allocated to your own app. To read the file back, use the corresponding openFileInput(String name) method.
I am attempting to use java FileInputStream to write some strings to a text file that will be stored on the android internal storage. However my virtual device keeps throwing an exception and I am not sure what or where I should be looking as the DDMS log cat function does not give me any useful information. I am using a try/catch structure with a stack trace print as shown below. I am not very familiar with the debug function in relation to android and I am not sure where else I can look to find out what is going on. Code is below.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText textBox;
private static final int READ_BLOCK_SIZE = 100;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textBox = (EditText)findViewById(R.id.textView1);
Button saveBtn = (Button)findViewById(R.id.button1);
Button loadBtn = (Button)findViewById(R.id.button2);
saveBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String str = textBox.getText().toString();
try{
FileOutputStream fOut =
openFileOutput("textfile.txt", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
//---write the string to the file---
osw.write(str);
osw.flush();
osw.close();
//---display file saved message---
Toast.makeText(getBaseContext(), "File saved successfully!!", Toast.LENGTH_SHORT).show();
//---clears the EditText---
textBox.setText("");
}catch(IOException ioe){
ioe.printStackTrace();
}
}
});
loadBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try{
FileInputStream fIn = openFileInput("textfile.txt");
InputStreamReader isr = new InputStreamReader(fIn);
char[]inputBuffer = new char[READ_BLOCK_SIZE];
String s = "";
int charRead;
while((charRead = isr.read(inputBuffer))>0){
//---convert the char to a String---
String readString = String.copyValueOf(inputBuffer, 0, charRead);
s += readString;
inputBuffer = new char[READ_BLOCK_SIZE];
}
//---set the EditText to the text that has been read---
textBox.setText(s);
Toast.makeText(getBaseContext(), "File loaded successfully!!", Toast.LENGTH_SHORT).show();
}catch(IOException ioe){
ioe.printStackTrace();
}
}
});
}
}
did you set your permissions in your manifest for writing?
and is your device a droidx (which when you plug in the USB cable, unmounts the external storage, making it inaccessible).
Why not run the debugger and put in debug points and see how far it gets before it crashes?