Skip to content Skip to sidebar Skip to footer

Saving A Json File To Internal Memory

hey there guys and girls i have this code that should download a json object and then save it to internal memory, i keep getting stuck here try{ //connects to mySQL

Solution 1:

Try this code

package com.android.test.CacheDemo;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

publicclassCachingDemoActivityextendsActivityimplementsOnClickListener{
    privatestatic String URL="http://bhaskar1.cntdy.mobi/punjabkesari/appdetails/sectiondetails.json";
    privatestaticStringFILE_NAME="CachedResponse";
    private Button startAPICallButton;
    private Button retrieveFromCacheButton;

    /* view lifecycle methods*/@OverridepublicvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        this.initializeComponents();
    }
    /*overriden methods*/publicvoidonClick(View clickedView)
    {
        if(clickedView == this.startAPICallButton)
        {
            Toast.makeText(this, "Making the API call... Please wait", Toast.LENGTH_LONG).show();
            this.makeAPICall();
        }
        elseif(clickedView == this.retrieveFromCacheButton)
        {
            Toast.makeText(this, "Retrieving data from the cache!!!", Toast.LENGTH_LONG).show();
            this.retrieveStuffFromCache();
        }
    }
    /* private methods*/privatevoidinitializeComponents()
    {
        this.startAPICallButton = (Button) this.findViewById(R.id.start_api_call_button);
        this.startAPICallButton.setOnClickListener(this);
        this.retrieveFromCacheButton = (Button) this.findViewById(R.id.retrieve_cache_button);
        this.retrieveFromCacheButton.setOnClickListener(this);
    }
    privatevoidmakeAPICall()
    {
        newThread(newRunnable() 
        {
            @Overridepublicvoidrun() 
            {
                try
                {
                    //download the json onto the device.URLurl=newURL(CachingDemoActivity.URL);
                    URLConnectionconnection= url.openConnection();
                    //read the data and store it in a byte array first.//dont use this code for big json file //as long as its a json and not very long, this will work just fine!!!InputStreaminStream= connection.getInputStream();
                    ByteArrayOutputStreambyteOutStream=newByteArrayOutputStream();
                    intreadByte=0;
                    //read the bytes one-by-one from the inputstream to the buffer.while(true)
                    {
                        readByte = inStream.read();
                        if(readByte == -1)
                        {
                            break;
                        }
                        byteOutStream.write(readByte);
                    }
                    byteOutStream.flush();
                    inStream.close();
                    byteOutStream.close();
                    byte[] response = byteOutStream.toByteArray();
                    //now response byte array is the complete json in the biary form. We will save this stuff to file.FilecacheDir= CachingDemoActivity.this.getCacheDir();
                    FilejsonFile=newFile(cacheDir, FILE_NAME);
                    FileOutputStreamoutStream=newFileOutputStream(jsonFile);
                    //write the whole data into the filefor(inti=0; i < response.length; i++)
                    {
                        outStream.write(response[i]);
                    }
                    android.util.Log.e("status - ","API call is complete!!");
                    //this should do the trick of saving all the stuff in the file with file name CachedResponse!!//let see if we can retrieve the stuff!!!
                } 
                catch (Exception e) 
                {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    privatevoidretrieveStuffFromCache()
    {
        newThread(newRunnable() 
        {
            @Overridepublicvoidrun() 
            {
                try
                {
                    FilejsonFile=newFile(CachingDemoActivity.this.getCacheDir(), FILE_NAME);
                    FileInputStreamfInStream=newFileInputStream(jsonFile);
                    ByteArrayOutputStreambyteOutStream=newByteArrayOutputStream();
                    intreadByte=0;
                    while(true)
                    {
                        readByte = fInStream.read();
                        if(readByte == -1)
                        {
                            break;
                        }
                        byteOutStream.write(readByte);
                    }
                    fInStream.close();
                    byteOutStream.flush();
                    byteOutStream.close();
                    byte[] retrievedStringData = byteOutStream.toByteArray();
                    StringoriginalJson=newString(retrievedStringData);
                    android.util.Log.e("json - ", originalJson);
                }
                catch(Exception ex)
                {
                    ex.printStackTrace();
                }
            }
        }).start();
    }
}

Solution 2:

This is weird case, I edited my previous answer to fix this problem of yours. However: another question was asked, so here goes this portion of my previous answer:

About the error you get - you are trying to cast the entity of the response directly to an Integer. This will always fail, because Integer is not superclass of HttpEntity. You need to read the contents of the entity in a String and then parse the contents of the string to integer:

InputStreamentityStream= entity.getcontent();
StringBuilderentityStringBuilder=newStringBuilder();
byte [] buffer = newbyte[1024];
int bytesReadCount;
while ((bytesReadCount = entityStream.read(buffer)) > 0) {
    entityStringBuilder.append(newString(buffer, 0, bytesReadCount));
}
StringentityString= entityStringBuilder.toString();
writer.wrtie(entityString);

this is not highly optimized, but does the job. From then on you can use the responseInteger value as you like . However if you want to do writer.write you will need String value, not Integer. Thus I recommend you to use entityString.

Post a Comment for "Saving A Json File To Internal Memory"