|
AndroidJsonList
Android Json to ListActivities with Images
Tooltips Old example, edited in 2009... /** * Fetch JSON object from distant server (Generated by PHP) * Parse JSON stream * Get Image ressource from Internet * Print List with Icones **/ src/myGuide.java
package com.example.augmentedTV;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
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.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Fetch JSON object from distant server (Generated by PHP) Parse JSON stream
* Get Image ressource from Internet Print List with Icones
**/
public class myGuide extends ListActivity {
private static final String LOG_TAG = "myGuide";
private static final String SITE_URL = "http://www.XXX.net/mobile/";
public static HashMap<Integer, JSONObject> channelMap;
public static HashMap<Integer, Bitmap> iconsMap;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getEmissions();
setListAdapter(new EfficientAdapter(this));
}
public void getEmissions() {
channelMap = new HashMap<Integer, JSONObject>();
iconsMap = new HashMap<Integer, Bitmap>();
try {
/*
* JSON string provided by PHP { 1: { id: "14", titre: "France 2",
* emission: "La légende de Santa Senara", debut: "14h50", fin:
* "16h35", icone: http://www.XXX.net/tv/images/france2.gif }, ... }
*/
JSONObject jsonChannels = getHttpJson(SITE_URL + "?action=channel");
JSONArray nameArray = jsonChannels.names();
JSONArray valArray = jsonChannels.toJSONArray(nameArray);
for (int i = 0; i < valArray.length(); i++) {
int myChannelNumber = nameArray.getInt(i);
JSONObject myChannel = valArray.getJSONObject(i);
URL myFileUrl = null;
try {
myFileUrl = new URL(myChannel.getString("icone"));
} catch (MalformedURLException e) {
Log.e(LOG_TAG,
"getView() There was a malformed url based error",
e);
}
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
Bitmap bitmap = BitmapFactory.decodeStream(conn
.getInputStream());
conn.disconnect();
iconsMap.put(myChannelNumber, bitmap);
} catch (IOException e) {
Log
.e(
LOG_TAG,
"getView() There was a url access to image based error",
e);
}
channelMap.put(myChannelNumber, myChannel);
}
} catch (JSONException e) {
Log.e(LOG_TAG, "There was a Json parsing based error", e);
}
}
private static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return channelMap.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item_icon_text,
null);
holder = new ViewHolder();
holder.titre = (TextView) convertView.findViewById(R.id.titre);
holder.soustitre = (TextView) convertView
.findViewById(R.id.soustitre);
holder.icon = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (channelMap.containsKey((position + 1)) == true) {
try {
JSONObject obj = (JSONObject) channelMap
.get((position + 1));
holder.titre.setText(obj.getString("titre") + " de "
+ obj.getString("debut") + " à "
+ obj.getString("fin"));
holder.soustitre.setText(obj.getString("emission"));
if (iconsMap.containsKey((position + 1)) == true)
holder.icon
.setImageBitmap(iconsMap.get((position + 1)));
} catch (JSONException e) {
Log
.e(
LOG_TAG,
"getView() There was a Json parsing based error",
e);
}
}
return convertView;
}
static class ViewHolder {
TextView titre;
TextView soustitre;
ImageView icon;
}
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public JSONObject getHttpJson(String url) {
JSONObject json = null;
String result = getHttp(url);
try {
json = new JSONObject(result);
} catch (JSONException e) {
Log.e(LOG_TAG, "There was a Json parsing based error", e);
}
return json;
}
public String getHttp(String url) {
Log.d(LOG_TAG, "getHttp : " + url);
String result = "";
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response;
try {
response = httpclient.execute(httpget);
// Log.i(LOG_TAG, response.getStatusLine().toString());
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
result = convertStreamToString(instream);
Log.i(LOG_TAG, result);
instream.close();
}
} catch (ClientProtocolException e) {
Log.e(LOG_TAG, "There was a protocol based error", e);
} catch (IOException e) {
Log.e(LOG_TAG, "There was an IO Stream related error", e);
}
return result;
}
}
res/layout/list_item_icon_text.xml<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="0dip">
<ImageView
android:id="@+id/icon"
android:layout_width="48dip"
android:layout_height="48dip"
android:layout_marginRight="6dip" />
<TextView
android:id="@+id/titre"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/icon"
android:gravity="center_vertical"
android:singleLine="true"
android:ellipsize="marquee"
style="@style/titreList" />
<TextView
android:id="@+id/soustitre"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/titre"
android:layout_toRightOf="@id/icon"
android:gravity="center_vertical"
android:singleLine="true"
android:ellipsize="marquee"
android:textAppearance="?android:attr/textAppearanceLarge"
style="@style/textList" />
</RelativeLayout>res/values/styles.xml<?xml version="1.0" encoding="utf-8"?> <resources> <style name="bytelTheme" parent="android:style/Theme.Light.NoTitleBar"> <item name="android:windowNoTitle">true</item> <item name="android:windowBackground">@drawable/bg</item> </style> <style name="titreList"> <item name="android:textSize">14px</item> <item name="android:textColor">#999999</item> </style> <style name="textList"> <item name="android:textSize">16px</item> <item name="android:textStyle">bold</item> <item name="android:textColor">#666666</item> </style> <style name="textList2"> <item name="android:textSize">12px</item> <item name="android:textColor">#999999</item> </style> </resources> manifest.xml<activity android:name="initTV" android:label="@string/app_name" android:theme="@style/bytelTheme"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> | |
► Sign in to add a comment
this program is not running its give 1/ There was a Json parsing based error 2/ org.json.JSONException: A JSONObject text must begin with '{' at character 1 of <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> 3/at org.json.JSONTokener.syntaxError(JSONTokener.java:448)
Hello,
Sorry, i don't provide the JSON here, but this is provided by PHP, on the server side.
It's look like :
{ 1:{id:"10", name:"toto"}, 2:{id:"11", name:"tutu"} }I m getting null value in this line. JSONArray nameArray = jsonChannels.names(); what will the JSON object return? Waiting for ur sugesstion.
"There was an IO Stream related error" why messege where messege?
Sorry guy, this is a old file i made in 2009 Finally i'm always in love with jQuery ;)
jQuery(function() { $.ajax({ dataType: 'jsonp', url: 'http://jsfiddle.net/api/user/molokoloco/demo/list.json', data: {sort:'date', start:0, limit:10}, success: function (data) { if (!data || !data.list) return $('div.widget_fiffle').remove(); $.template('fiddleTpl', '<li><a title="${description}" href="${url}" class="rsswidget" target="_blank">${title}</a> <span class="rss-date">${getDateTo()}</span></li>'); $.tmpl('fiddleTpl', data.list).appendTo('ul#fiddlesList'); } }); });