将 json 文件保存到内部存储器

2023-12-02

嘿,伙计们,女孩们,我有这段代码,应该下载一个 json 对象,然后将其保存到内存中,我一直卡在这里

    try{
        //connects to mySQL
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://10.0.2.2/textures_story_list.php");
        HttpResponse response = client.execute(post);
        //captures the response
        entity = response.getEntity();
    }catch(Exception e) {
         Log.e("log_tag", "Error in http connection "+e.toString());
    }
    try{
        is = entity.getContent();
        String FILENAME = "story.json";
        //gives file name
        FileOutputStream output = openFileOutput(FILENAME, MODE_WORLD_READABLE);
        //creates new StreamWriter
        OutputStreamWriter writer = new OutputStreamWriter(output);
        //writes json with file name story.json
        writer.write(is);
        writer.flush();
        //closes writer
        writer.close();

    }catch(Exception e) {
         Log.e("log_tag", "Error saving string "+e.toString());
    }

我不断收到 writer.write(is); 上的错误eclipse 要求我将其更改为 int,从行编码的最佳方式是什么

entity = response.getEntity();

???

这是我的完整代码

    public class MainActivity extends Activity {

String storyObj = "";
Object json = null;
HttpEntity entity = null;
InputStream is = null;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


    //button that saves the file from mySQL
    Button save = (Button) findViewById(R.id.downloadBtn);
    save.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            saveJson();             
        }
    });

    //Button that opens the file from InternalMemory
    Button open = (Button) findViewById(R.id.showBtn);
    open.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            openJson();             
        }
    });


//end of onCreate() 
}


//saveJson pull a JSON file from mySQl server then saves that file in its JSON type eg .json
public void saveJson(){
    TextView test = (TextView) findViewById(R.id.showView);


    try{
        //connects to mySQL
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://10.0.2.2/textures_story_list.php");
        HttpResponse response = client.execute(post);
        //captures the response
        entity = response.getEntity();
    }catch(Exception e) {
         Log.e("log_tag", "Error in http connection "+e.toString());
    }
    try{
        is = entity.getContent();
        String FILENAME = "story.json";
        //gives file name
        FileOutputStream output = openFileOutput(FILENAME, MODE_WORLD_READABLE);
        //creates new StreamWriter
        OutputStreamWriter writer = new OutputStreamWriter(output);
        //writes json with file name story.json
        writer.write(is);
        writer.flush();
        //closes writer
        writer.close();

    }catch(Exception e) {
         Log.e("log_tag", "Error saving string "+e.toString());
    }

//end of saveJson()
}

private char[] Object(Object json2) {
    // TODO Auto-generated method stub
    return null;
}


public void openJson(){
    TextView test = (TextView) findViewById(R.id.showView);



    try{
        FileInputStream fileInput = openFileInput("story.json");

        BufferedReader inputReader = new BufferedReader(new InputStreamReader(fileInput, "UTF-8"), 8);
        StringBuilder strBuilder = new StringBuilder();
            String line = null;
            while ((line = inputReader.readLine()) != null) {
                strBuilder.append(line + "\n");
            }
            fileInput.close();
            storyObj = strBuilder.toString();

    }catch(IOException e){
         Log.e("log_tag", "Error building string "+e.toString());
    }

    try{
        JSONArray jArray = new JSONArray(storyObj);
        String storyNames = "";
        for(int i = 0;i<jArray.length();i++){
            storyNames += jArray.getJSONObject(i).getString("story_name") +"\n";
        }
        test.setText(storyNames);

    }catch(JSONException e) {
         Log.e("log_tag", "Error returning string "+e.toString());
    }
    return;
//and of openJson() 
}




//end of class body    
}

希望你能帮我解决这个问题,花了很长时间才让它发挥作用!

添加了鲍里斯的额外代码...这是我放置代码的地方吗?

    try{
        //connects to mySQL
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://10.0.2.2/textures_story_list.php");
        HttpResponse response = client.execute(post);
        //captures the response
        entity = response.getEntity();
        InputStream entityStream = entity.getcontent();
        StringBuilder entityStringBuilder = new StringBuilder();
        byte [] buffer = new byte[1024];
        int bytesReadCount;
        while ((bytesReadCount = entityStream(read(buffer)) > 0)) {
            entityStringBuilder.append(new String(buffer, 0, bytesReadCount));
        }
        String entityString = entityStringBuilder.toString();
        Integer responseInteger = Integer.valueOf(entityString);
    }catch(Exception e) {
         Log.e("log_tag", "Error in http connection "+e.toString());
    }

如果是的话我在读取时遇到错误


试试这个代码

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();
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 json 文件保存到内部存储器 的相关文章

随机推荐

  • List RemoveAll() 没有删除项目

    我有一个看起来像这样的对象 Text Another lovely alert Category 2 UserAlerts UserId 2 这将传递到 Web API 并正确绑定到 Key Column Order 0 public lo
  • SwiftUI @FetchRequest 使应用程序崩溃并返回错误

    我正在尝试使用 Xcode 11 在 SwiftUI 的 mac 应用程序中使用核心数据 我在创建项目时勾选了 使用核心数据 我还创建了实体 称为 VisitedCases 并使用编辑器创建 NSManagedObject 子类文件 我还将
  • F#:从另一个列表中过滤一个列表中找到的项目

    假设我有两个列表 let a 1 1000 let b 250 500 如何获取包含值 1 249 501 1000 的新列表 由于您的列表已排序 因此您可以使用此 非尾递归 函数在线性时间内解决此问题 let rec except a b
  • Specs2 - 标记要运行的测试

    我已经使用 ScalaTest 一段时间了 我发现标记测试并从命令行仅运行具有特定标记的测试的功能非常有用 Specs2中有类似的东西吗 我知道您可以使用 testOnly 运行特定的测试类 但我只想使用规范中的特定标签运行测试 操作方法如
  • 如何在 CSS 中使用 :not 选择器?

    我的问题说明了一切 我是 CSS 新手 我正在尝试使用以下代码 但它不起作用 ul verticalNav declaration ul verticalNav li declaration ul verticalNav li a decl
  • AppCompat PreferenceActivity 向上按钮不起作用

    我正在尝试创建一个扩展 AppCompatPreferenceActivity 并在操作栏中实现向上按钮的活动 视觉上一切看起来都很好 但向上按钮不响应触摸事件 以下是我的java和xml代码 PrefrencesDisplayActivi
  • aChartEngine、GraphicalView OnClickListener 不起作用

    我是 android 新手 正在使用 aChartEngine 创建条形图 我想在用户单击图表时捕获 x 和 y 值 我已经查看了 aChartEngine 的演示 并且我的图表创建得很好 但是 当我单击图形时 onClickListner
  • 当 eventDrop 被调用时,如何发送 ajax 请求来更新 FullCalendar UI 中的事件?

    我正在尝试使用这个很棒的用户界面 全日历 但我想做的是 当用户移动事件时 发送一个 ajax 请求来更新数据库中的事件数据 因此 如果用户想要将事件移至日历中的不同日期 那么我需要能够使用 ajax 请求将请求发送到数据库 我如何收集新信息
  • 用户输入创建对象

    我正在尝试创建一个使用用户输入的新对象 我尝试将用户输入分配给变量但是不知道如何添加变量当我声明新对象时到新对象 这只是我需要帮助的代码部分 我需要帮助的部分是line 8 我知道我可以随机放置一些东西 当我使用我的设置方法时 它会覆盖 但
  • 从 Amazon MySQL RDS 本地导入转储时 MySQL 语法错误?

    当我从 Amazon RDS 创建数据库转储然后尝试将其导入本地时 结果是ERROR 1064 42000 at line 54 第 54 行有如下语句 CREATE TABLE account emailconfirmation 用于转储
  • 查找未加权无向图中两个节点之间的所有最短路径

    我需要帮助找到一个节点中两个节点之间的所有最短路径未加权无向图 我能够使用 BFS 找到最短路径之一 但到目前为止我不知道如何找到并打印所有路径 对我可以使用的算法 伪代码有什么想法吗 需要注意的是 请记住 图中两个节点之间的最短路径可能呈
  • 启动 Hbase:cygpath:无法转换空路径

    我希望有人能帮助我解决这个问题 启动 hbase 时出现此错误 start hbase sh cygpath can t convert empty path cygpath can t convert empty path soporte
  • iOS:仅绘制 UImage 的一部分

    我正在尝试仅绘制一个自定义部分UIImage 即 我想reveal的部分UIImage用户触摸 并且我通过使用得到了合理的结果mask的财产layer 我的身上有这样的东西UIView UIBezierPath maskPath UIBez
  • 一个 NFC 标签上有 2 条 NDEF 消息/记录 - Android

    有人尝试过Android默认行为如何 当NFC标签上保存2个NDEF记录时 一个指向带有应用程序 apk的URL 而第二个具有应用程序专有数据 用例如下 当用户尚未安装应用程序时 设备启动 Google Play 或网络浏览器 并且用户可以
  • 如何使用 Spring Boot 监听动态目的地?

    我们有一个使用 Spring Boot 及其 JMS 工具的应用程序 在运行时 我们有不同的生产者在线跳转并告诉我们的应用程序要侦听的主题或队列的名称 现在 我们有 JmsListener destination helloworld q
  • MATLAB中如何删除矩阵中的零?

    这是我的问题 我有一个nxnmatlab中的矩阵 我想删除这个矩阵的所有零并将其行放入向量中 为了n 4 假设我有以下矩阵 A 1 1 0 0 1 2 0 0 1 0 0 0 1 2 1 0 如何获得以下内容 v1 1 1 v2 1 2 v
  • 在目录中查找文件

    我有一个目录 里面有很多文件 pic 1 79879879879879879 jpg pic 1 89798798789798789 jpg pic 1 45646545646545646 jpg pic 2 123456782131456
  • session_start(): open(SESSION_FILE, O_RDWR) 失败:没有这样的文件或目录 (2) session_start():

    我已将 php 版本从 PHP 7 升级到 PHP 7 1 之后我无法打开 phpmyadmin 我收到以下错误 会话启动期间出错 请检查您的 PHP 和 或网络服务器日志文件并正确配置您的 PHP 安装 还要确保您的浏览器中启用了 coo
  • 检查类是否有某个键的值

    我知道您可以使用设置基础类的属性setValue value forKey key 但是如何检查一个类是否有某个键的值呢 Swift3的版本Raymond的回应 extension NSObject func safeValue forKe
  • 将 json 文件保存到内部存储器

    嘿 伙计们 女孩们 我有这段代码 应该下载一个 json 对象 然后将其保存到内存中 我一直卡在这里 try connects to mySQL HttpClient client new DefaultHttpClient HttpPos