-1

I tried to read a json string loading from an URL, but I could not find complete code sample. Can any one provide or point me to a complete client code. I'm newer to BB development.

this is what I have done but still can't get it work please help me.

Thanks!

Community
  • 1
  • 1
Grant
  • 4,413
  • 18
  • 56
  • 82
  • 1
    possible duplicate of [Blackberry json parser](http://stackoverflow.com/questions/16474847/blackberry-json-parser) – Rince Thomas May 21 '13 at 11:21
  • that question also asked by me, but it is still not working. I think I have to start new thread to access the web but still I have no idea. Please help. Thanks! – Grant May 21 '13 at 11:23
  • 1
    my answer to that question will solve your problem. Did you tried that ? – Rince Thomas May 21 '13 at 11:25
  • Do I need to start new thread to make a http request in BB ?? – Grant May 21 '13 at 11:26
  • after getting _response = new String(out.toByteArray()); , use my code – Rince Thomas May 21 '13 at 11:28
  • Sorry one more question.. So what is the value that I need to add for this "Insert Json Array Key" here JSONArray newsArray = resObject.getJSONArray("Insert Json Array Key"); – Grant May 21 '13 at 11:31
  • no need to use json array. Because your responce is a json object. Not an array. – Rince Thomas May 21 '13 at 11:31
  • Exception: Uncaught exception : pushModalScreen called by a non........................................ – Grant May 21 '13 at 11:41
  • comment the line Dialog.alert – Rince Thomas May 21 '13 at 11:44
  • 3
    @Grant, I think you are dealing with several problems at the same time. You need to break your problem to sub problems and solve each of them independently. For this problem, first you need to know how to make an HTTP connection and read data from URL. After you completed that task then you need to start JSON parsing which will use a String as input. And finally you need to solve other UI related issues (pushModalScreen error, Dialog error etc). – Rupak May 21 '13 at 13:43

1 Answers1

2

To read and parse data from an URL you need to implement two routines. First one of them will handle reading data from the specified URL over HTTP connection, and the second one will parse the data.

Check the following application HttpUrlReaderDemoApp, which will first read the data from specified URL and then parse the retrieved data.

Classes:

  • HttpUrlReaderDemoApp - UiApplication instance
  • HttpResponseListener - Interface used to notify other classes about HTTP request status
  • HttpUrlReader - Reads the data from given url
  • AppMainScreen - MainScreen instance
  • DataParser - Parse data
  • DataModel - Data definition

Screenshots:

  • Request for data

    Request for data

  • When data retrieved successfully

    When data retrieved successfully

  • Parsed data

    Parsed data

Implementation:

HttpUrlReaderDemoApp

public class HttpUrlReaderDemoApp extends UiApplication {
    public static void main(String[] args) {
        HttpUrlReaderDemoApp theApp = new HttpUrlReaderDemoApp();
        theApp.enterEventDispatcher();
    }

    public HttpUrlReaderDemoApp() {
        pushScreen(new AppMainScreen("HTTP Url Reader Demo Application"));
    }
}

HttpResponseListener

public interface HttpResponseListener {
    public void onHttpResponseFail(String message, String url);

    public void onHttpResponseSuccess(byte bytes[], String url);
}

HttpUrlReader

public class HttpUrlReader implements Runnable {
    private String url;
    private HttpResponseListener listener;

    public HttpUrlReader(String url, HttpResponseListener listener) {
        this.url = url;
        this.listener = listener;
    }

    private String getConncetionDependentUrlSuffix() {
        // Not implemented
        return "";
    }

    private void notifySuccess(byte bytes[], String url) {
        if (listener != null) {
            listener.onHttpResponseSuccess(bytes, url);
        }
    }

    private void notifyFailure(String message, String url) {
        if (listener != null) {
            listener.onHttpResponseFail(message, url);
        }
    }

    private boolean isValidUrl(String url) {
        return (url != null && url.length() > 0);
    }

    public void run() {
        if (!isValidUrl(url) || listener == null) {
            String message = "Invalid parameters.";
            message += !isValidUrl(url) ? " Invalid url." : "";
            message += (listener == null) ? " Invalid HttpResponseListerner instance."
                    : "";
            notifyFailure(message, url);
            return;
        }

        // update URL depending on connection type
        url += DeviceInfo.isSimulator() ? ";deviceside=true"
                : getConncetionDependentUrlSuffix();

        // Open the connection and retrieve the data
        try {
            HttpConnection httpConn = (HttpConnection) Connector.open(url);
            int status = httpConn.getResponseCode();
            if (status == HttpConnection.HTTP_OK) {
                InputStream input = httpConn.openInputStream();
                byte[] bytes = IOUtilities.streamToBytes(input);
                input.close();
                notifySuccess(bytes, url);
            } else {
                notifyFailure("Failed to retrieve data, HTTP response code: "
                        + status, url);
                return;
            }
            httpConn.close();
        } catch (Exception e) {
            notifyFailure("Failed to retrieve data, Exception: ", e.toString());
            return;
        }
    }
}

AppMainScreen

public class AppMainScreen extends MainScreen implements HttpResponseListener {
    private final String URL = "http://codeincloud.tk/json_android_example.php";

    public AppMainScreen(String title) {
        setTitle(title);
    }

    private MenuItem miReadData = new MenuItem("Read data", 0, 0) {
        public void run() {
            requestData();
        }
    };

    protected void makeMenu(Menu menu, int instance) {
        menu.add(miReadData);
        super.makeMenu(menu, instance);
    }

    public void close() {
        super.close();
    }

    public void showDialog(final String message) {
        UiApplication.getUiApplication().invokeLater(new Runnable() {
            public void run() {
                Dialog.alert(message);
            }
        });
    }

    private void requestData() {
        Thread urlReader = new Thread(new HttpUrlReader(URL, this));
        urlReader.start();
        showDialog("Request for data from\n \"" + URL + "\"\n started.");
    }

    public void onHttpResponseFail(String message, String url) {
        showDialog("Failure Mesage:\n" + message + "\n\nUrl:\n" + url);
    }

    public void onHttpResponseSuccess(byte bytes[], String url) {
        showDialog("Data retrived from:\n" + url + "\n\nData:\n"
                + new String(bytes));

        // now parse response
        DataModel dataModel = DataParser.getData(bytes);
        if (dataModel == null) {
            showDialog("Failed to parse data: " + new String(bytes));
        } else {
            showDialog("Parsed Data:\nName: " + dataModel.getName()
                    + "\nVersion: " + dataModel.getVersion());
        }
    }
}

DataParser

public class DataParser {
    private static final String NAME = "name";
    private static final String VERSION = "version";

    public static DataModel getData(byte data[]) {
        String rawData = new String(data);
        DataModel dataModel = new DataModel();

        try {
            JSONObject jsonObj = new JSONObject(rawData);
            if (jsonObj.has(NAME)) {
                dataModel.setName(jsonObj.getString(NAME));
            }
            if (jsonObj.has(VERSION)) {
                dataModel.setVersion(jsonObj.getString(VERSION));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return dataModel;
    }
}

DataModel

public class DataModel {
    private String name;
    private String version;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String model) {
        this.version = model;
    }
}
Rupak
  • 3,674
  • 15
  • 23