Android static vs nonstatic issue - java

I've been trying to call the following:
public static void startfile() {
Log.i("File Works", "working2 ");
try {
FileOutputStream fos = openFileOutput("sdcard/sdtext.txt", MODE_WORLD_WRITEABLE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I get an error that tells me that "Cannot make a static reference to the non-static method openFileOutput(String, int) from the type ContextWrapper"
So I searched for that error and found this site.
I implemented this:
public static void startfile(Trackfile O) {
Log.i("File Works", "working2 ");
O.nonstatstartfile();
}
public void nonstatstartfile(){
Log.i("File Works", "nonStat");
try {
FileOutputStream fos = openFileOutput("sdcard/sdtext.txt", MODE_WORLD_WRITEABLE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
When I call startfile from another class getting a Null pointer error. What argument do I need to send to avoid the null pointer error?

You can pass context from activity like below
public static void startfile(Context c) {
Log.i("File Works", "working2 ");
try {
FileOutputStream fos = c.openFileOutput("sdcard/sdtext.txt", MODE_WORLD_WRITEABLE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

public void startfile() {
Log.i("File Works", "working2 ");
try {
FileOutputStream fos = openFileOutput("sdcard/sdtext.txt", MODE_WORLD_WRITEABLE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Add this method to your class, and use it without problems.
If you need it in main class, use it over object.

Related

last object serialized gets overwritten

I am writing a program for keeping track of library books. There is an object book that includes a title, sku number, price and quantity. All the books are stored in an Array List. I'm trying to serialize the books and add new books but every time a book is added the last is overwritten.
here is the code below to load objects from save
public static void readSave() {
File stockFile = new File("inventory.txt");
try {
if(!stockFile.createNewFile() && stockFile.length() != 0) {
ObjectInputStream objIn = new ObjectInputStream(new FileInputStream(stockFile));
int size = objIn.readInt();
for(int i = 0; i < size; i++) {
Book t = (Book) objIn.readObject();
bookList.add(t);
}
objIn.close();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
here is my save method and it is set to save every time the program executes.
public static void save() {
File inventoryFile = new File("inventory.txt");
ObjectOutputStream objOut;
try {
objOut = new ObjectOutputStream(new FileOutputStream(inventoryFile));
objOut.writeInt(bookList.size());
Iterator<Book> i = bookList.iterator();
while(i.hasNext()){
objOut.writeObject(i.next());
}
objOut.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
below is my main method which calls these functions
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
readSave();
CampusBookWindow window = new CampusBookWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
save();
}
});
}
My problem was when I hit the add book button I would not create a new book object for that item, but instead I was reassigning that last book object so the object last book object was erased from the bookList array list

Why am I getting InvocationTargetException at ClassLoaders.callStaticFunction Java Eclipse? [duplicate]

I have created a program to convert text to xml by using ReverseXSL API.
This program is to be executed by an application by calling static method (static int transformXSL).
I am able to execute and produce output with running from Eclipse. However, When I ran program (jar) by using application it stuck somewhere and I couldnt find anything.
Then, I debugged by "Debug as...-> Remote Java Application" in Eclipse from Application and found "InvocationTargetException" at ClassLoaders.callStaticFunction.
Below Static method is called by application.
public class MyTest4 {
public MyTest4()
{
}
public static int transformXSL(String defFile, String inputFile, String XSLFile, String OutputFile) {
System.out.println("Dheeraj's method is called");
// start time
FileWriter fw=null;
try {
fw = new FileWriter("D://Countime.txt");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedWriter output=new BufferedWriter(fw);
DateFormat sd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date dt= new Date();
System.out.println("Date is calculated");
try {
output.write("Start Time:"+sd.format(dt).toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(sd.format(dt));
FileReader myDEFReader=null, myXSLReader=null;
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t=null;
FileInputStream inStream = null;
ByteArrayOutputStream outStream = null;
// Step 1:
//instantiate a transformer with the specified DEF and XSLT
if (new File(defFile).canRead())
{
try {
myDEFReader = new FileReader(defFile);
System.out.println("Definition file is read");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
else myDEFReader = null;
if (new File(XSLFile).canRead())
try {
myXSLReader = new FileReader(XSLFile);
System.out.println("XSL file is read");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
else myXSLReader = null;
try {
t = tf.newTransformer(myDEFReader, myXSLReader);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Step 1: DEF AND XSLT Transformation completed");
// Step 2:
// Read Input data
try {
inStream = new FileInputStream(inputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
outStream = new ByteArrayOutputStream();
System.out.println("Step 2: Reading Input file: completed");
// Step 3:
// Transform Input
try {
try (BufferedReader br = new BufferedReader(new FileReader("D://2.txt"))) {
String line = null;
while ((line = br.readLine()) != null) {
System.out.println("Content: "+line);
}
}
System.out.println("File: "+inputFile.toString());
System.out.println("\n content: \n"+ inStream.toString());
System.out.println("Calling Transform Function");
t.transform(inStream, outStream);
System.out.println("Transformation is called");
outStream.close();
try(OutputStream outputStream = new FileOutputStream(OutputFile)) {
outStream.writeTo(outputStream);
System.out.println("Outstream is generated; Output file is creating");
}
System.out.println(outStream.toString());
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerFactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (javax.xml.transform.TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("output file is created");
// End time
Date dt2= new Date();
System.out.println(sd.format(dt2));
System.out.println("End time:"+dt2.toString());
try {
output.append("End Time:"+sd.format(dt2).toString());
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
}

Program won't run because variables "may be uninitialized"?

I'm trying to make a new thread for parsing xml from an rss feed. When I click run it says there are errors please correct them etc. I have 2 classes in my project. The other class has no errors and this class below has only warnings that a lot of the things in the try/catch statements may be uninitialized. I understand that and figured I should still be able to run the program anyways, I expect them to be initialized and if they're not that's fine I want to know about it. Is this really what's going on or am I missing something? I thought it would compile if something may be uninitialized but its not certainly uninitialized.
public class RssParse extends Thread {
Thread th=new Thread() {
public void run(){
System.out.println("1");
URL iotd;
try {
iotd = new URL("http://www.nasa.gov/rss/image_of_the_day.rss");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("2");
BufferedReader in;
try {
in = new BufferedReader(new InputStreamReader(iotd.openStream()));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("3");
XmlPullParserFactory factory;
try {
factory = XmlPullParserFactory.newInstance();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
factory.setNamespaceAware(true);
System.out.println("4");
XmlPullParser xpp;
try {
xpp = factory.newPullParser();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("5");
try {
xpp.setInput(in);
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("6");
int eventType;
try {
eventType = xpp.getEventType();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(eventType+"!!!!!!!!!!!!!!!!");
while(eventType!=XmlPullParser.END_DOCUMENT){
if(eventType==XmlPullParser.START_DOCUMENT){
System.out.println("start");
}
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//method
};//thread
}//class
Look at this try/catch block for example :
URL iotd;
try {
iotd = new URL("http://www.nasa.gov/rss/image_of_the_day.rss");
} catch (MalformedURLException e) {
e.printStackTrace();
}
If iotd = new URL("...") fails, iotd will remain uninitialized.
There are two ways to deal with this :
Assign a default value to iotd, like : URL iotd = null; However, it's bad here because if you use iotd later its value may be null and can throw a NullPointerException.
Stop the execution of your function if something failed instead of just printing the stack trace. For example you can add a return statement in the catch block :
URL iotd;
try {
iotd = new URL("http://www.nasa.gov/rss/image_of_the_day.rss");
} catch (MalformedURLException e) {
e.printStackTrace();
return;
}
All the warnings you are getting are because all your catch blocks are not dealing with the exception at all (just printing the stacktrace to standard out).
Let's see it through an example:
URL iotd;
try {
iotd = new URL("http://www.nasa.gov/rss/image_of_the_day.rss");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
at that snipped you are declaring a iotd variable as a URL but without initializing it (not assigning any value), you do it inside the try block - which isn't wrong by the way. However if for any reason the statement inside the try block throws an exception program flow will go to the catch block leaving the iotd variable with its initial value (unassigned).
So, in that case, execution of the program will continue and when reaching this statement:
in = new BufferedReader(new InputStreamReader(iotd.openStream()));
it will find no value assigned to the iotd variable.
To remove the warning regarding the uninitialized value you can either assign a null value to the variable when declaring it or rethrow another exception inside the catch block, stopping the program flow.
In the other hand, the snippet you posted here is not just one class, it's actually two as you are extending the Thread class and then creating an anonymous one inside its body. Using threads is easier than that in Java, just implement the Runnable interface and then instantiate a new thread from that interface:
public class MyRunnable implements Runnable {
public void run() {
// do stuff
}
}
and then:
new Thread(new MyRunnable()).start();
cheers
you need to initialize the variables above the try catch block, or give them a value in catch or finally block
find updated code here
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
public class RssParse extends Thread {
Thread th=new Thread() {
public void run(){
System.out.println("1");
URL iotd=null;
try {
iotd = new URL("http://www.nasa.gov/rss/image_of_the_day.rss");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("2");
BufferedReader in=null;
try {
in = new BufferedReader(new InputStreamReader(iotd.openStream()));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("3");
XmlPullParserFactory factory=null;
try {
factory = XmlPullParserFactory.newInstance();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
factory.setNamespaceAware(true);
System.out.println("4");
XmlPullParser xpp=null;
try {
xpp = factory.newPullParser();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("5");
try {
xpp.setInput(in);
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("6");
int eventType=-1; // set to a default value of your choice
try {
eventType = xpp.getEventType();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(eventType+"!!!!!!!!!!!!!!!!");
while(eventType!=XmlPullParser.END_DOCUMENT){
if(eventType==XmlPullParser.START_DOCUMENT){
System.out.println("start");
}
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}//method
};//thread
}//class

Using sockets and Object IO streams in Android programming

I'm trying to implement multiplayer in a game I've been writing, and I've gotten everything to successfully connect (I think..), but when I'm running it, there's an EOFException thrown by the client, and the object (an ArrayList) isn't successfully received.
Code for the server thread:
class ServerThread implements Runnable
{
ServerSocket server = null;
Socket controlSocket = null;
ObjectOutputStream outStream = null;
ObjectInputStream inStream = null;
#Override
public void run() {
setupConnection();
while(true){
sendObject(out.getStuff());
}
}
void setupConnection(){
Log.e("OUTPUTSHOOTER","init-connect");
try {
server = new ServerSocket(SERVERPORT);
Log.e("OUTPUTSHOOTER","server initiated port: "+SERVERPORT);
controlSocket = server.accept();
Log.e("OUTPUTSHOOTER","connected");
inStream = new ObjectInputStream(controlSocket.getInputStream());
outStream = new ObjectOutputStream(controlSocket.getOutputStream());
} catch (StreamCorruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e("OUTPUTSHOOTER",server+" "+controlSocket+" "+inStream+" "+outStream);
}
public Object recieveObject(){
Object o = null;
try {
o = inStream.readObject();
} catch (OptionalDataException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return o;
}
public void sendObject(Object o)
{
try {
outStream.writeObject(o);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
And then the code for the client:
class ClientThread implements Runnable
{
Socket controlSocket = null;
ObjectOutputStream outStream = null;
ObjectInputStream inStream = null;
#Override
public void run() {
setupConnection();
while(true){
Log.e("OUTPUTSHOOTER","recieving");
Object in = recieveObject();
if(in!= null && in instanceof ArrayList)
{
Log.e("OUTPUTSHOOTER","loading");
out.load((ArrayList<UniverseObject>)in);
}
}
}
void setupConnection(){
Log.e("OUTPUTSHOOTER","ip: "+SERVERIP);
while(controlSocket == null) {
try {
controlSocket = new Socket(SERVERIP,SERVERPORT);
Log.e("OUTPUTSHOOTER","socket connected");
} catch (IOException e) {
e.printStackTrace();
}
}
try {
Log.e("OUTPUTSHOOTER","attempting streams");
outStream = new ObjectOutputStream(controlSocket.getOutputStream());
Log.e("OUTPUTSHOOTER","output working");
inStream = new ObjectInputStream(controlSocket.getInputStream());
Log.e("OUTPUTSHOOTER","streams connected");
} catch (StreamCorruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Object recieveObject(){
Object o = null;
try {
o = inStream.readObject();
} catch (OptionalDataException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return o;
}
public void sendObject(Object o)
{
try {
outStream.writeObject(o);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
What does this mean? And perhaps more importantly, how can I fix it? Thanks in advance..
I don't see you closing your outputstream.
See this SO topic: Problem serializing and deserializing ArrayList
Turns out the server wasn't properly initiating it's input and output streams, even though its sockets were successful. Dunno why, but it only works if I started with the output stream first, then the input (?). Having some other really strange bugs, but at least the communication seems to work.. I'll look more in to them before posting here about it. Thanks guys!

Serialization of a class which doesnt implement Serializable

I have 2 classes serial1 and serial 2. serial1 implements Serializable whereas serial2 does not.As per theory i should get an Exception for the following code, but it is working fine. why is it so ?
import java.io.*;
public class SerialTest {
public static void main(String args[]){
FileOutputStream fos=null;
ObjectOutputStream oos =null;
serial1 se = new serial1();
serial1 sd = null;
se.mets();
try {
fos= new FileOutputStream("serialtest");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
oos =new ObjectOutputStream(fos);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
oos.writeObject(se);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileInputStream fis=null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream("serialtest");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
ois = new ObjectInputStream(fis);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
sd = (serial1) ois.readObject();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sd.mets();
}
}
import java.io.Serializable;
public class serial1 implements Serializable{
/* public static void main(String []args){
serial1 ss = new serial1();
ss.mets();
}*/
public void mets(){
serial2 s2 = new serial2();
System.out.println( "serial 1 + mets");
s2.met1();
}
}
public class serial2 {
public void met1(){
System.out.println("serial2 + met1");
}
}
---------------------------*
The output is
serial 1 + mets
serial2 + met1
serial 1 + mets
serial2 + met1
You don't actually serialize serial2. Your mets method creates a local variable but as soon as the method returns it goes out of scope and becomes eligible for garbage collection.
If you had an instance variable of type serial2 inside serial1 then you would see an exception when you try to serialize (assuming it's a non-null value), but a local variable will not be a problem.
I don't see you ever serializing serial2

Categories