试图从MySQL下载JSON [英] trying to download JSON from mySQL

查看:90
本文介绍了试图从MySQL下载JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿家伙和女孩,IV一直在努力解决这个问题,现在周carnt似乎得到任何帮助,我想code,从我的服务器下载一个JSON文件,并将其保存到内部存储器在saveJSON(),然后用showJSON()应该显示保存的JSON文件,然后去code将其以纯文本。我得到的问题是各地的Htt presponse和下一行,还林不知道它在下一节中还写它应该保存JSON文件。这里有两个误区即时得到

 错误的HTTP连接产生java.net.SocketException:权限被拒绝

 错误节省串null.pointer

任何帮助将大大AP preciated

 公共类MainActivity延伸活动{串storyObj =;
JSON对象= NULL;
HttpEntity实体= NULL;
@覆盖
公共无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.main);
    //按钮保存从MySQL文件
    按钮保存=(按钮)findViewById(R.id.downloadBtn);
    save.setOnClickListener(新View.OnClickListener(){        @覆盖
        公共无效的onClick(视图v){
            saveJson();
        }
    });    //打开从InternalMemory文件按钮
    按钮打开=(按钮)findViewById(R.id.showBtn);
    open.setOnClickListener(新View.OnClickListener(){        @覆盖
        公共无效的onClick(视图v){
            openJson();
        }
    });
//的onCreate结束()
}
// saveJson拉从MySQL服务器的JSON文件,然后保存该文件在其JSON类型如以.json
公共无效saveJson(){
    TextView的测试=(的TextView)findViewById(R.id.showView);
    尝试{
        //连接到MySQL
        HttpClient的客户端=新DefaultHttpClient();
        HttpPost后=新HttpPost(http://10.0.2.2/textures_story_list.php);
        HTT presponse响应= client.execute(岗位);
        //捕获响应
        实体= response.getEntity();    }赶上(例外五){
         Log.e(log_tag,在HTTP连接错误+ e.toString());
    }
    尝试{
        JSON对象实体=;
        字符串文件名=story.json;
        //给文件名
        FileOutputStream中输出= openFileOutput(文件名,MODE_WORLD_READABLE);
        //创建新的StreamWriter
        OutputStreamWriter作家=新OutputStreamWriter(输出);
        //使用文件名story.json写入JSON
        writer.write((整数)JSON);
        writer.flush();
        //关闭作家
        writer.close();    }赶上(例外五){
         Log.e(log_tag,错误保存字符串+ e.toString());
    }// saveJson结束()
}私人的char []对象(​​对象json2){
    // TODO自动生成方法存根
    返回null;
}
公共无效openJson(){
    TextView的测试=(的TextView)findViewById(R.id.showView);    尝试{
        的FileInputStream的FileInput = openFileInput(story.json);        的BufferedReader inputReader =新的BufferedReader(新的InputStreamReader(的FileInput,UTF-8),8);
        StringBuilder的strBuilder =新的StringBuilder();
            串线= NULL;
            而((行= inputReader.readLine())!= NULL){
                strBuilder.append(行+\\ n);
            }
            fileInput.close();
            storyObj = strBuilder.toString();    }赶上(IOException异常五){
         Log.e(log_tag,错误建筑物字符串+ e.toString());
    }    尝试{
        JSONArray jArray =新JSONArray(storyObj);
        串storyNames =;
        的for(int i = 0; I< jArray.length();我++){
            storyNames + = jArray.getJSONObject(ⅰ).getString(story_name)+\\ N的;
        }
        test.setText(storyNames);    }赶上(JSONException E){
         Log.e(log_tag,错误返回字符串+ e.toString());
    }
    返回;
//和openJson的()
}
//类体结束
}

和这里是我的XML清单

 <?XML版本=1.0编码=UTF-8&GT?;
<清单的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
包=com.game
安卓版code =1
机器人:=的versionName1.0><采用-SDK安卓的minSdkVersion =8/><用户许可权
    机器人:名字=android.permission.INTERNET对/>
<用户许可权的android:NAME =android.permission.SET_DEBUG_APP/><应用
    机器人:图标=@绘制/ ic_launcher
    机器人:标签=@字符串/ APP_NAME
     机器人:可调试=真正的>    <活动
        机器人:名字=。MainActivity
        机器人:标签=@字符串/ APP_NAME>
        &所述;意图滤光器>
            <作用机器人:名字=android.intent.action.MAIN/>            <类机器人:名字=android.intent.category.LAUNCHER/>
        &所述; /意图滤光器>
    < /活性GT;< /用途>< /清单>


解决方案

如果这真的是你的清单文件,错误是显而易见的.The标签不应该是使用[R] S-许可,但使用许可权

 <使用许可权
    机器人:名字=android.permission.INTERNET对/>
<使用许可权的android:NAME =android.permission.SET_DEBUG_APP/>

现在你就不能访问互联网,从而错误。如果您切换到使用像Eclipse的IDE,并使用自动完成你会避免这样的错误,从一开始,但是而且IDE将强调这是错误的警告。

修改:关于你的错误 - 你想直接投响应的实体为整数。这将始终失败,因为Integer是不是 HttpEntity 的超类。你需要阅读的实体的内容在字符串,然后解析字符串的内容到整数:

 的InputStream entityStream = entity.getcontent();
StringBuilder的entityStringBuilder =新的StringBuilder();
字节[]缓冲区=新的字节[1024];
INT bytesReadCount;
而((bytesReadCount = entityStream.read(缓冲液))大于0){
    entityStringBuilder.append(新的String(缓冲,0,bytesReadCount));
}
串entityString = entityStringBuilder.toString();
整数responseInteger = Integer.valueOf(entityString);

这是没有经过高度优化,但做这项工作。从那时起,只要你喜欢,你可以使用 responseInteger 值。但是,如果你想要做的 writer.write 则需要字符串价值,而不是整数。因此,我建议你使用 entityString

hey there guys and girls, iv been trying to fix this problem for weeks now and carnt seem to get any help, i want the code to download a JSON file from my server and the save it to internal memory with the saveJSON() and then with the showJSON() it should display the saved JSON file and then decode it to plain text. the problems i get are around HttpResponse and the next line and also im not sure it the next section is also write where it should save the JSON file. here are the two errors im getting

Error in http connection java.net.SocketException: Permission denied 

and

Error saving string null.pointer

any help would be greatly appreciated

    public class MainActivity extends Activity {

String storyObj = "";
Object json = null;
HttpEntity entity = 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{
        Object json = entity;
        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((Integer) json);
        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    
}

and here is my xml manifest

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.game"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="8" />

<users-permission
    android:name="android.permission.INTERNET"  />
<users-permission   android:name="android.permission.SET_DEBUG_APP" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" 
     android:debuggable="true">

    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

</application>

</manifest>

解决方案

If this really is your Manifest file, the error is obvious .The tags should not be use[r]s-permission, but uses-permission:

<uses-permission
    android:name="android.permission.INTERNET"  />
<uses-permission   android:name="android.permission.SET_DEBUG_APP" />

Now you wouldn't have access to internet, and thus the error. If you switch to using an IDE like Eclipse and use autocomplete you will avoid such errors from the very beginning, but furthermore the IDE will underline this mistakes as warnings.

EDIT: 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:

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);

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.

这篇关于试图从MySQL下载JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆