saving a json file to internal memory

后端 未结 2 813
眼角桃花
眼角桃花 2021-01-22 11:53

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{
        //co         


        
2条回答
  •  无人共我
    2021-01-22 12:08

    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;
    
    public class CachingDemoActivity extends Activity implements OnClickListener{
        private static String URL="http://bhaskar1.cntdy.mobi/punjabkesari/appdetails/sectiondetails.json";
        private static String FILE_NAME = "CachedResponse";
        private Button startAPICallButton;
        private Button retrieveFromCacheButton;
    
        /* view lifecycle methods*/
            @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            this.initializeComponents();
        }
        /*overriden methods*/
        public void onClick(View clickedView)
        {
            if(clickedView == this.startAPICallButton)
            {
                Toast.makeText(this, "Making the API call... Please wait", Toast.LENGTH_LONG).show();
                this.makeAPICall();
            }
            else if(clickedView == this.retrieveFromCacheButton)
            {
                Toast.makeText(this, "Retrieving data from the cache!!!", Toast.LENGTH_LONG).show();
                this.retrieveStuffFromCache();
            }
        }
        /* private methods*/
        private void initializeComponents()
        {
            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);
        }
        private void makeAPICall()
        {
            new Thread(new Runnable() 
            {
                @Override
                public void run() 
                {
                    try
                    {
                        //download the json onto the device.
                        URL url = new URL(CachingDemoActivity.URL);
                        URLConnection connection = 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!!!
                        InputStream inStream = connection.getInputStream();
                        ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
                        int readByte = 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.
                        File cacheDir = CachingDemoActivity.this.getCacheDir();
                        File jsonFile = new File(cacheDir, FILE_NAME);
                        FileOutputStream outStream = new FileOutputStream(jsonFile);
                        //write the whole data into the file
                        for(int i = 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();
        }
    
        private void retrieveStuffFromCache()
        {
            new Thread(new Runnable() 
            {
                @Override
                public void run() 
                {
                    try
                    {
                        File jsonFile = new File(CachingDemoActivity.this.getCacheDir(), FILE_NAME);
                        FileInputStream fInStream = new FileInputStream(jsonFile);
                        ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
                        int readByte = 0;
                        while(true)
                        {
                            readByte = fInStream.read();
                            if(readByte == -1)
                            {
                                break;
                            }
                            byteOutStream.write(readByte);
                        }
                        fInStream.close();
                        byteOutStream.flush();
                        byteOutStream.close();
                        byte[] retrievedStringData = byteOutStream.toByteArray();
                        String originalJson = new String(retrievedStringData);
                        android.util.Log.e("json - ", originalJson);
                    }
                    catch(Exception ex)
                    {
                        ex.printStackTrace();
                    }
                }
            }).start();
        }
    }
    

提交回复
热议问题