W

 

Image

Image

Image

Image

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.

Take care of laptop power charger adapters

Many notebook power adapters are made with cheap components these days. You may have noticed. Here is how to make them last longer

1) Do not bend the cables as they can break easily these days. I have taped cables to the charger body to prevent them waggling around too much. If you carry your adapter round in a laptop bag then give it lots of room and place it in your back carefully – as if it were made of glass.
2) Try not to let the adapter get too hot. Processor running full tilt and battery half charged will heat the charger up too much.
3) So, check charger does not get too hot and handle it VERY carefully.

These tips will give you extra time with your very fragile power adapter. All the best with it.🙂

Note: Looking forward to much needed advances in power adapter design. I suppose its not sexy enough😦

Java Thread wait and notify for Right Handed Thinkers

This code may be enough for you, but I will add a few words at the end. (note: if you use this code replace the WordPress ” with real ones)

*********************************
package com.multiple.threads;

public class Controller
{
public static void main(String[]args) throws InterruptedException
{
WorkingClass b1 =new WorkingClass();
Thread b = new Thread(b1);
b.start();
synchronized(b)
{
System.out.println(“1 Just about to call wait()” + b.getName());
b.wait();
System.out.println(“2 Just got notified”);}
System.out.println(“3 Ended here”);}}

class WorkingClass implements Runnable
{
public void run(){ synchronized (this){
System.out.println(“4 Starting a 4 sec sleep, nighty night.”);
try{ Thread.sleep(4000); }catch(Exception e){}
System.out.println(“5 Finished sleeping and calling notification”);
notify();
}}}
**********************************
output is:
1 Just about to call wait() Thread-0
4 Starting delay
5 Finished sleeping and calling notification
2 Just got notified
3 ended here

So, you have to synchronize your thread object and run() to get locks. Then the thread stops at the wait() stage and does nothing until notify() – after the task is finished. At which point it goes to the last stage in the program and finishes. – The task here is a 4 second sleep, but it could be getting data online.
Try it in your terminal window – it works.

Java Interfaces and Threads for Right Hand Thinkers

How can a java interface gain you access to methods in classes that implement the same interface?
How can a Thread use a start() method that is nowhere to be seen (its hiding in Thread).

To solve these convoluted issues I have written a Thready class that is similar to java.lang.Thread and a Runnabley interface that is similar to java.lang.Runnable but just 4 or 5 lines so that you can then see exactly how its all working. Its hard to explain in words without being an annoying geek.

So, here’s some code to look at and run at home.
Thread becomes Thready and Runnable becomes Runnabley. The users class is called FakeThread:

************************************************
package com.thready;

public class FakeThread implements Runnabley {

public static void main(String[] args){

// or Runnabley runnable = new FakeThread();
FakeThread runnable = new FakeThread();
Thready thready = new Thready(runnable);

// or Thready thready = new Thready(new FakeThread());
thready.start();
System.out.println(” running thread “+thready.getName());

}
public void run(){
System.out.println(” running dummy thread from FakeThread “);
}
}
********************************************************

Here is a fake Thready class (similar to the real Thread class)
******************************************
package com.thready;

public class Thready implements Runnabley {

private Runnabley target;

public Thready(Runnabley target){
this.target = target;
}

public void run() {
if (target != null) {
target.run();
}
System.out.println(” from run() in Thready but in this case NOT a real thread but a dummy one “);
}
public void start(){
System.out.println(” from start() in Thready class “);
run();
}
public final String getName() {
return “FredTheThread”;
}
}
*********************************

Here is Runnabley, similar to java.lang.Runnable:
**************************
package com.thready;

public interface Runnabley {

public abstract void run();

}
***********************************

If you want to do a real Thread and Runnable, then here is your tester class:
***********************************
package com.thready;

public class Test2 implements Runnable {

public static void main(String[] args){

Runnable runnable = new Test2();

Thread thread = new Thread(runnable);

thread.start();
System.out.println(” running thread “+thread.getName());

}

public void run(){
System.out.println(” running thread in run test2 class “);
}

}
***********************************************************

If you like words here are some: If your class implements an interface, then when you make an object it automatically becomes an object of the interface as well. Then all classes that implement the same interface can use each other’s methods if they want. See how we make a thread object that takes an interface in its constructor, pass it our class object and then we get access to methods in Thread. Run() in Thread runs because something in Thread tells it to run, – target.run() – not because it is overwritten.

Its best to play around with the code I have given you answering the questions:
1) How can run() in your class be called?
2) How is start() in Thread called?
3) If Thread had no constructor that took a Runnable, how would things change.

Like I said it IS convoluted, so all the best.

Answer to 3)
The class thread needs to call run() in our users class. Therefore it needs to know
the name of our user classes object so it can call it. That object gets into Thread via its constructor.
(I repeat its not overwriting the run() method, its actually being called form Thread.

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 File I/O & Language

Android file writing using a variety of paradigms. Note it is best to add a BufferedReader buffer size – or the default is 8K.

package com.readwriter;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Random;

public class CheckFileForRepeats2 {
OutputStream outputStream;
static ArrayList ar = new ArrayList();
static ArrayList br = new ArrayList();
String endOfVerb, endOfVerb_1, theAnswer;
private static String x;
static String newy;
public static void main(String[] args) {
CheckFileForRepeats2 neu = new CheckFileForRepeats2();
for(int i = 2;i<92316;i++){ // i must be 1 more than lines in file
x = neu.readLines("RepeatsCheck.txt",i);
if(ar.contains(x)){
System.out.println(" contain " + x);
}
ar.add(neu.findWord("RepeatsCheck.txt", x));
}

} // end of main
public static void writeIt(String sentence_to_write, String file) throws Exception {
OutputStream outputStream;
outputStream = new FileOutputStream("res/raw/"+file,true);
Writer writer = new OutputStreamWriter(outputStream);
try {
writer.write(sentence_to_write + "\n");
} catch (IOException e) {
}
try {
writer.close();
} catch (IOException e) {
}
} // end of writeIt method
String findWord(String file, String theWord){ // machtes theWord to one in
Random generator = new Random();
int numy = generator.nextInt(f_tot) + 1;
InputStream in = this.getResources().openRawResource(R.raw.wordlist);
InputStream in;
try{
in = new FileInputStream("/"+file); // on the effing c drive
} catch(Exception e) {
try {
in = new FileInputStream("/"+file);
} catch(Exception e2){ return "didntread_1"; }
}
StringBuffer inLine = new StringBuffer();
InputStreamReader isr = new InputStreamReader(in);
BufferedReader inRd = new BufferedReader(isr);
String text = "";
String one_line = "";
try {
int county = 0;
while ((text = inRd.readLine()) != null) {
county += 1;
if (text.equals(theWord)){
one_line = text;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
}
return one_line.toLowerCase().trim();
}

String getWord(String file, int f_tot){ // gets one random word
Random generator = new Random();
int numy = generator.nextInt(f_tot) + 1;
InputStream in;
try{
in = new FileInputStream("/"+file);
} catch(Exception e) {
try {
in = new FileInputStream("/"+file);
} catch(Exception e2){ return "didntread_1"; }
}
StringBuffer inLine = new StringBuffer();
InputStreamReader isr = new InputStreamReader(in);
BufferedReader inRd = new BufferedReader(isr);
String text = "";
String one_line = "";
try {
int county = 0;
while ((text = inRd.readLine()) != null) {
county += 1;
inLine.append(county + " " + text);
inLine.append("\n");
if (county==numy){
one_line = text + " " + String.valueOf(county);}
}
} catch (IOException e) {
// TODO Auto-generated catch block
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
}
return one_line.toLowerCase().trim();
}
String readLines(String file, int lineNumber){
;
InputStream in;
try{
in = new FileInputStream("/"+file); // on the effing c drive
} catch(Exception e) {
try {
in = new FileInputStream("/"+file);
} catch(Exception e2){ return "didntread_1"; }
}
StringBuffer inLine = new StringBuffer();
InputStreamReader isr = new InputStreamReader(in);
BufferedReader inRd = new BufferedReader(isr);
String text = "";
String one_line = "";
try {
int county = 0;
while ((text = inRd.readLine()) != null) {
county += 1;
if (lineNumber==county){
one_line = text;
}
}
} catch (IOException e) {
// TODO must handle this
}
try {
in.close();

} catch (IOException e) {
// TODO Auto-generated catch block
}
return one_line;
}

void writeIds(String ids) throws IOException{
try {
outputStream = new FileOutputStream("sdcard/Android/data/billtododo",true); // append is true
} catch (FileNotFoundException e) {
try{ // does not write 44 if it finds previous and writes
outputStream = new FileOutputStream("sdcard/billtododo");
} catch (IOException e2) { } }
Writer writer = new OutputStreamWriter(outputStream);
try {
writer.write("p"+ids);
} catch (IOException e) { }
writer.close();
}

private String readLines() throws FileNotFoundException{
String one_line2 = "";
InputStream in2;
try{
in2 = new FileInputStream("sdcard/Android/data/billtododo");
} catch(Exception e) {
try {
in2 = new FileInputStream("sdcard/billtododo");
} catch(Exception e2){ return "didntread_1"; }
}
InputStreamReader isr2 = new InputStreamReader(in2);
BufferedReader inRd2 = new BufferedReader(isr2);
String text2 = "";
try {
while ((text2 = inRd2.readLine()) != null) {
one_line2 = text2;
}
} catch (IOException e) {
return "didntread_3";
}
try {
in2.close();
} catch (IOException e) {
return "didntread_4";
}
return one_line2;
}

}

package com.umba;
command line🙂
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;

public class MakeFileRegGerunds {
OutputStream outputStream;
static ArrayList ar = new ArrayList();
String endOfVerb, endOfVerb_1, theAnswer;
private static String x;

public static void main(String[] args) {
MakeFileRegGerunds ma = new MakeFileRegGerunds();
System.out.println(ma.pastParticiple(“taste”)); // debugging
for(int i = 1;i<621;i++){ // i must be 1 more than lines in file, go thro whole file
x = ma.readLines("MakeFileRegSimplePast.txt",i);
System.out.println(ma.gerund(x));
}

}
String readLines(String file, int lineNumber){
Random generator = new Random();
int numy = generator.nextInt(f_tot) + 1;
InputStream in = this.getResources().openRawResource(R.raw.wordlist);
InputStream in;
try{
in = new FileInputStream("/"+file); // on the effing c drive
} catch(Exception e) {
try {
in = new FileInputStream("/"+file);
} catch(Exception e2){ return "didntread_1"; }
}
StringBuffer inLine = new StringBuffer();
InputStreamReader isr = new InputStreamReader(in);
BufferedReader inRd = new BufferedReader(isr);
String text = "";
String one_line = "";
try {
int county = 0;
while ((text = inRd.readLine()) != null) {
county += 1;
if (lineNumber==county){
// if(!text.equals("")){ // takes care of lines with no word?
one_line = text;
// }
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
}
try {
in.close();
// textview02.setText(one_line.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
}
return one_line.toLowerCase().trim();
}

// begin gerunds from regular verb

private String gerund(String verb_infinitive){
endOfVerb = verb_infinitive.substring(verb_infinitive.length()-1); // need this in cases
endOfVerb_1 = verb_infinitive.substring(verb_infinitive.length()-2,verb_infinitive.length()-1);
if(endOfVerb.equals("e")){
theAnswer = verb_infinitive.substring(0, verb_infinitive.length()-1) + "ing";

} else {
theAnswer = verb_infinitive + "ing";
}

if(endOfVerb.equals("t")){
if(endOfVerb_1.equals("a") || endOfVerb_1.equals("e")|| endOfVerb_1.equals("i")|| endOfVerb_1.equals("o")|| endOfVerb_1.equals("u")){
theAnswer = verb_infinitive + "ting";
} else {
theAnswer = verb_infinitive.substring(0, verb_infinitive.length()) + "ing";
} }

if(endOfVerb.equals("b")){
if(endOfVerb_1.equals("a") || endOfVerb_1.equals("e")|| endOfVerb_1.equals("i")|| endOfVerb_1.equals("o")|| endOfVerb_1.equals("u")){
theAnswer = verb_infinitive + "bing";
} else {
theAnswer = verb_infinitive.substring(0, verb_infinitive.length()) + "ing";
} }

if(endOfVerb.equals("g")){
if(endOfVerb_1.equals("a") || endOfVerb_1.equals("e")|| endOfVerb_1.equals("i")|| endOfVerb_1.equals("o")|| endOfVerb_1.equals("u")){
theAnswer = verb_infinitive + "ging";
} else {
theAnswer = verb_infinitive.substring(0, verb_infinitive.length()) + "ing";
} }

if(endOfVerb.equals("p")){
if(endOfVerb_1.equals("a") || endOfVerb_1.equals("e")|| endOfVerb_1.equals("i")|| endOfVerb_1.equals("o")|| endOfVerb_1.equals("u")){
theAnswer = verb_infinitive + "ping";
} else {
theAnswer = verb_infinitive.substring(0, verb_infinitive.length()) + "ing";
} }

// catch t ending weirdos
if(verb_infinitive.equals("cheat") || verb_infinitive.equals("float") ||
verb_infinitive.equals("greet") || verb_infinitive.equals("heat") ||
verb_infinitive.equals("sprout")|| verb_infinitive.equals("repeat") ||
verb_infinitive.equals("visit") || verb_infinitive.equals("treat") ||
verb_infinitive.equals("agree") || verb_infinitive.equals("suit") ){
theAnswer = verb_infinitive +"ing"; }

// catch m ending weirdos
if(verb_infinitive.equals("jam") || verb_infinitive.equals("program") ||
verb_infinitive.equals("hum") || verb_infinitive.equals("drum") ||
verb_infinitive.equals("dam") ){
theAnswer = verb_infinitive +"ming";
}

// weirdos ending in e
if(verb_infinitive.equals("agree") || verb_infinitive.equals("disagree") ||
verb_infinitive.equals("guarantee") || verb_infinitive.equals("lie") ||
verb_infinitive.equals("queue")|| verb_infinitive.equals("tie") ){
theAnswer = verb_infinitive +"ing";

}

// weirdos ending in p
if(verb_infinitive.equals("develop") || verb_infinitive.equals("heap") ||
verb_infinitive.equals("peep")){
theAnswer = verb_infinitive +"ing";
}

// weirdos ending in n
if(verb_infinitive.equals("ban") || verb_infinitive.equals("grin") || verb_infinitive.equals("man") || verb_infinitive.equals("plan") || verb_infinitive.equals("sin") ){
theAnswer = verb_infinitive +"ning";
}
// just weird
if(verb_infinitive.equals("stir") || verb_infinitive.equals("star")){
theAnswer = verb_infinitive +"ring";

}

if(verb_infinitive.equals("glue") ){
theAnswer = verb_infinitive +"ing";

}

return theAnswer;
} // end of method gerund
}