Creating and Writing txt files in Android studio ( Java Code ) - java

I'm trying to create files and write arrray's values on it and I don't have errors in my code most probably there is some exception that i can not see.
Here is my code :
for (int i = 0; i < groups.size(); i++) {
try{
Log.d("a" , "broj grupa " + groups.size());
h = "C" + (i+1) + ".txt" ;
// File root = new File(Environment.getExternalStorageDirectory(), "Notes");
File root = new File(Environment.DIRECTORY_DOWNLOADS +h);
if (!root.exists()) {
root.mkdirs(); // this will create folder.
// root.createNewFile();
}
File filepath = new File(root, h );
FileWriter writer = new FileWriter(filepath);
for(int ii=0 ; ii < groups.get(i).size(); ii++)
{
// System.out.println(groups.get(i).get(ii)+"\n");
String broj = groups.get(i).get(ii).toString();
Log.d("ima li podataka ovamo ", broj);
writer.write(broj);
writer.flush();
}
writer.close();
}
catch(IOException e){
e.toString();
}
}
And Main Activity :
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
long [] array = new long[142];
int kkkod;
try {
// OPENING THE REQUIRED TEXT FILE
BufferedReader reader = new BufferedReader(new InputStreamReader(
getAssets().open("renkhex.txt")));
String myLine = reader.readLine();
int i = 0;
while (myLine != null) {
String heksakodbezpraznina = myLine.replaceAll(" ", "");
//Log.d("a da li je to : " , heksakodbezpraznina);
kkkod = Integer.parseInt(heksakodbezpraznina, 16);
// Log.d("to je" , "integer vrednost = " + kkkod);
array[i]= kkkod;
i=i+1;
myLine = reader.readLine();
}
reader.close();
}
catch (IOException e) {
Toast.makeText(getApplicationContext(),
"Error Opening the File !!!", Toast.LENGTH_LONG).show();
}
new KMeans(3,142,array) ;
}
}
Here is my LogCat :
Process: hesh.rtxt, PID: 2119
java.lang.RuntimeException: Unable to start activity ComponentInfo{hesh.rtxt/hesh.rtxt.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:109)
at hesh.rtxt.KMeans.<init>(KMeans.java:98)
at hesh.rtxt.MainActivity.onCreate(MainActivity.java:59)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
      
 When I run program it's not stoping, also It writes to much Output to process.

Related

Getting a "android.os.NetworkOnMainThreadException" even though I am running it in a separate thread

Have very little experience in Android Development, and am trying to pull HTML directly from a website. I have written code that works fine when running it just straight java, but i get an "android.os.NetworkOnMainThreadException" when I try to run it through my app. Some googling has told me that I have to put it in a separate thread, which I believe I have done, but it's not helping. Here are my two different java class files, the first being the MainActivity and the second being my thread that is supposed to deal with getting the info from the website.
Here's the MainActivity:
public class MainActivity extends AppCompatActivity {
public static TextView main = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onPostCreate(Bundle savedInstanceState){
super.onPostCreate(savedInstanceState);
main = (TextView) findViewById(R.id.main);
WebsiteDealerino jbae = new WebsiteDealerino();
jbae.start();
}
}
And here's my thread file:
public class WebsiteDealerino extends Thread {
public void run(){
try{
WebsiteDealerino jbae = new WebsiteDealerino();
String[] stuff = jbae.getQuestion();
MainActivity.main.setText(stuff[0]);
}catch(Exception e){}
}
public String[] getQuestion() {
try {
return parseHTML(getHTML("http://jbae.po8.org"));
} catch (IOException error) {
return new String[]{"Ran into an error" };
}
}
public String getHTML(String websiteURL) {
String content = null;
URLConnection connection = null;
try {
connection = new URL(websiteURL).openConnection();
Scanner scanner = new Scanner(connection.getInputStream());
scanner.useDelimiter("\\Z");
content = scanner.next();
} catch (Exception ex) {
ex.printStackTrace();
}
return content;
}
public String[] parseHTML(String rawHTML) throws IOException {
String parsed = "";
boolean relevant;
String[] lines = rawHTML.split(System.getProperty("line.separator"));
for(String line : lines) {
relevant = true;
for (char piece : line.toCharArray()) {
if (piece == '<')
relevant = false;
}
if (relevant)
parsed += "SPLIT" + line;
}
String old = parsed;
parsed = "";
String characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./,+­ *!?|() :^~=";
for (int i = 1; i < old.length(); i++) {
int j = i - 1;
if ((old.toCharArray()[i] == ' ' && !characters.contains(old.toCharArray()[j] + "")))
parsed += "";
else
parsed += old.toCharArray()[i];
}
String fixed = "";
for (char Char : parsed.toCharArray()) {
if (characters.contains(Char + ""))
fixed += Char;
}
String[] parts = fixed.split("SPLIT");
int leng = parts.length;
int lengt = leng - 2;
String[] fixeds = new String[lengt];
int i = 0;
int empties = 0;
for (String part : parts) {
if (i + 2 < parts.length)
if (part.length() <= 1)
i++;
fixeds[i] = parts[i + 2];
empties++;
}
String[] finalized;
if (empties > 0) {
int len = fixeds.length;
finalized = new String[len - empties];
i = 0;
for (String fixe : fixeds) {
if (fixe.length() > 1) {
finalized[i] = fixe;
i++;
}
}
} else
finalized = fixeds;
i = 0;
for (String finale : finalized) {
if (finale.contains("Answer")) {
String answer = "";
String sensible = "0123456789.-";
for (char Char : finale.toCharArray()) {
if (sensible.contains(Char + ""))
answer += Char;
}
finalized[i] = answer;
}
i++;
}
return finalized;
}
}
Any help would be very much appreciated. Tried a bunch of things so far and no luck. Wish I'd have kept track of what I've done better so I could tell you what hasn't worked better but it's probably something obvious anyways.
Here's what I believe to be the relevant part of the logcat:
07-20 21:56:59.919 21503-21503/com.bmassey.android.jbaeapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.bmassey.android.jbaeapp, PID: 21503
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.bmassey.android.jbaeapp/com.bmassey.android.jbaeapp.MainActivity}: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
at java.net.InetAddress.lookupHostByName(InetAddress.java:431)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.android.okhttp.internal.Network$1.resolveInetAddresses(Network.java:29)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:188)
at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:157)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:100)
at com.android.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:357)
at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:340)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:433)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:114)
at com.bmassey.android.jbaeapp.WebsiteDealerino.getHtml(WebsiteDealerino.java:53)
at com.bmassey.android.jbaeapp.MainActivity.onPostCreate(MainActivity.java:36)
at android.app.Instrumentation.callActivityOnPostCreate(Instrumentation.java:1188)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2398)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
PS: The majority of this code is my awkward parsing through the HTML, and I know that most of it will not be helpful but I thought I might as well just put it all in here.

Writing a TableRow on UI thread with data from AsyncTask Thread

I have implemented a JSON Parser on a background thread and then am trying to write the data to a series of TableRows on the UI Thread using some embedded code which includes a handler to put me back on the normal UI Thread. The code continually comes back with this stack trace
Process: webmd.mmu.ac.uk.wmfinal3, PID: 6123
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:3562)
at android.view.ViewGroup.addView(ViewGroup.java:3415)
at android.widget.TableLayout.addView(TableLayout.java:429)
at android.view.ViewGroup.addView(ViewGroup.java:3360)
at android.widget.TableLayout.addView(TableLayout.java:411)
at android.view.ViewGroup.addView(ViewGroup.java:3336)
at android.widget.TableLayout.addView(TableLayout.java:402)
at webmd.mmu.ac.uk.wmfinal3.MainActivity$ProgressTask$1$1.run(MainActivity.java:244)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
04-21 14:58:08.506 6199-6199/webmd.mmu.ac.uk.wmfinal3 D/gralloc_goldfish﹕ Emulator without GPU emulation detected.
04-21 14:58:11.316 6199-6215/webmd.mmu.ac.uk.wmfinal3 D/dalvikvm﹕ GC_FOR_ALLOC freed 209K, 10% free 3129K/3460K, paused 2ms, total 2ms
04-21 14:58:11.336 6199-6199/webmd.mmu.ac.uk.wmfinal3 D/AndroidRuntime﹕ Shutting down VM
04-21 14:58:11.336 6199-6199/webmd.mmu.ac.uk.wmfinal3 W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb0cb3b20)
04-21 14:58:11.336 6199-6199/webmd.mmu.ac.uk.wmfinal3 E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: webmd.mmu.ac.uk.wmfinal3, PID: 6199
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:3562)
at android.view.ViewGroup.addView(ViewGroup.java:3415)
at android.widget.TableLayout.addView(TableLayout.java:429)
at android.view.ViewGroup.addView(ViewGroup.java:3360)
at android.widget.TableLayout.addView(TableLayout.java:411)
at android.view.ViewGroup.addView(ViewGroup.java:3336)
at android.widget.TableLayout.addView(TableLayout.java:402)
at webmd.mmu.ac.uk.wmfinal3.MainActivity$ProgressTask$1$1.run(MainActivity.java:245)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
I tried moving all the code into the AsyncTask but it then demands to be on the UI Thread.
Here is my code. Any help would be much appreciated.
protected Boolean doInBackground(final String... args) {
final TableLayout tl = (TableLayout) findViewById(R.id.table);
final TableRow v1 = new TableRow(MainActivity.this);
JSONParser jParser = new JSONParser();
String temp = "http://sandbox.kriswelsh.com/hygieneapi/hygiene.php?op=nearest&lat=" + latitude + "&long=" + longitude;
JSONArray json = jParser.getJSONFromUrl(temp);
int [] test = new int [10];
for (int i = 0; i < 10; i++) {
try {
JSONObject c = json.getJSONObject(i);
String vid = c.getString(id);
String vbn = c.getString(BusinessName);
String va1 = c.getString(Add1);
String va2 = c.getString(Add2);
String va3 = c.getString(Add3);
String vpost = c.getString(Post);
String vlong = c.getString(longitudej);
String vrate = c.getString(RatingDate);
String vratestar = c.getString(Rating);
String vlat = c.getString(latitudej);
if (vratestar.contentEquals("-1")) {
vratestar = "Exempt";
}
//testing(vbn,va1,va2,va3,vpost,vratestar);
//TableLayout tl = (TableLayout) findViewById(R.id.table);
isRunning = true;
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (isRunning) {
try {
// Thread.sleep(10000);
mHandler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
tl.addView(v1);
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();
isRunning = false;
//jsonlist.add(map);
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
UPDATE: Now shows v1 initialization
Looking at your while (isRunning) loop I suppose you are trying to add the same v1 TableRow view to the TableLayout on each iteration (however, it is just a guess, because you didn't post v1 declaration). Of course, at the second time it will give you an error as it is already has parent, you should create new TableRow object each time. Going deeper, you don't need Handler which is connected to UI thread, because you are using AsyncTask, you can take advantage of the fact, that onPostExecute method is executed on the main thread. Considering it, you can write the following AsyncTask implementation:
class MyAsyncTask extends AsyncTask<Void, Void, JSONArray>{
#Override
protected JSONArray doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
String temp = "http://sandbox.kriswelsh.com/hygieneapi/hygiene.php?op=nearest&lat=" + latitude + "&long=" + longitude;
JSONArray json = jParser.getJSONFromUrl(temp);
return json;
}
#Override
protected void onPostExecute(JSONArray json) {
TableLayout tl = (TableLayout) findViewById(R.id.table);
for (int i = 0; i < 10; i++) {
try {
JSONObject c = json.getJSONObject(i);
String vid = c.getString(id);
String vbn = c.getString(BusinessName);
String va1 = c.getString(Add1);
String va2 = c.getString(Add2);
String va3 = c.getString(Add3);
String vpost = c.getString(Post);
String vlong = c.getString(longitudej);
String vrate = c.getString(RatingDate);
String vratestar = c.getString(Rating);
String vlat = c.getString(latitudej);
if (vratestar.contentEquals("-1")) {
vratestar = "Exempt";
}
TableRow tableRow = new TableRow(context);
//configuring row, setting layout params
tl.addView(tableRow);
} catch (JSONException ex){
//error handling
}
}
}
}

Cannot save files to SDcard android app

Im having a problem saving/ creating a file on my sdcard to save text to, i am trying to check if the file is created and if not create it, then write certain data to it on button click. Here is my code and error output:
This is the error output:
java.lang.RuntimeException: Unable to start activity ComponentInfo{ibettergetagoodgradeforthisorillbepissed.sciencefair.beta.mmmeds.com.mmmeds/ibettergetagoodgradeforthisorillbepissed.sciencefair.beta.mmmeds.com.mmmeds.MainActivity}: java.lang.IllegalArgumentException: File /sdcard/output.txt contains a path separator
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2187)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2236)
at android.app.ActivityThread.access$800(ActivityThread.java:138)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1199)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5034)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1270)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1086)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalArgumentException: File /sdcard/output.txt contains a path separator
at android.app.ContextImpl.makeFilename(ContextImpl.java:2165)
at android.app.ContextImpl.getFileStreamPath(ContextImpl.java:964)
at android.content.ContextWrapper.getFileStreamPath(ContextWrapper.java:195)
at ibettergetagoodgradeforthisorillbepissed.sciencefair.beta.mmmeds.com.mmmeds.MainActivity.onCreate(MainActivity.java:207)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2151)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2236)
            at android.app.ActivityThread.access$800(ActivityThread.java:138)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1199)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5034)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
and here is the code for the file saving:
String SDRoot = Environment.getExternalStorageDirectory().getPath();
final File output = getFileStreamPath(SDRoot + "/output.txt");
if(!output.exists()){
try {
output.createNewFile();
Context context = getApplicationContext();
CharSequence text = "Output File Created!";
int duration = Toast.LENGTH_LONG;
Toast fileCreated = Toast.makeText(context, text, duration);
fileCreated.show();
} catch (IOException e) {
Context context = getApplicationContext();
CharSequence text = "Output File Not Created!";
int duration = Toast.LENGTH_LONG;
Toast fileNotCreated = Toast.makeText(context, text, duration);
fileNotCreated.show();
e.printStackTrace();
}
}
Button addbutton = (Button)findViewById(R.id.addMeds);
addbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String outputLine = medOut.toString() + doseOut.getText() + dayout.getText() + timeOut.getText();
try {
FileOutputStream fOut = new FileOutputStream(output);
OutputStreamWriter myOutputStreamWriter = new OutputStreamWriter(fOut);
myOutputStreamWriter.append(outputLine);
myOutputStreamWriter.flush();
myOutputStreamWriter.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
}
http://developer.android.com/reference/android/content/Context.html#getFileStreamPath(java.lang.String)
Parameters : name The name of the file for which you would like to get its path.
If you give a path (containing "/") instead, it will crash as you have already noticed.
Besides, this function applies only for your application private files, created with openFileOuput for instance.
http://developer.android.com/reference/android/content/Context.html#openFileOutput(java.lang.String, int)
Just do like this :
String SDRoot = Environment.getExternalStorageDirectory().getPath();
final File output = new File(SDRoot + "/output.txt");

java.lang.RuntimeException: Unable to start receiver *.mycustomReceiver java.lang.NullPointerException

I am getting a Java null pointer exception Unable to start receiver error. I am making an app which receives the push from the parse.com and I am getting the error for Android 4.0.3 - 4.0.4, and also when I restart the some devices..
My LogCat is
**java.lang.RuntimeException: Unable to start receiver com.omega.omegaplus.main.MyCustomReceiver: java.lang.NullPointerException
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2419)
at android.app.ActivityThread.access$1500(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1322)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:4987)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
at org.json.JSONTokener.nextValue(JSONTokener.java:94)
at org.json.JSONObject.<init>(JSONObject.java:154)
at org.json.JSONObject.<init>(JSONObject.java:171)
at com.omega.omegaplus.main.MyCustomReceiver.onReceive(MyCustomReceiver.java:30)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2408)
... 10 more**
My broadcast receiver is
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
String message = extras != null ? extras.getString("com.parse.Data")
: "";
Log.e("message ", " " + message);
JSONObject jObject;
try {
jObject = new JSONObject(message);
//objectId = jObject.getString("id");
time = jObject.getString("time");
msg = jObject.getString("title");
title = jObject.getString("msg");
GCMMessage gcmMessage = new GCMMessage();
//gcmMessage.setMsg_id(1);
gcmMessage.setMsg_body(msg);
gcmMessage.setMsg_title(title);
gcmMessage.setType(0);
gcmMessage.setDateTime(time);
DatabaseUtil.insertMessage(context, gcmMessage);
}
catch (JSONException e) {
e.printStackTrace();
}
}
When I reboot my phone then also it showing same error..., otherwise it is working fine.
I'll have a guess that message has the value of "" or NULL
JSONObject jObject;
try {
if (message != null && !message.equals("") {
jObject = new JSONObject(message);
//objectId = jObject.getString("id");
time = jObject.getString("time");
msg = jObject.getString("title");
title = jObject.getString("msg");
GCMMessage gcmMessage = new GCMMessage();
//gcmMessage.setMsg_id(1);
gcmMessage.setMsg_body(msg);
gcmMessage.setMsg_title(title);
gcmMessage.setType(0);
gcmMessage.setDateTime(time);
DatabaseUtil.insertMessage(context, gcmMessage);
}
}
catch (JSONException e) {
e.printStackTrace();
}

Writing arrayList <class> to file [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 8 years ago.
I am new to android app development and I tried to write an arrayList to a file, but I've been getting problems when attempting to do that in my code:
public class AddActivity extends Activity implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public transient Context ctx;
private final String filename = "Accounts";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
final EditText name = (EditText) findViewById(R.id.name);
final EditText username = (EditText) findViewById(R.id.username);
final EditText password = (EditText) findViewById(R.id.password);
final EditText type = (EditText) findViewById(R.id.type);
Button add = (Button) findViewById(R.id.add);
add.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("unchecked")
public void onClick(View arg0) {
String n = name.getText().toString();
String u = username.getText().toString();
String p = password.getText().toString();
String t = type.getText().toString();
Account newAccount = new Account (n, u , p, t);
ArrayList<Account> accounts;
String filePath = getFilesDir().getPath().toString() + "/" + filename;
File fl = new File(filePath);
try {
if (fl.exists()){
FileInputStream fis = ctx.openFileInput(filename);
ObjectInputStream oi = new ObjectInputStream(fis);
accounts = (ArrayList<Account>) oi.readObject();
accounts.add(newAccount);
oi.close();
fis.close();
fl.delete();
}else{
accounts = new ArrayList<Account>();
accounts.add(newAccount);
}
fl.createNewFile();
FileOutputStream fos = (openFileOutput(filename, Context.MODE_PRIVATE));
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(accounts);
oos.flush();
oos.close();
fos.close();
} catch (IOException e) {
Log.e("InternalStorage", e.getMessage());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
});
}
}
My logCat says this:
05-20 18:56:23.782: E/AndroidRuntime(2242): FATAL EXCEPTION: main
05-20 18:56:23.782: E/AndroidRuntime(2242): Process: com.chenw15.accountmanager, PID: 2242
05-20 18:56:23.782: E/AndroidRuntime(2242): java.lang.NullPointerException
05-20 18:56:23.782: E/AndroidRuntime(2242): at com.chenw15.accountmanager.AddActivity$1.onClick(AddActivity.java:56)
05-20 18:56:23.782: E/AndroidRuntime(2242): at android.view.View.performClick(View.java:4438)
05-20 18:56:23.782: E/AndroidRuntime(2242): at android.view.View$PerformClick.run(View.java:18422)
05-20 18:56:23.782: E/AndroidRuntime(2242): at android.os.Handler.handleCallback(Handler.java:733)
05-20 18:56:23.782: E/AndroidRuntime(2242): at android.os.Handler.dispatchMessage(Handler.java:95)
05-20 18:56:23.782: E/AndroidRuntime(2242): at android.os.Looper.loop(Looper.java:136)
05-20 18:56:23.782: E/AndroidRuntime(2242): at android.app.ActivityThread.main(ActivityThread.java:5017)
05-20 18:56:23.782: E/AndroidRuntime(2242): at java.lang.reflect.Method.invokeNative(Native Method)
05-20 18:56:23.782: E/AndroidRuntime(2242): at java.lang.reflect.Method.invoke(Method.java:515)
05-20 18:56:23.782: E/AndroidRuntime(2242): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-20 18:56:23.782: E/AndroidRuntime(2242): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-20 18:56:23.782: E/AndroidRuntime(2242): at dalvik.system.NativeStart.main(Native Method)
Every time I click my add button, I get an error that says "Unfortunately, (App name) has stopped". Please help. Thanks.
I think you can also try below code for writing the list in file:
File myfile = getFileStreamPath(FileName);
try {
if (myfile.exists() || myfile.createNewFile()) {
FileOutputStream fos = openFileOutput(FileName, MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(masterlistrev);
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}

Categories

Resources