Ryusuke Fuda's Tech Blog

Softweare Enginier about Web, iOS, Android.

android RSS,API 取得

ajax みたいにURLからjson取得

itunesランキング APIを使用
https://itunes.apple.com/jp/rss/topsongs/limit=50/json

■ DefaultHttpClientを使ってURlからjsonデータをそのまま返すfunctionつくる
http://techbooster.org/android/application/1801/

    public String getRss() {
    	String data = "";
	    HttpClient httpClient = new DefaultHttpClient();
	    StringBuilder uri = new StringBuilder("https://itunes.apple.com/jp/rss/topsongs/limit=50/json");
	    HttpGet request = new HttpGet(uri.toString());
	    
	    HttpResponse httpResponse = null;
	    try {
	        httpResponse = httpClient.execute(request);
	    } catch (Exception e) {
	        return ("error" + e);
	    }
	    
	    int status = httpResponse.getStatusLine().getStatusCode();
	    if (HttpStatus.SC_OK == status) {
	        try {
	            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
	            httpResponse.getEntity().writeTo(outputStream);
	            data = outputStream.toString(); // JSONデータ
	            Log.d("HttpSampleActivity", "success: "+data);	
	        } catch (Exception e) {
	            Log.d("HttpSampleActivity", "Error" + e);
	        }
	    } else {
	        Log.d("HttpSampleActivity", "Status" + status);
	    }
	    return data;
    }

これをandroid4.xでメインスレッドで呼ぶと"NetworkOnMainThreadException"とエラー返ってくる。メインスレッドでDefaultHttpClientは実行できないのでこのgetRSS()はサブスレッドで実行しないといけない。
http://shirusu-ni-tarazu.hatenablog.jp/entry/2013/01/20/033030

■ 次にjsonをパースしてviewに渡すfunction作る
http://techbooster.jpn.org/andriod/application/1645/

    public void parsingJson(String data) {
        StringBuffer stringBuffer = new StringBuffer();
        try {
		JSONObject rootObject = new JSONObject(data);
		rootObject = rootObject.getJSONObject("feed");
		JSONArray rankingArray = rootObject.getJSONArray("entry");
		Log.d("dataArray", "array:" + rankingArray);
		for (int i = 0; i < rankingArray.length(); i++) {
			JSONObject jsonObject = rankingArray.getJSONObject(i);
			Log.d("JSONSampleActivity", jsonObject.getJSONObject("title").getString("label"));
				String title = jsonObject.getJSONObject("title").getString("label");
	           	stringBuffer.append(title + "\n");
		}
            TextView rankingView = new TextView(this);
            rankingView.setHorizontallyScrolling(true);
            rankingView.setText(stringBuffer);
            ScrollView scrollView = new ScrollView(this);
            scrollView = (ScrollView)findViewById(R.id.scrollview);
            scrollView.addView(rankingView);
            
            Log.d("here", "here");
		} catch (Exception e) {
			// TODO: handle exception
		}

引数はjsonのデータ。
サブスレッドから画面のviewはいじれないので、parsingJson()はメインスレッドで呼ばなきゃいけない。

■ onStartで実行
http://d.hatena.ne.jp/androidprogram/20100622/1277229166

   @Override
    protected void onStart() {
    	// TODO Auto-generated method stub
    	super.onStart();
        
        Thread thread = new Thread(new Runnable() {
		@Override
		public void run() {
        	jdata = getRss(); //ここで実行	グローバル変数jdata作っておく
	    }
	});
    	thread.start();
    	try {
	    thread.join();
  	} catch (InterruptedException e) {
	    e.printStackTrace();
            Log.d("HttpSampleActivity", "thread Error" + e);
	}
    	parsingJson(jdata); //json解析してviewに渡す関数実行
    }


参考)
http://techbooster.org/android/application/1801/
http://techbooster.jpn.org/andriod/application/1645/
http://d.hatena.ne.jp/androidprogram/20100622/1277229166
http://shirusu-ni-tarazu.hatenablog.jp/entry/2013/01/20/033030