Tag Archives: android

JSONArray and JSONObject Android

Having problems retrieving your data using java libraries JSONObject?
I am not surprised because its not so easy. This example will help you:

/* – here is an example JSON object from a URL (guardian API)
{
“response”:{
“status”:”ok”,
“userTier”:”free”,
“total”:1361206,
“startIndex”:1,
“pageSize”:10,
“currentPage”:1,
“pages”:136121,
“orderBy”:”newest”,
“results”:[{
“id”:”world/2011/aug/03/hosni-mubarak-way-trial”,
“sectionId”:”world”,
“sectionName”:”World news”,
“webPublicationDate”:”2011-08-03T07:11:00+01:00″,
“webTitle”:”Hosni Mubarak on way to face trial, says Egyptian official”,
“webUrl”:”http://www.guardian.co.uk/world/2011/aug/03/hosni-mubarak-way-trial”,
“apiUrl”:”http://content.guardianapis.com/world/2011/aug/03/hosni-mubarak-way-trial”
},{
“id”:”public-leaders-network/2011/aug/03/pfi-promises-rhetoric-reality”,
“sectionId”:”public-leaders-network”,
“sectionName”:”Public Leaders Network”,
“webPublicationDate”:”2011-08-03T07:00:04+01:00″,
“webTitle”:”PFI promises are more rhetoric than reality”,
“webUrl”:”http://www.guardian.co.uk/public-leaders-network/2011/aug/03/pfi-promises-rhetoric-reality”,
“apiUrl”:”http://content.guardianapis.com/public-leaders-network/2011/aug/03/pfi-promises-rhetoric-reality”
},{
“id”:”money/2011/aug/03/home-rental-costs-hit-record-highs”,
“sectionId”:”money”,
“sectionName”:”Money”,
“webPublicationDate”:”2011-08-03T07:00:03+01:00″,
“webTitle”:”Rents soar to record levels”,
“webUrl”:”http://www.guardian.co.uk/money/2011/aug/03/home-rental-costs-hit-record-highs”,
“apiUrl”:”http://content.guardianapis.com/money/2011/aug/03/home-rental-costs-hit-record-highs”
},{
“id”:”global-development/poverty-matters/2011/aug/03/africa-drought-uganda-no-somalia”,
“sectionId”:”global-development”,
“sectionName”:”Global development”,
“webPublicationDate”:”2011-08-03T07:00:02+01:00″,
“webTitle”:”East Africa drought: Uganda has problems, but it is no Somalia | Ben Jones”,
“webUrl”:”http://www.guardian.co.uk/global-development/poverty-matters/2011/aug/03/africa-drought-uganda-no-somalia”,
“apiUrl”:”http://content.guardianapis.com/global-development/poverty-matters/2011/aug/03/africa-drought-uganda-no-somalia”
},{
“id”:”money/2011/aug/03/virginia-wallis-redemption-charges”,
“sectionId”:”money”,
“sectionName”:”Money”,
“webPublicationDate”:”2011-08-03T07:00:01+01:00″,
“webTitle”:”Angry and confused over change in mortgage redemption charges”,
“webUrl”:”http://www.guardian.co.uk/money/2011/aug/03/virginia-wallis-redemption-charges”,
“apiUrl”:”http://content.guardianapis.com/money/2011/aug/03/virginia-wallis-redemption-charges”
},{
“id”:”money/2011/aug/03/virginia-wallis-house-flats-mortgage”,
“sectionId”:”money”,
“sectionName”:”Money”,
“webPublicationDate”:”2011-08-03T07:00:00+01:00″,
“webTitle”:”I want to convert flats back into a single house \u2013 what mortgage should I go for?”,
“webUrl”:”http://www.guardian.co.uk/money/2011/aug/03/virginia-wallis-house-flats-mortgage”,
“apiUrl”:”http://content.guardianapis.com/money/2011/aug/03/virginia-wallis-house-flats-mortgage”
},{
“id”:”world/2011/aug/03/china-calls-us-debt-manage”,
“sectionId”:”world”,
“sectionName”:”World news”,
“webPublicationDate”:”2011-08-03T06:45:36+01:00″,
“webTitle”:”China calls on US to manage its debt ‘responsibly’ from now on”,
“webUrl”:”http://www.guardian.co.uk/world/2011/aug/03/china-calls-us-debt-manage”,
“apiUrl”:”http://content.guardianapis.com/world/2011/aug/03/china-calls-us-debt-manage”
},{
“id”:”technology/blog/2011/aug/03/google-sergey-brin-2000-tv-show”,
“sectionId”:”technology”,
“sectionName”:”Technology”,
“webPublicationDate”:”2011-08-03T06:40:00+01:00″,
“webTitle”:”It’s 2000: can you spot the real Sergey Brin on the quizshow?”,
“webUrl”:”http://www.guardian.co.uk/technology/blog/2011/aug/03/google-sergey-brin-2000-tv-show”,
“apiUrl”:”http://content.guardianapis.com/technology/blog/2011/aug/03/google-sergey-brin-2000-tv-show”
},{
“id”:”environment/2011/aug/03/garden-birds-avian-pox-virus”,
“sectionId”:”environment”,
“sectionName”:”Environment”,
“webPublicationDate”:”2011-08-03T06:00:02+01:00″,
“webTitle”:”UK garden birds hit by avian pox virus”,
“webUrl”:”http://www.guardian.co.uk/environment/2011/aug/03/garden-birds-avian-pox-virus”,
“apiUrl”:”http://content.guardianapis.com/environment/2011/aug/03/garden-birds-avian-pox-virus”
},{
“id”:”voluntary-sector-network/2011/aug/03/charity-sector-management-recruitments”,
“sectionId”:”voluntary-sector-network”,
“sectionName”:”Voluntary Sector Network”,
“webPublicationDate”:”2011-08-03T06:00:02+01:00″,
“webTitle”:”Demand for interim managers in charity sector remains high, says recruitment specialist”,
“webUrl”:”http://www.guardian.co.uk/voluntary-sector-network/2011/aug/03/charity-sector-management-recruitments”,
“apiUrl”:”http://content.guardianapis.com/voluntary-sector-network/2011/aug/03/charity-sector-management-recruitments”
}] }}
*/

// retrieve your JSON somehow, I am using URLConnection. If you want the whole code email me.
URL twitter = new URL(“http://content.guardianapis.com/search?format=json”);
URLConnection tc = twitter.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));

//. put your JSON into a string:
StringBuilder sb = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
sb.append(line + “\n”);
}
// here is what you probably want most – its not so damn obvious. I got there by ‘trial and error’ 🙂
JSONObject jObject2 = new JSONObject(sb.toString());
JSONObject menuObject2 = jObject2.getJSONObject(“response”);
String attributeId12 = menuObject2.getString(“status”);
System.out.println(“value == ” +attributeId12);
String attributeId22 = menuObject2.getString(“userTier”);
System.out.println(“value == ” +attributeId22);
String attribute3 = menuObject2.getString(“results”);
System.out.println(“value == ” +attribute3);
JSONArray ja4 = jObject2.getJSONObject(“response”).getJSONArray(“results”);
System.out.println(“sub1_att = ” + ja4.getJSONObject(0).getString(“sectionId”).toString()+”\n\n”);
System.out.println(“sub1_att = ” + ja4.getJSONObject(0).getString(“sectionName”).toString()+”\n\n”);
for (int i=0;i<ja4.length();i++){
System.out.println("length = " + ja4.getJSONObject(i).getString("sectionName").toString()+"\n\n");
}

All the best with this JSONObject library. It does work but needs careful coding.
‘Like me’ if you appreciated this pls.

Advertisements

Android Graphics & Applications

Feel free to help yourself – I am not claiming any copyright on these images.
Android on a Wall

Radioactive Android

Through-the-Glass Android

Night-Time Android

Friendly Android

Alpha Cut-Out Android

Android NDK

Write c through the java jni (java native interface).

Below is a file write example using native c.

#include
#include
#include

jstring
Java_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env,
jobject thiz )
{
FILE* file = fopen(“textexample”,”w+”);

if (file != NULL)
{
fputs(“text example!\n”, file);
fflush(file);
fclose(file);
}

return (*env)->NewStringUTF(env, “JNI (with file io)!”);
}

The java activity to drive this c interface is:

package com.example.hellojni;

import android.app.Activity;
import android.widget.TextView;
import android.os.Bundle;

public class HelloJni extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText( stringFromJNI() );
setContentView(tv);
}
public native String stringFromJNI();
public native String unimplementedStringFromJNI();
static {
System.loadLibrary(“hello-jni”);
}
}

The android.mk file is:

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE := hello-jni
LOCAL_SRC_FILES := hello-jni.c

include $(BUILD_SHARED_LIBRARY)

Android ASE and Python

My phone is a Nexus One Froyo but these scripts will run on most phones (time of writing this: 14 July 2010).

ASE is a way of running python scripts on an Android phone. Its very easy to set it up (http://code.google.com/p/android-scripting/ – just download the python apk – it installs like an ordinary App) and the libraries have twitter and json already there. You can edit on the phone itself.

My phone is a Nexus One Froyo but these scripts will run on most phones.

Script 1 (as simple as you can get!)
*****************

print “python test”

*****************

Script 2 (make Toast label thingy)
*****************

import android
droid = android.Android()
droid.makeToast(‘Hello, Android!’)

******************

Script 3 (alert dialogue)
*****************

import android
droid = android.Android()
droid.dialogCreateAlert(‘my title’, ‘my message bla bla’)
droid.dialogShow()

******************

Script 4 (post a twitter update, libraries already there)
******************

import android
import twitter
droid = android.Android()
twitter_name = droid.getInput(”,’Twitter name?’).result
twitter_password = droid.getInput(”,’Twitter password?’).result
twitter_update = droid.getInput(”,’Update message?’).result
t = twitter.Api(username=twitter_name, password=twitter_password)
update = t.PostUpdate(twitter_update)
print update.text
#print twitter_password
#print twitter_update
print ‘ \n\n done it ‘

*************************

Script 5 (posts to twitter your phone location)
***********************

import android
import twitter

droid = android.Android()
# Login to twitter account.
twitter_name = droid.getInput(”,’Twitter name?’).result
twitter_password = droid.getInput(”,’Twitter password?’).result
t = twitter.Api(username=twitter_name, password=twitter_password)
# get phones location data
location = droid.getLastKnownLocation().result
# print a bit of interesting data
print str(location.keys())
print ‘latitude is ‘ + str(location.values()[0][‘latitude’])
print ‘longitude is ‘ + str(location.values()[0][‘longitude’])
# update twitter
update = t.PostUpdate(‘My location is: http://maps.google.com/maps?q=’+str(location.values()%5B0%5D%5B‘latitude’%5D)+&#8217;,’+str(location.values()[0][‘longitude’])+”)
# if no errors this will print
print ‘\n\nDone it’
droid.makeToast(‘done it’)

**************************

Script 5 (speaks text)
*************************

import android

droid = android.Android()
say_it = droid.getInput(”,’Say what?’).result
if say_it:
droid.ttsSpeak(say_it)
else:
droid.ttsSpeak(‘You forgot to enter something in the previous text box.’)

********************************

Script 6 (sends an email, user must confirm)
********************************

import android

recipientAddress = ‘blabla@gmail.com’
subject = ‘test from android’
body = ‘testing…’
droid = android.Android()
droid.sendEmail(recipientAddress,subject,body)

*******************************

Script 7 (takes photo and puts in gallery folder)
*******************************

import android

droid = android.Android()
fileName = droid.getInput(”,’Photo name?’).result
if fileName:
droid.cameraCapturePicture(‘/sdcard/DCIM/Camera/’ + fileName + ‘.jpg’)
else:
fileName = ‘billpic’
droid.cameraCapturePicture(‘/sdcard/DCIM/Camera/’ + fileName + ‘.jpg’)
print ‘you called it billpic’

print ‘you called it: ‘ + fileName

***********************************

ASE-scripts-screen

List of my scripts


ASE-scripts-screen-2

Shell command line


scanbarcode python or shell choice menu on the phone

scanbarcode gets smallish scripts that are in the 2D code!

Rodsit Infos



Android Applications, London, UK
<br

email: rodsit@gmail.com
Location: Google Maps: Edgware Rd, London

Based mainly in London.

Products

1) Android applications ready for market
2) Google App Engine as cloud platform for Android
3) Java, OpenGL, c++, c, python, linux, unix, Mac software solutions
4) Database design and implementations
5) Graphic designs for mobile
6) Blogs, photos, social media, films