阅读JSON的URL文件我的Andr​​oid手机上返回黑屏 [英] reading json url file returns blank screen on my Android phone

查看:299
本文介绍了阅读JSON的URL文件我的Andr​​oid手机上返回黑屏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的#2的第一篇文章,我努力学习的Andr​​oid。我需要从一个Android应用程序中读取一个JSON文件。

this is my first post on Stackoverflow and I am trying to learn Android. I need to read a json file from within an android application.

我跑我的手机上的以下code,它不会我的手机上显示什么,我只是得到一个空白屏幕。

I ran the following code on my phone and it doesn't display anything on my phone, I just get a blank screen.

我知道有很多方法可以使用​​Java库来解析JSON但是这不是我所期待的。我想完成阅读使用由Android提供的工具只是这个JSON。这里是我的JSON

I know there are ways to use Java libraries to parse json but that's is NOT what I am looking for. I would like to accomplish reading this json using ONLY tools provided by Android. Here's my json

我使用的是Android 4.0.3
这是我的JSON文件数据:

I am using Android 4.0.3 Here's my json file data:

{
    "offers": [
        {
                "id": "1",
                "type":"xyz",
                "description":"blah blah",
                "url":"http://www.example.com/"
        },
        {
                "id": "1",
                "type":"xyz",
                "description":"some description",
                "url":"http://www.example.com/"
        },
        {
                "id": "1",
                "type":"xyz",
                "description":"some description",
                "url":"http://www.example.com/"
        }
    ]
}

下面是我的MainActivity.java

Here's my MainActivity.java

package com.pega.parsejson;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    TextView jsonWrapper;
    HttpClient httpClient;
    JSONObject json;


    final static String offersUrl="http://somewebsite.com/offers.json";



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        jsonWrapper=(TextView) findViewById(R.id.jsonWrap);
        httpClient=new DefaultHttpClient();
        new Read().execute("description");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    public JSONObject jsonOffers() throws ClientProtocolException, IOException, JSONException {
        //StringBuilder url=new StringBuilder(offersUrl);

        HttpGet get=new HttpGet(offersUrl);
        HttpResponse res=httpClient.execute(get);
        int status=res.getStatusLine().getStatusCode();

        if(status==200){
            HttpEntity e=res.getEntity();
            String data=EntityUtils.toString(e);
            JSONArray timeline=new JSONArray("offers");
            JSONObject jsonOffer=timeline.getJSONObject(0); //returns most recent offer
            return jsonOffer;
        }else{
            Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
            return null;
        }

    }

    public class Read extends AsyncTask<String, Integer, String>{

        @Override
        protected String doInBackground(String... params) {
            try {
                json=jsonOffers();
                return (String) json.get("description"); //returns string w/ parameter passed in as "description"
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            jsonWrapper.setText(result);
        }

    }

}

我也使用互联网的权限:

I am also using the INTERNET PERMISSIONS:

下面是我的清单文件:

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.pega.parsejson.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>

和这里是我的TextView正确如下:

And here's my textview right below:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/jsonWrap"
        android:layout_width="match_parent"
        android:layout_height="400dp"
        android:text="" />

</RelativeLayout>

这是我的logcat的:

And here's my logcat:

[2013-08-07 23:35:41 - parseJson] ------------------------------
[2013-08-07 23:35:41 - parseJson] Android Launch!
[2013-08-07 23:35:41 - parseJson] adb is running normally.
[2013-08-07 23:35:41 - parseJson] Performing com.pega.parsejson.MainActivity activity launch
[2013-08-07 23:35:42 - parseJson] Uploading parseJson.apk onto device 'HT25EHX00690'
[2013-08-07 23:35:42 - parseJson] Installing parseJson.apk...
[2013-08-07 23:35:45 - parseJson] Success!
[2013-08-07 23:35:45 - parseJson] Starting activity com.pega.parsejson.MainActivity on device HT25EHX00690
[2013-08-07 23:35:46 - parseJson] ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.pega.parsejson/.MainActivity }

请注意我不希望使用任何JSON库解析的json,我严格想用仅适用于Android解析JSON。我只是不明白为什么我的mainActivity.java不显示在手机上任何东西。

Please note I do NOT want to use any json libraries to parse my json, I strictly would like to use ONLY android to parse the json. I just don't get why my mainActivity.java doesn't display anything on phone.

道歉帖子的长度,真的需要帮助的这一个时间敏感的项目,是的,我已经阅读并#1让利类似的问题似乎回答这个问题。

Apologize for the length of my post, really need help on this for a time sensitive project and YES, I have already read other similar questions on Stackoverflow and none seem to answer this question.

有谁请帮助我在这?

感谢

推荐答案

我相信你的错误就在于code:

I believe your error lies in the code:

HttpEntity e=res.getEntity();
String data=EntityUtils.toString(e);
JSONArray timeline=new JSONArray("offers");
JSONObject jsonOffer=timeline.getJSONObject(0); //returns most recent offer
return jsonOffer;

原因是,你正在创建一个新的JSONArray,而不是使用来自您收到JSON阵列。

The reason is that you are creating a NEW JSONArray instead of using the array from the JSON you receive.

相反,你应该分析收到的JSON,使用内置的JSONObject,然后选择阵列。假设数据持有的JSON文本,你可以这样做:

Instead, you should parse the JSON you receive, using the built-in JSONObject and then select the array. Assuming data holds the JSON text, you could do something like:

JSONObject json = new JSONObject(data);
JSONArray timeline = json.getJSONArray("offers");
return timeline.getJSONObject(0); // return most recent offer

这篇关于阅读JSON的URL文件我的Andr​​oid手机上返回黑屏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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