为什么JSON解析器无法在Android上运行?

时间:2015-01-25 13:15:41

标签: java android json

我有一个下载YouTube JSON数据的应用。代码在桌面应用程序中完美运行,但不在android中(当尝试迭代时,列表为null)。这是我的代码,重要的是:

    public String DownloadJSONData(){
    BufferedReader reader = null;
    String webc = "";
    try{
        URL url = new URL("http://gdata.youtube.com/feeds/api/users/thecovery/uploads?v=2&alt=json");
        reader = new BufferedReader(new InputStreamReader(url.openStream()));
        StringBuffer buffer = new StringBuffer();
        int read;
        char[] chars = new char[1024];
        while((read = reader.read(chars)) != -1){
            buffer.append(chars,0,read);
        }
        webc = buffer.toString();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
                return webc;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    System.out.println(webc);
    return webc;
}
public void GetData() throws JSONException {
    JSONObject obj = new JSONObject(DownloadJSONData());
    JSONArray feed = obj.getJSONObject("feed").getJSONArray("entry");
    for(int i = 0; i < feed.length(); i++){
        EPISODE_NAME.add(feed.getJSONObject(i).getJSONObject("title").getString("$t"));
        EPISODE_LINK.add(feed.getJSONObject(i).getJSONArray("link").getJSONObject(0).getString("href"));
    }
    ListView episodes = (ListView) findViewById(R.id.episodeChooser);
    ArrayAdapter<String> episodesSource = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,EPISODE_NAME);
}

}

在onCreate方法中,我调用GetData()方法,并尝试将适配器设置为来自EPISODE_NAME ArrayList的ListView,但它是null。我还尝试在onCreate中设置方法之后的适配器,但没有运气。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

一切正常

在Manifest.xml中添加以下权限

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

<强> ManiActivity.java

public class MainActivity extends Activity {
private ListView listView;
private List<FeedsDTO> feedsList = new ArrayList<FeedsDTO>();
private FeedsDTO dto  = null;
private BackgroundThread backgroundThread;
private CustomAdapter customAdapter = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    listView = (ListView) findViewById(R.id.listview);
    backgroundThread = new BackgroundThread();
    backgroundThread.execute();
}
private void setListViewAdapter(){
    customAdapter = new CustomAdapter(this, R.layout.listitem, feedsList);
    listView.setAdapter(customAdapter);
}
private class BackgroundThread extends AsyncTask<Void, Void, String> {
    private ProgressDialog progressBar = null;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressBar = new ProgressDialog(MainActivity.this);
        progressBar.setCancelable(false);
        progressBar.show();

    }
    @Override
    protected String doInBackground(Void... params) {
        BufferedReader reader = null;
        String webc = "";
        try{
            URL url = new URL("http://gdata.youtube.com/feeds/api/users/thecovery/uploads?v=2&alt=json");
            reader = new BufferedReader(new InputStreamReader(url.openStream()));
            StringBuffer buffer = new StringBuffer();
            int read;
            char[] chars = new char[1024];
            while((read = reader.read(chars)) != -1){
                buffer.append(chars,0,read);
            }
            webc = buffer.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                    return webc;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println(webc);
        return webc;
    }
    @Override
    protected void onPostExecute(String result) {
        JSONObject obj;
        try {
            obj = new JSONObject(result);
            JSONArray feed = obj.getJSONObject("feed").getJSONArray("entry");
            Log.i("=======", "========="+feed.length());
            for(int i = 0; i < feed.length(); i++){
                dto = new FeedsDTO();
                dto.setName(feed.getJSONObject(i).getJSONObject("title").getString("$t"));
                dto.setLink(feed.getJSONObject(i).getJSONArray("link").getJSONObject(0).getString("href"));
                feedsList.add(dto);
                dto = null;
            }
            Log.i("=======LIst Size", "========="+feedsList.size());
            progressBar.dismiss();
            setListViewAdapter();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        super.onPostExecute(result);
    }
}

}

<强> CustomAdapter.java

public class CustomAdapter extends ArrayAdapter<FeedsDTO>{
private LayoutInflater inflater;
private int layoutID;
public CustomAdapter(Context cntx, int resource, List<FeedsDTO> objects) {
    super(cntx, resource, objects);
    this.inflater =(LayoutInflater) cntx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    this.layoutID = resource;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    try {
        ViewHolder holder = null;
        if (convertView == null) {
            convertView = inflater.inflate(layoutID, null);
            holder = new ViewHolder();
            holder.NameTV = (TextView) convertView.findViewById(R.id.textview);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        FeedsDTO feedsDTO = getItem(position);
        holder.NameTV.setText(feedsDTO.getName());

        feedsDTO = null;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return convertView;
}
private class ViewHolder{
    TextView NameTV;
}

}

<强> FeedsDTO.java

public class FeedsDTO {
private String name;
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getLink() {
    return link;
}
public void setLink(String link) {
    this.link = link;
}
private String link;
}

<强> listitem.xlm: -

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical" >

<TextView
    android:id="@+id/textview"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
</TextView>

我希望此代码能够完美运行

答案 1 :(得分:-2)

  

大多数应用包含允许用户使用的多种不同活动   执行不同的操作。活动是否是主要活动   当用户点击您的应用图标或其他图标时创建的内容   您的应用启动以响应用户操作(系统)的活动   通过调用onCreate()创建Activity的每个新实例   方法

     

您必须实现onCreate()方法才能执行基本应用程序   启动逻辑,应该只在整个生命周期中发生一次   活动。例如,你的onCreate()实现应该定义   用户界面并可能实例化一些类范围   变量

     

例如,下面的onCreate()方法示例显示了一些   为活动执行一些基本设置的代码,例如   声明用户界面(在XML布局文件中定义),定义   成员变量,并配置一些UI。

你基本上是左右混合的东西。首先在onCreate()中创建您的界面并在onStart()中执行逻辑。 你应该阅读android生命周期。 See here