android - JSON parsing with Java -
i created android app involving json parsing. when run application in emulator worked, when run in android phone outputs error "unfortunately has stopped".
this json class:
package com.example.uichandbook; import java.io.bufferedreader; import java.io.ioexception; import java.io.inputstreamreader; import java.net.httpurlconnection; import java.net.malformedurlexception; import java.net.url; import java.util.list; import org.apache.http.httpresponse; import org.apache.http.client.methods.httpget; import org.apache.http.impl.client.defaulthttpclient; import org.json.jsonarray; import org.json.jsonobject; import android.app.activity; import android.content.context; import android.content.intent; import android.graphics.paint; import android.net.connectivitymanager; import android.net.networkinfo; import android.os.bundle; import android.util.log; import android.view.gravity; import android.view.view; import android.widget.button; import android.widget.linearlayout; import android.widget.textview; import android.widget.toast; public class mainactivity extends activity { button b1; button copy; button search; int final_id = 0; int final_id2 = 0; int large1 = 0; int large2 = 0; int counter2; int counter1; string parse; // url make request private static string url = "http://lynda.byethost32.com/uichandbook/contents.json"; private static string url2 = "http://lynda.byethost32.com/uichandbook/sub_contents.json"; int id; databasehandler db = new databasehandler(this); // contacts jsonarray jsonarray contacts = null; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); if (detectconnection .checkinternetconnection(mainactivity.this) == true) { toast.maketext(mainactivity.this, "you have internet connection", toast.length_long) .show(); updates(); } databasehandler db = new databasehandler(this); list<data2> contacts = db.getallcontent(); (data2 cn : contacts) { linearlayout lnr = (linearlayout) findviewbyid(r.id.container); lnr.setpadding(1, 1, 1, 1); b1 = new button(this); linearlayout.layoutparams lp = new linearlayout.layoutparams(linearlayout.layoutparams.match_parent, linearlayout.layoutparams.wrap_content); // verbose! lp.weight = 1.0f; // critical. doesn't work without it. b1.setid(cn.getid()); final int _id = b1.getid(); b1.settext(cn.getcontentname()); lnr.addview(b1, lp); copy = ((button)findviewbyid(_id)); copy.setonclicklistener(new view.onclicklistener(){ public void onclick(view view){ intent intent = new intent(mainactivity.this, subcontent.class); intent.putextra("id", _id); startactivity(intent); } }); } db.close(); } public void getjson() { // creating json parser instance jsonparser jparser = new jsonparser(); // getting json string url jsonobject json = jparser.getjsonfromurl(url); try{ // create new http client defaulthttpclient defaultclient = new defaulthttpclient(); // setup request httpget httpgetrequest = new httpget(url); // execute request in client httpresponse httpresponse = defaultclient.execute(httpgetrequest); // grab response bufferedreader reader = new bufferedreader(new inputstreamreader(httpresponse.getentity().getcontent(), "utf-8")); string jsonreader = reader.readline(); // instantiate json object request response jsonobject jsonobject = new jsonobject(jsonreader); contacts = jsonobject.getjsonarray("tbl_content"); for(int = 0; < contacts.length(); i++){ jsonobject c = contacts.getjsonobject(i); log.d("contact", c.getstring("content_name")); log.d("contact", c.getstring("content")); log.d("contact", c.getstring("content_id")); log.d("contact", c.getstring("book_id")); databasehandler db = new databasehandler(this); db.addcontent(new data2(c.getint("content_id"), c.getstring("content_name"),c.getstring("content"),c.getint("book_id"))); } } catch(exception e){ // in production code handle errors , catch individual exceptions e.printstacktrace(); } } public void getjson2() { // creating json parser instance jsonparser jparser = new jsonparser(); // getting json string url jsonobject json = jparser.getjsonfromurl(url2); try{ // create new http client defaulthttpclient defaultclient = new defaulthttpclient(); // setup request httpget httpgetrequest = new httpget(url2); // execute request in client httpresponse httpresponse = defaultclient.execute(httpgetrequest); // grab response bufferedreader reader = new bufferedreader(new inputstreamreader(httpresponse.getentity().getcontent(), "utf-8")); string jsonreader = reader.readline(); // instantiate json object request response jsonobject jsonobject = new jsonobject(jsonreader); contacts = jsonobject.getjsonarray("subcontent"); for(int = 0; < contacts.length(); i++){ jsonobject c = contacts.getjsonobject(i); log.d("contact", c.getstring("subcontent_name")); log.d("contact", c.getstring("subcontent")); log.d("contact", c.getstring("subcontent_id")); log.d("contact", c.getstring("content_id")); databasehandler db = new databasehandler(this); db.subaddcontent(new data3(c.getint("subcontent_id"), c.getstring("subcontent_name"),c.getstring("subcontent"),c.getint("content_id"))); } } catch(exception e){ // in production code handle errors , catch individual exceptions e.printstacktrace(); } } final static string system_newline = "\n"; final static float complexity = 5.12f; //reducing increase effici ency decrease effectiveness final static paint p = new paint(); public static void justifytext(final textview tv, final float origwidth){ string s = tv.gettext().tostring(); p.settypeface(tv.gettypeface()); string [] splits = s.split(system_newline); float width = origwidth - 5; for(int x = 0; x<splits.length;x++) if(p.measuretext(splits[x])>width){ splits[x] = wrap(splits[x], width, p); string [] microsplits = splits[x].split(system_newline); for(int y = 0; y<microsplits.length-1;y++) microsplits[y] = justify(removelast(microsplits[y], " "), width, p); stringbuilder smb_internal = new stringbuilder(); for(int z = 0; z<microsplits.length;z++) smb_internal.append(microsplits[z]+((z+1<microsplits.length) ? system_newline : "")); splits[x] = smb_internal.tostring(); } final stringbuilder smb = new stringbuilder(); for(string cleaned : splits) smb.append(cleaned+system_newline); tv.setgravity(gravity.left); tv.settext(smb); } private static string wrap(string s, float width, paint p){ string [] str = s.split("\\s"); //regex stringbuilder smb = new stringbuilder(); //save memory smb.append(system_newline); for(int x = 0; x<str.length; x++){ float length = p.measuretext(str[x]); string [] pieces = smb.tostring().split(system_newline); try{ if(p.measuretext(pieces[pieces.length-1])+length>width) smb.append(system_newline); }catch(exception e){} smb.append(str[x] + " "); } return smb.tostring().replacefirst(system_newline, ""); } private static string removelast(string s, string g){ if(s.contains(g)){ int index = s.lastindexof(g); int indexend = index + g.length(); if(index == 0) return s.substring(1); else if(index == s.length()-1) return s.substring(0, index); else return s.substring(0, index) + s.substring(indexend); } return s; } private static string justifyoperation(string s, float width, paint p){ float holder = (float) (complexity*math.random()); while(s.contains(float.tostring(holder))) holder = (float) (complexity*math.random()); string holder_string = float.tostring(holder); float lessthan = width; int timeout = 100; int current = 0; while(p.measuretext(s)<lessthan&¤t<timeout) { s = s.replacefirst(" ([^"+holder_string+"])", " "+holder_string+"$1"); lessthan = p.measuretext(holder_string)+lessthan-p.measuretext(" "); current++; } string cleaned = s.replaceall(holder_string, " "); return cleaned; } private static string justify(string s, float width, paint p){ while(p.measuretext(s)<width){ s = justifyoperation(s,width, p); } return s; } public void updates() { databasehandler db = new databasehandler(this); db.deletetable1(); db.deletetable2(); getjson(); //getjson2(); } }
you doing operation on activity's main thread
. please use asynctask
download data web.
from android 4.0 + version, mandatory use worker thread.
async task documentation link: asynctask
Comments
Post a Comment