json string is not properly shown in android device - string
i am facing a issue on getting JObject, my app is working in emulator and it is not working in device. because the string is not properly converting to JObject.
E/JSON 1111﹕ parsing data {"success":1,"projects":[{"thumbimg":"http:\/\/spvdigi.com\/diyaphp\/images\/lab.png","duration":"3 mins","updated_at":"0000-00-00 00:00:00","keywords":"law,white sheet,pen,pencil,mini bulbs,","materials":"pen,pencil,ball,worksheet","description":"about the law bla bla","subject":"science","target":"k2","created_at":"2015-08-14 14:24:54","pid":"1","rating":"4","procedure":"procedure about this project"},{"thumbimg":"http:\/\/spvdigi.com\/diyaphp\/images\/lab.png","duration":"3 mins","updated_at":"0000-00-00 00:00:00","keywords":"pen,pencil,color pencil,chart,sticks","materials":"pen,pencil,color pencil,chart,sticks,etc","description":"about description of the project","subject":"science","target":"k3","created_at":"2015-08-14 14:25:16",
"pid":"2","rating":"3","procedure":"about description of the procedure"},{"thumbimg":"http:\/\/spvdigi.com\/diyaphp\/images\/lab.png","duration":"5 mins","updated_at":"0000-00-00 00:00:00","keywords":"pen,pencil,wire,chart,sticks","materials":"pen,pencil,color pencil,chart,sticks,eraser","description":"about description of the project","subject":"english","target":"k4","created_at":"2015-08-14 14:25:21",
....
"pid":"8","rating":"3","procedure":"about description of the procedure"}]}
the above is the output of the jsonObject, the below is the correct result showing in emulator
{"projects":[{"pid":"1","target":"k2","subject":"science","description":"about the law bla bla","duration":"3 mins","materials":"pen,pencil,ball,worksheet","procedure":"procedure about this project","keywords":"law,white sheet,pen,pencil,mini bulbs,","thumbimg":"http:\/\/spvdigi.com\/diyaphp\/images\/lab.png","rating":"4","created_at":"2015-08-14 14:24:54","updated_at":"0000-00-00 00:00:00"},{"pid":"2","target":"k3","subject":"science","description":"about description of the project","duration":"3 mins","materials":"pen,pencil,color pencil,chart,sticks,etc","procedure":"about description of the procedure","keywords":"pen,pencil,color pencil,chart,sticks","thumbimg":"http:\/\/spvdigi.com\/diyaphp\/images\/lab.png","rating":"3","created_at":"2015-08-14 14:25:16","updated_at":"0000-00-00 00:00:00"},
...
{"pid":"8","target":"k3","subject":"english","description":"to learn english tenses","duration":"3 mins","materials":"white sheet,pen,pencil,eraser","procedure":"about description of the procedure","keywords":"english,grammer,tenses","thumbimg":"http:\/\/spvdigi.com\/diyaphp\/images\/lab.png","rating":"3","created_at":"2015-08-18 06:45:28","updated_at":"0000-00-00 00:00:00"}],"success":1}
this is my jsonparse class code:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
static String jboolean = "0";
static JSONArray jarr =null;
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 10000);
HttpConnectionParams.setSoTimeout(httpParameters, 10000 + 12000);
DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-type","application/json");
httpPost.setParams(httpParameters);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Log.e("Buffer 11", "Error converting result " + e.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("Buffer 22", "Error converting result " + e.toString());
} catch (IOException e) {
e.printStackTrace();
Log.e("Buffer 33", "Error converting result " + e.toString());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
//Log.e("JSON 1111 ", "parsing data " + json.toString());
} catch (Exception e) {
Log.e("Buffer Error????", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
Log.e("JSON 1111 ", "parsing data " + jObj.toString());
} catch (JSONException e) {
Log.e("JSON Parser44", "Error parsing data " + e.toString());
}
return jObj;
/// This JObj is not properly getting the json string???
// return JSON String
}
}
Is there any issues on the above code? i am facing a issue on getting JObject, my app is working in emulator and it is not working in device. because the string is not properly converting to JObject.
Related
Azure Graph API Authentication_MissingOrMalformed
I am using Azure Graph API to import users from Azure AD. In the azure portal I have added multiple Applications. I am getting clientId, tenantId from protal and creating a secret key with one year expiry. Using these values I am creating an access_token and using that token connecting to AD. Here is the code public static String loginUrlPrefix = "https://login.windows.net/"; public static String loginUrlSufix = "/oauth2/token"; public static String importUrl = "https://management.core.windows.net/<subscription-id>/services/importexport/"; #SuppressWarnings("deprecation") public static String getToken(String tenantId,String clientId,String encodedSecretKey) { try { String secretKey = EncryptionUtils.decryptAES(encodedSecretKey); secretKey = URLEncoder.encode(secretKey); String urltoConnect = loginUrlPrefix+tenantId+loginUrlSufix; String payLoad = "resource=https%3A%2F%2Fmanagement.core.windows.net%2F&client_id="+clientId+"&grant_type=client_credentials&client_secret=" + secretKey; URL url = new URL(urltoConnect); URLConnection connection = null; connection = url.openConnection(); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setDoOutput(true); java.io.OutputStreamWriter wr = new java.io.OutputStreamWriter(connection.getOutputStream()); wr.write(payLoad); wr.flush(); BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); String content; String html = ""; while ((content = br.readLine()) != null) { if (!content.equals("") && content.length() != 0) html += content.trim(); } return html; } catch (Exception e) { e.printStackTrace(); try { throw e; } catch (Exception e1) { e1.printStackTrace(); } } return null; } #SuppressWarnings("deprecation") public static Boolean testADConnection(String accessToken,String tenant) { try { URL url = new URL(String.format("https://graph.windows.net/%s/tenantDetails?api-version=2013-04-05", tenant, accessToken)); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // Set the appropriate header fields in the request header. conn.setRequestProperty("api-version", "2013-04-05"); conn.setRequestProperty("Authorization","Bearer "+ accessToken); conn.setRequestProperty("Accept", "application/json;odata=minimalmetadata"); String goodRespStr = HttpClientHelper.getResponseStringFromConn(conn, true); System.out.println(goodRespStr); int responseCode = conn.getResponseCode(); if(responseCode == 200){ return true; } else{ System.out.println(goodRespStr); } } catch (Exception e) { e.printStackTrace(); try { throw e; } catch (Exception e1) { e1.printStackTrace(); } } return false; } public static void main(String[] args){ String tokenJSON = getToken(tenantId,clientId,secretKey); if(tokenJSON != null){ JSONObject j = (JSONObject) JSONValue.parse(tokenJSON); String token = (String) j.get("access_token"); testADConnection(token,tenantId); } } This works fine with the first application I added. But when I add a second application with the same configuration and permissions this is not working. I am getting a 403 error "odata.error": { "code": "Authentication_MissingOrMalformed", "message": { "lang": "en", "value": "Access Token missing or malformed." }, "date": "2016-12-02T07:27:59", } Tenant Id i am passing same for both the applications (copied from show diagnostics in help menu) client id I am copying whatever is generated in Azure and labelled as Application Id.Secret Key I am generating in Azure portal with 1 year validity.
Blackberry - How to consume wcf rest services
Recently i have started working on consuming wcf rest webservices in blackberry. I have used the below two codes: 1. URLEncodedPostData postData = new URLEncodedPostData(URLEncodedPostData.DEFAULT_CHARSET, false); // passing q’s value and ie’s value postData.append("UserName", "hsharma#seasiaconsulting.com"); postData.append("Password", "mind#123"); HttpPosst hh=new HttpPosst(); add(new LabelField("1")); String res=hh.GetResponse("http://dotnetstg.seasiaconsulting.com/profire/ProfireService.svc/UserRegistration",postData); add(new LabelField("2")); add(new LabelField(res)); public String GetResponse(String url, URLEncodedPostData data) { this._postData = data; this._url = url; ConnectionFactory conFactory = new ConnectionFactory(); ConnectionDescriptor conDesc = null; try { if (WLANInfo.getWLANState() == WLANInfo.WLAN_STATE_CONNECTED) { connectionString = ";interface=wifi"; } // Is the carrier network the only way to connect? else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_DIRECT) == CoverageInfo.COVERAGE_DIRECT) { // logMessage("Carrier coverage."); // String carrierUid = getCarrierBIBSUid(); // Has carrier coverage, but not BIBS. So use the carrier's TCP // network // logMessage("No Uid"); connectionString = ";deviceside=true"; } // Check for an MDS connection instead (BlackBerry Enterprise // Server) else if ((CoverageInfo.getCoverageStatus() & CoverageInfo.COVERAGE_MDS) == CoverageInfo.COVERAGE_MDS) { // logMessage("MDS coverage found"); connectionString = ";deviceside=false"; } // If there is no connection available abort to avoid bugging the // user // unnecssarily. else if (CoverageInfo.getCoverageStatus() == CoverageInfo.COVERAGE_NONE) { // logMessage("There is no available connection."); } // In theory, all bases are covered so this shouldn't be reachable. else { // logMessage("no other options found, assuming device."); // connectionString = ";deviceside=true"; } conDesc = conFactory.getConnection(url + connectionString); } catch (Exception e) { System.out.println(e.toString() + ":" + e.getMessage()); } String response = ""; // this variable used for the server response // if we can get the connection descriptor from ConnectionFactory if (null != conDesc) { try { HttpConnection connection = (HttpConnection) conDesc.getConnection(); // set the header property connection.setRequestMethod(HttpConnection.POST); connection.setRequestProperty("Content-Length",Integer.toString(data.size())); // body content of // post data connection.setRequestProperty("Connection", "close"); // close // the // connection // after // success // sending // request // and // receiving // response // from // the // server connection.setRequestProperty("Content-Type","application/json"); // we set the // content of // this request // as // application/x-www-form-urlencoded, // because the // post data is // encoded as // form-urlencoded(if // you print the // post data // string, it // will be like // this -> // q=remoQte&ie=UTF-8). // now it is time to write the post data into OutputStream OutputStream out = connection.openOutputStream(); out.write(data.getBytes()); out.flush(); out.close(); int responseCode = connection.getResponseCode(); // when this // code is // called, // the post // data // request // will be // send to // server, // and after // that we // can read // the // response // from the // server if // the // response // code is // 200 (HTTP // OK). if (responseCode == HttpConnection.HTTP_OK) { // read the response from the server, if the response is // ascii character, you can use this following code, // otherwise, you must use array of byte instead of String InputStream in = connection.openInputStream(); StringBuffer buf = new StringBuffer(); int read = -1; while ((read = in.read()) != -1) buf.append((char) read); response = buf.toString(); } // don’t forget to close the connection connection.close(); } catch (Exception e) { System.out.println(e.toString() + ":" + e.getMessage()); } } return response; } public boolean checkResponse(String res) { if(!res.equals("")) { if(res.charAt(0)=='{') { return true; } else { return false; } } else { return false; } } but with this code i am unable to obtain response as what the above wcf web service return which is({"UserRegistrationResult":[{"OutputCode":"2","OutputDescription":"UserName Already Exists."}]}) Can anybody help me regarding its parsing in blackberry client end. 2.And the another code which i used is: public class KSoapDemo extends MainScreen { private EditField userNametxt; private PasswordEditField passwordTxt; private ButtonField loginBtn; String Username; String Password; public KSoapDemo() { userNametxt = new EditField("User Name : ", "hsharma#seasiaconsulting.com"); passwordTxt = new PasswordEditField("Password : ", "mind#123"); loginBtn = new ButtonField("Login"); add(userNametxt); add(passwordTxt); add(loginBtn); loginBtn.setChangeListener(new FieldChangeListener() { public void fieldChanged(Field field, int context) { //Dialog.alert("Hi Satyaseshu..!"); login(); } }); } private void login() { if (userNametxt.getTextLength() == 0 || passwordTxt.getTextLength() == 0) { //Dialog.alert("You must enter a username and password", ); } else { String username = userNametxt.getText(); String password = passwordTxt.getText(); System.out.println("UserName... " + username); System.out.println("Password... " + password); boolean value = loginPArse1(username, password); add(new LabelField("value... " + value)); } } public boolean onClose() { Dialog.alert("ADIOOO!!"); System.exit(0); return true; } public boolean loginPArse1(String username, String password) { username=this.Username; password=this.Password; boolean ans = false; String result = null; SoapObject request = new SoapObject("http://dotnetstg.seasiaconsulting.com/","UserRegistration"); //request.addProperty("PowerValue","1000"); //request.addProperty("fromPowerUnit","kilowatts"); //request.addProperty("toPowerUnit","megawatts"); request.addProperty("userName",Username); request.addProperty("Password", Password); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.bodyOut = request; envelope.dotNet = true; add(new LabelField("value... " + "1")); HttpTransport ht = new HttpTransport("http://dotnetstg.seasiaconsulting.com/profire/ProfireService.svc/UserRegistration"+ConnectionInfo.getInstance().getConnectionParameters()); ht.debug = true; add(new LabelField("value... " + "2")); //System.out.println("connectionType is: " + connectionType); try { ht.call("http://dotnetstg.seasiaconsulting.com/profire/ProfireService.svc/UserRegistration", envelope); SoapObject body = (SoapObject) envelope.bodyIn; add(new LabelField("soap....="+body.toString())); add(new LabelField("property count....="+body.getPropertyCount())); // add(new LabelField("Result....="+body.getProperty("HelloWorldResult"))); //result = body.getProperty("Params").toString(); // add(new LabelField("value... " + "4")); ans=true; } catch (XmlPullParserException ex) { add(new LabelField("ex1 "+ex.toString()) ); ex.printStackTrace(); } catch (IOException ex) { add(new LabelField("ex1 "+ex.toString()) ); ex.printStackTrace(); } catch (Exception ex) { add(new LabelField("ex1 "+ex.toString()) ); ex.printStackTrace(); } return ans; } and in return i am obtain response as net.rim.device.cldc.io.dns.DNS Exception:DNS Error Please help me in this regard Thanks And Regards Pinkesh Gupta
Please have the answer for my own question helps in parsing wcf rest services developed in .net and parsed at blackberry end. This 2 classess definitely helps in achieving the above code parsing. import java.io.IOException; import java.io.OutputStream; import java.io.InputStream; import javax.microedition.io.Connector; import javax.microedition.io.HttpConnection; public class ConnectionThread extends Thread { private boolean start = false; private boolean stop = false; private String url; private String data; public boolean sendResult = false; public boolean sending = false; private String requestMode = HttpConnection.POST; public String responseContent; int ch; public void run() { while (true) { if (start == false && stop == false) { try { sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } else if (stop) { return; } else if (start) { http(); } } } private void getResponseContent( HttpConnection conn ) throws IOException { InputStream is = null; is = conn.openInputStream(); // Get the length and process the data int len = (int) conn.getLength(); if ( len > 0 ) { int actual = 0; int bytesread = 0; byte[] data = new byte[len]; while ( ( bytesread != len ) && ( actual != -1 ) ) { actual = is.read( data, bytesread, len - bytesread ); bytesread += actual; } responseContent = new String (data); } else { // int ch; while ( ( ch = is.read() ) != -1 ) { } } } private void http() { System.out.println( url ); HttpConnection conn = null; OutputStream out = null; int responseCode; try { conn = (HttpConnection) Connector.open(url); conn.setRequestMethod(requestMode); conn.setRequestMethod(HttpConnection.POST); conn.setRequestProperty("Content-Length",Integer.toString(data.length())); conn.setRequestProperty("Connection", "close"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("SOAPAction","http://dotnetstg.seasiaconsulting.com/"); out = conn.openOutputStream(); out.write(data.getBytes()); out.flush(); responseCode = conn.getResponseCode(); if (responseCode != HttpConnection.HTTP_OK) { sendResult = false; responseContent = null; } else { sendResult = true; getResponseContent( conn ); } start = false; sending = false; } catch (IOException e) { start = false; sendResult = false; sending = false; } } public void get(String url) { this.url = url; this.data = ""; requestMode = HttpConnection.GET; sendResult = false; sending = true; start = true; } public void post(String url, String data) { this.url = url; this.data = data; requestMode = HttpConnection.POST; sendResult = false; sending = true; start = true; } public void stop() { stop = true; } } import net.rim.device.api.ui.Field; import net.rim.device.api.ui.FieldChangeListener; import net.rim.device.api.ui.component.AutoTextEditField; import net.rim.device.api.ui.component.BasicEditField; import net.rim.device.api.ui.component.ButtonField; import net.rim.device.api.ui.component.DateField; import net.rim.device.api.ui.component.LabelField; import net.rim.device.api.ui.component.ObjectChoiceField; import net.rim.device.api.ui.component.SeparatorField; import net.rim.device.api.ui.component.Status; import net.rim.device.api.ui.container.MainScreen; import org.json.me.JSONArray; import org.json.me.JSONException; import org.json.me.JSONObject; import org.xml.sax.SAXException; import net.rim.device.api.xml.parsers.SAXParser; import net.rim.device.api.xml.jaxp.SAXParserImpl; import org.xml.sax.helpers.DefaultHandler; import java.io.ByteArrayInputStream; import com.sts.example.ConnectionThread; import com.sts.example.ResponseHandler; public class DemoScreen extends MainScreen { private ConnectionThread connThread; private BasicEditField response = new BasicEditField("Response: ", ""); private BasicEditField xmlResponse = new BasicEditField("xml: ", ""); private ButtonField sendButton = new ButtonField("Response"); public DemoScreen(ConnectionThread connThread) { this.connThread = connThread; FieldListener sendListener = new FieldListener(); sendButton.setChangeListener(sendListener); response.setEditable( false ); xmlResponse.setEditable( false ); add(sendButton); add(response); add(new SeparatorField()); add(xmlResponse); } public boolean onClose() { connThread.stop(); close(); return true; } private String getFieldData() { //{"UserName":"hsharma#seasiaconsulting.com","Password":"mind#123"} StringBuffer sb = new StringBuffer(); sb.append("{\"UserNamepinkesh.g#cisinlabs.com\",\"Password\":\"pinkesh1985\"}"); return sb.toString(); } class FieldListener implements FieldChangeListener { public void fieldChanged(Field field, int context) { StringBuffer sb = new StringBuffer("Sending..."); connThread.post("http://dotnetstg.seasiaconsulting.com/profire/ProfireService.svc/UserRegistration"+ConnectionInfo.getInstance().getConnectionParameters(), getFieldData()); while (connThread.sending) { try { Status.show( sb.append(".").toString() ); Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } if (connThread.sendResult) { Status.show("Transmission Successfull"); xmlResponse.setText( connThread.responseContent ); try { JSONObject jsonResponse = new JSONObject(connThread.responseContent); JSONArray jsonArray = jsonResponse.getJSONArray("UserRegistrationResult"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject result = (JSONObject)jsonArray.get(i); add(new LabelField("OutputCode"+result.getString("OutputCode"))); add(new LabelField("OutputDescription"+result.getString("OutputDescription"))); } } catch (JSONException e) { add(new LabelField(e.getMessage().toString())); e.printStackTrace(); } } else { Status.show("Transmission Failed"); } } } }
using post throws IOExceptions on some phones
i have created an application in J2ME that uses the following method to connect to a server. php is used on the Server side to process the requests. the application works fine on some phones like NOkia asha 303 but throws IOException on other phones what could be the problem with this code. this method is called on a different thread. i also want to ask if you use post in j2me and set the httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); do you have to urlencode the data before sending or that is handled automatically by j2me public String sendData(String serverUrl, String dataToSend) { String strResponse = "0"; //string to hold serverResponse StringBuffer sb = new StringBuffer(""); HttpConnection httpConn = null; InputStream inputStream = null; OutputStream outStream = null; try { //convert the dataToSend to bytes String strData = dataToSend; // get the data to Send and store it in a variable. byte[] dataToSendBytes = strData.getBytes(); //open the Connection to the server. httpConn = (HttpConnection) Connector.open(serverUrl, Connector.READ_WRITE, true); if (httpConn != null) { httpConn.setRequestMethod(HttpConnection.POST); // method used to send the data. httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpConn.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.1"); //httpConn.setRequestProperty("Content-Language", "en-US"); //language to use. //setRequestProperty("Connection", "close") ===> could generate or Solve IOExceptions on different mobile Phones. //httpConn.setRequestProperty("Connection", "close"); //setting the Content-length could have issues with some Servers===> //if the dataToSend is Empty String => contentLen = 0 , else get length of the dataBytes. String contentLen = ((dataToSend.length() > 0) ? Integer.toString(dataToSendBytes.length) : Integer.toString(0)); //httpConn.setRequestProperty("Content-length", contentLen); //not working on Emulator ....enable on shipping application. //open the output Stream to send data to the Server. outStream = httpConn.openOutputStream(); // send the bytes of data to the Server.===> //outStream.write(dataToSendBytes); //send the data bytes to the Server. int byteLen = dataToSendBytes.length; //length of byteToSend. for (int k = 0; k < byteLen; k++) { //send all the databytes to the Server. outStream.write(dataToSendBytes[k]); } //close the outputStream ===immediately after sending the data bytes to the Server===>eliminates the IOExceptions. closeOutStream(outStream); //get response code on Sending Data===> getting response code automatically flushes the output data. ntworkResponseCode = httpConn.getResponseCode(); if (ntworkResponseCode == HttpConnection.HTTP_OK) { //connection to the Server was okay. if (httpConn != null) { //read the Response From the Server----------- inputStream = httpConn.openInputStream(); // open the inputStream. //get server Response Content length. int contLen = (int) httpConn.getLength(); byte[] serverResponseBytes; //byte array to store the serverResponse. if (contLen != -1) { //store the serverResponse to a byte array.===> using a byte buffer could be faster. serverResponseBytes = new byte[contLen]; inputStream.read(serverResponseBytes); //convert the bytes to String and store them to the StringBuffer. sb.append(new String(serverResponseBytes)); } else { //serverResponse Length not available===> read character by character could be slower. int read; while ((read = inputStream.read()) != -1) { sb.append((char) read); } } //store the server response in a String. strResponse = sb.toString(); } } else { //connection problem occured. //throw new IOException("Http Response Code [" + ntworkResponseCode + "]"); } }// the httpConnection Not null.--end. } catch (IllegalArgumentException arge) { strResponse = CONNECTION_EXCEPTION; } catch (ConnectionNotFoundException cone) { //a string to show we got an exception strResponse = CONNECTION_EXCEPTION; } catch (IOException ioe) { //a string to show we got an exception strResponse = CONNECTION_EXCEPTION; } catch (SecurityException se) { //user cancelled the Connection Request. strResponse = CONNECTION_EXCEPTION; } finally { //close all the connection streams try { if (inputStream != null) { //close the inputStream inputStream.close(); inputStream = null; } if (outStream != null) { //close the outStream. outStream.close(); outStream = null; } if (httpConn != null) { //close the connection object. httpConn.close(); httpConn = null; } } catch (IOException ie) { //show exception occured. } } //return server Response to the Client. return strResponse; }
Download Images in loop java me
In my application we have to download around 10 Images from server and display it in mobile. How can I do this? Can I use same HttpConnection for full download? Is any other way for download?
You can do with this simple loop (Supposing imageList is a List with the url of the images). HttpConnection = null; Image image = null; for (int i = 0; i < imageList.getSize(); i++) { try{ String urlImage = imageList.get(i); hc = (HttpConnection) Connector.open(urlImage); image = Image.createImage(hc.openInputStream())); } catch (Exception e) { e.printStackTrace(); } finally { try { hc.close(); } catch (IOException ex) { ex.printStackTrace(); } } }
You can try following method in a loop for downloading images from server. private void downloadImage ( String URL ) { try { System.out.println("URL FOR POST_DATA : "+URL); // Open up a http connection with the Web server for both send and receive operations httpConnection = (HttpConnection)Connector.open(URL, Connector.READ_WRITE); // Set the request method to POST httpConnection.setRequestMethod(HttpConnection.POST); // Set the request headers httpConnection.setRequestProperty(ConstantCodes.ACTION_MODE_PARAMETER,action); httpConnection.setRequestProperty(ConstantCodes.USER_NAME_REQUEST_PARAMETER,userName); if(eventName==null || eventName.equals("")) eventName="default"; httpConnection.setRequestProperty(ConstantCodes.EVENT_NAME_REQUEST_PARAMETER, eventName); httpConnection.setRequestProperty(ConstantCodes.CAMERAID_REQUEST_PARAMETER, cameraID); // all the headers are sending now and connection chanel is establising dis = httpConnection.openDataInputStream(); int ch = 0; ByteArrayOutputStream bytearray = new ByteArrayOutputStream(250000); while((ch = dis.read()) != -1) bytearray.write(ch); // fileByte contains whole file in bytes byte fileByte[] = bytearray.toByteArray(); fileSize = fileByte.length; System.out.println("Got file size : "+fileSize); if(bytearray!=null) bytearray.close(); midlet.getLastPostedImageResponse(fileByte); } catch (IOException ioe) { ioe.printStackTrace(); System.out.println("IOException occured during getting last image data : "+ioe.getMessage()); } catch(Exception e) { e.printStackTrace(); System.out.println("Eeception occurred during getting last image data : "+e.getMessage()); } finally { System.out.println("Calling close from Last image posted Action"); close(); }
FileOutputStream error
I had a part of code which suppose to get an image from website and store it into the sdcard. The following code was working find when i develop on sdk1.5. However, it was not working now after i change it to android sdk 2.0. This line got problem; FileOutputStream fos = new FileOutputStream(filepath + "/" + this.filename); Here is the code that i have: void downloadFile(String fileUrl) { URL myFileUrl = null; try { myFileUrl = new URL(fileUrl); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { HttpURLConnection conn = (HttpURLConnection) myFileUrl .openConnection(); conn.setDoInput(true); conn.connect(); InputStream is = conn.getInputStream(); bmImg = BitmapFactory.decodeStream(is); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { String filepath = Environment.getExternalStorageDirectory() .getAbsolutePath(); FileOutputStream fos = new FileOutputStream(filepath + "/" + this.filename); bmImg.compress(CompressFormat.JPEG, 75, fos); fos.flush(); fos.close(); Context context = this.getBaseContext(); new MediaScannerNotifier2(context, filepath + "/" + this.filename, "image/jpeg"); // displaying download completion message AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Wallpaper Downloaded").setCancelable(false) .setPositiveButton("ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); btn_setwall.setEnabled(true); btn_download.setEnabled(false); } }); AlertDialog alert = builder.create(); alert.show(); } catch (Exception e) { Log.e("MyLog", e.toString()); } } The error occur in the 3rd catch. However, when i move this line FileOutputStream fos = new FileOutputStream(filepath + "/" + this.filename); to the 2nd try/catch, then it will occur in the 2nd catch. Can please help me on this?
Maybe try getting rid of .getAbsolutePath() This works for me on 2.2: FileOutputStream fos = new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + fileName);