I have an OpenGL game with two images, one is a texture atlas, and one is a single image. When I try to open the single one to an OpenGL object the application dies when closing it.
The code:
InputStream is = context.getResources().openRawResource(texture);
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream(is);
} finally {
try {
is.close();
is = null;
Log.i("log", "try");
} catch (IOException e) {
Log.i("log", "Catch");
}
}
It decodes the InputStream, but it steps into the catch after closing. I really can't understand what is the problem. Opening and closing InputStreams with the other texture works fine.
try the below code to print a stacktrace
final Writer result = new StringWriter();
final PrintWriter printWriter = new PrintWriter(result);
ex.printStackTrace(printWriter);
String stacktrace = result.toString();
Log.i("log", "Catch" + stacktrace);
then hopefully you will have your answer :)
Related
The following code basically works as expected. However, to be paranoid, I was wondering, to avoid resource leakage,
Do I need to call HttpURLConnection.disconnect, after finish its usage?
Do I need to call InputStream.close?
Do I need to call InputStreamReader.close?
Do I need to have the following 2 line of code : httpUrlConnection.setDoInput(true) and httpUrlConnection.setDoOutput(false), just after the construction of httpUrlConnection?
The reason I ask so, is most of the examples I saw do not do such cleanup. http://www.exampledepot.com/egs/java.net/post.html and http://www.vogella.com/articles/AndroidNetworking/article.html. I just want to make sure those examples are correct as well.
public static String getResponseBodyAsString(String request) {
BufferedReader bufferedReader = null;
try {
URL url = new URL(request);
HttpURLConnection httpUrlConnection = (HttpURLConnection)url.openConnection();
InputStream inputStream = httpUrlConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
int charRead = 0;
char[] buffer = new char[1024];
StringBuffer stringBuffer = new StringBuffer();
while ((charRead = bufferedReader.read(buffer)) > 0) {
stringBuffer.append(buffer, 0, charRead);
}
return stringBuffer.toString();
} catch (MalformedURLException e) {
Log.e(TAG, "", e);
} catch (IOException e) {
Log.e(TAG, "", e);
} finally {
close(bufferedReader);
}
return null;
}
private static void close(Reader reader) {
if (reader != null) {
try {
reader.close();
} catch (IOException exp) {
Log.e(TAG, "", exp);
}
}
}
Yes you need to close the inputstream first and close httpconnection next. As per javadoc.
Each HttpURLConnection instance is used to make a single request but the underlying network connection to the HTTP server may be transparently shared by other instances. Calling the close() methods on the InputStream or OutputStream of an HttpURLConnection after a request may free network resources associated with this instance but has no effect on any shared persistent connection. Calling the disconnect() method may close the underlying socket if a persistent connection is otherwise idle at that time.
Next two questions answer depends on purpose of your connection. Read this link for more details.
I believe the requirement for calling setDoInput() or setDoOutput() is to make sure they are called before anything is written to or read from a stream on the connection. Beyond that, I'm not sure it matters when those methods are called.
i am thinking about there are some many way to store data in file , i found one of this is useing buffedinputstream ,but i really don't know is it good ??
if i using like this , it will be most fast ??
is there any other suggestion ?? i just want make the file io more fast !!
public ArrayList<String> testReadingTxtFromFile(){
ArrayList<String> result = null;
try {
FileInputStream fIn = openFileInput("cacheingtext.txt");
InputStreamReader isr = new InputStreamReader(fIn);
BufferedReader reader = new BufferedReader(isr);
String line;
while((line = reader.readLine() )!= null){
String[] datas = line.split(",");
Log.i("check", datas.length+"");
for(String data:datas){
Log.i("check", data);
result.add(data);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public void testWritingTxtToFile(String[] messages){
try {
FileOutputStream fo = openFileOutput("cacheingtext.txt", MODE_WORLD_READABLE);
OutputStreamWriter osw = new OutputStreamWriter(fo);
BufferedWriter writer = new BufferedWriter(osw);
int size = messages.length;
for(int i=0;i<size;i++){
writer.write(messages[i]);
writer.write(",");
Log.i("check", "write "+messages[i]);
}
writer.flush();
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The Reader/Writer class hierarchy is character-oriented, and the Input Stream/Output Stream class hierarchy is byte-oriented.
Basically there are two types of streams.Byte streams that are used to handle stream of bytes and character streams for handling streams of characters.
What I see in your case is that you are using a byte-oriented Stream.
Character streams are often "wrappers" for byte streams. The character stream uses the byte stream to perform the physical I/O, while the character stream handles translation between characters and bytes. FileReader, for example, uses FileInputStream, while FileWriter uses FileOutputStream.
So,if you want to generally deal with Characters (reading text files), go for Character-oriented Stream(Reader/Writer). But if you want to process the content independent of what type of file is it, go for byte-oriented stream.
I'm writing a small app that's supposed to mirror moves made on another phone during a game of tetris. It works perfectly for a little while, untill i get a CorruptedStreamException on the server side while writing an object.
Here's the code for the server:
public void run() {
ServerSocket ss = null;
Socket s = null;
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
try{
ss = new ServerSocket(PORT);
s = ss.accept();
Log.i(TAG,"accepted");
oos.flush();
ois = new ObjectInputStream(s.getInputStream());
while(run){
busy=true;
oos.writeObject(positions);
busy = false;
this.sleep(100);
oos.reset();
}
} catch (Exception e) {
e.printStackTrace();
}finally{//close sockets!!
try{
ois.close();
oos.close();
s.close();
ss.close();
}catch(Exception e){}
}
}
I'll toss out the client side code too:
public void run() {
Canvas c = null;
Socket s = null;
ObjectInputStream ois = null;
ObjectOutputStream oos = null;
try {
Log.i(TAG, "it entered try");
s = new Socket(IP, PORT);
oos = new ObjectOutputStream(s.getOutputStream());
oos.flush();
ois = new ObjectInputStream(s.getInputStream());
Log.i("try","has connected");
while(run){
blockList=(ArrayList<Posision>)ois.readObject();
if(blockList!=null){
try{
c=mSurfaceHolder.lockCanvas(null);
synchronized(mSurfaceHolder){
mTetrisView.drawTetris(c, blockList);
}
}finally{
if(c!=null){
mSurfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
}catch (EOFException ez){
Log.i("catch", "End of file");
} catch (Exception e) {
Log.i("catch",e.getMessage());
e.printStackTrace();
}finally{//close socket!!
try{
ois.close();
oos.close();
s.close();
}catch(IOException e){}
}
}
And a stack trace might come in handy too, when thinking of it:
java.io.StreamCorruptedException
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1712)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1665)
at com.prosjekt.tetris2.ServerThread.run(ServerThread.java:42)
Now why am I getting this error? As far as I know, writeObject() shouldn't be able to throw it.
I'm not really sure how I figured this out, but turns out that the client thread didn't print the errors it got (this however, doesn't explain why the server side threw the corruptedStreamException). The fault lay with the client getting a OptionalDataException with the length field set to 0 (indicates end of stream). I knew for a fact that the writeObject were called often enough that this shouldn't be a problem, so I decided to rewrite part of the code.
The final fix is really too simple, and this is how my while loop at server side looked like after rewriting:
while(run){
oos.writeObject(new ArrayList<Posisions>(positions));
oos.flush();
}
There's viritually no changes to the client side, so I guess the rate of resets() somehow stomped the stream.
i want to send my data in form of json to server using post method in android.
here is my format |data1|data2|data3|<>|data11|data22|data33
hope some example since i difficult to catch the procedure of post method.
Anyidea?
Edit:
my json format |data1|data2|data3|<>|data11|data22|data33|
where each data is a plain text (text get from database)
how can create it??
This blog post seems to talk about just that.
Post JSON Using Android And HttpClient
Edit: I saw your reply. Here's how. Hope this does the trick :)
public static void main(String[] args) {
File file = new File("<path to json file>");
FileInputStream fis;
String json = "";
try {
fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
// dis.available() returns 0 if the file does not have more lines.
while (dis.available() != 0) {
json += dis.readLine();
}
// dispose all the resources after using them.
fis.close();
bis.close();
dis.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Essentially after this you would create the string entity to send
StringEntity st = new StringEntity(json.toString());
Then just follow the steps in that link
Haha, edit for your 2nd question: Just create a string with the text from the database. Thats all there is to it. Then create a StringEntity like the one above.
So I'm unexpectedly receiving a FileNotFoundException. As you can see, shortly before I call the FileReader, I call FileInputStream which works fine. I've tried putting the FileReader in its own Try/Catch clause, but receive the same result. I've gutted most of the lines unnecessary to my question from this block. (Ultimately I call LineNumberReader as well, though I removed it from the block because I'm not even getting that far.)
String FILENAME = "file.txt";
try {
byte[] buffer = new byte[128];
String toStr = new String();
TextView view = (TextView)findViewById(R.id.textview);
FileInputStream fis = openFileInput(FILENAME); /////File is found successfully here/////
fis.read(buffer);
fis.close();
toStr = new String(buffer);
view.append(toStr);
FileReader fr = new FileReader(FILENAME); /////FileNotFoundExceptionThrownHere/////
/////do stuff here/////
fr.close();
}
catch (FileNotFoundException e) {
TextView view = (TextView)findViewById(R.id.textview);
view.append("file not found!");
}
catch (IOException e) {
TextView view = (TextView)findViewById(R.id.textview);
view.append("IO error!");
}
Also, please keep in mind when answering that I'm still somewhat of a novice when it comes to java. I have experience in a couple other languages but java is a bit of a different breed of monster to me. Any help would be tremendously appreciated!
openFileInput() and new FileReader() do not take the same parameter.
openFileInput("file.txt") is equivalent to new FileReader(new File(getFilesDir(), "file.txt")).