DefaultHttpClient change response size? - android

What I try to do
Hello Guys, I'm trying to create an App in which I can view the Orders the Customers gave to me. For this I created a interface on my server, on which I can send post/get/set request's. The response of the Server is in JSON-Format. (For your Information atm only dummydata is filled in)
Now when I do a get request from my app to the server, I get a response from it but it isn't complete about the half of the response I should get isn't there! :( But when I open the URL with the Get-Request in my browser, I get the full response.
Question
Like you see it can't be a server-based problem, because I also tryed via 'curl' to do this get requst, and allways got the full response.
In my App i work with the DefaultHttpClient, so I tought the Problem simply could be that there's a limit for the response but I didn't found it.
So where can I change this "response-size" and what else could be the problem why I don't get the full response! Some good code-snippets or whatever you can imagine would help!
Down here you'll find the code of the Methode which does the Get-Request.
Code
If you need more Code, just write it in the comments!
getOrders()
public void getOrders() {
Log.d("DataHandlerService", "Aufträge werden geladen");
Thread t = new Thread() {
public void run() {
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String userid = settings.getString("userid", "uid");
Log.d("DataHandlerService", userid);
// Download-URL
String URL = "http://api.i-v-o.ch/users/" + userid
+ "/assignments.json";
Log.d("Request-URL", URL);
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response;
try {
HttpGet request = new HttpGet();
request.setURI(new URI(URL));
request.addHeader("Content-Type",
"application/x-www-form-urlencoded");
response = client.execute(request);
int statuscode = response.getStatusLine().getStatusCode();
switch (statuscode) {
case 200:
if (response != null) {
StringBuilder sb = new StringBuilder();
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity()
.getContent()));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line + "\n");
}
String result;
result = sb.toString();
Log.d("Response", result);
JSONReader(result); //here the json will be generated
}
break;
case 500:
// Error-Handling
break;
}
} catch (Exception e) {
e.printStackTrace();
Log.e("DataHandler", "URLConnection-Error" + e);
}
}
};
t.start();
}
Here's the Response you asked for, like you see a part of it isn't there!:
[{"created_at":"2012-01-06T17:10:00Z","end_datetime":"2008-03-25T13:00:00Z","id":2127,"start_datetime":"2008-03-25T13:00:00Z","updated_at":"2012-01-06T17:10:00Z","title":"2127 Foobar","referee_forename":"Peter","referee_surname":"Gertsch","referee_full_name":"Peter Gertsch","category_title":"Installation - SAT","status_title":"Closed - Erfolgreich"},{"created_at":"2012-01-06T17:10:03Z","end_datetime":"2008-04-04T12:00:00Z","id":2134,"start_datetime":"2008-04-04T12:00:00Z","updated_at":"2012-01-06T17:10:03Z","title":"2134 Foobar","referee_forename":"Daniel","referee_surname":"Brunner","referee_full_name":"Daniel Brunner","category_title":"Installation - SAT","status_title":"Closed - Erfolgreich"},{"created_at":"2012-01-06T17:10:03Z","end_datetime":"2008-04-07T12:00:00Z","id":2136,"start_datetime":"2008-04-07T12:00:00Z","updated_at":"2012-01-06T17:10:03Z","title":"2136 Foobar","referee_forename":"Andreas","referee_surname":"Lutz","referee_full_name":"Andreas Lutz","category_title":"Installation - SAT","status_title":"Closed - technisches problem"},{"created_at":"2012-01-06T17:10:08Z","end_datetime":"2008-05-22T07:00:00Z","id":2144,"start_datetime":"2008-05-22T07:00:00Z","updated_at":"2012-01-06T17:10:08Z","title":"2144 Foobar","referee_forename":"Pascal","referee_surname":"Pichand","referee_full_name":"Pascal Pichand","category_title":"Installation - SAT","status_title":"Closed - Erfolgreich"},{"created_at":"2012-01-06T17:10:08Z","end_datetime":"2008-05-15T07:00:00Z","id":2145,"start_datetime":"2008-05-15T07:00:00Z","updated_at":"2012-01-06T17:10:08Z","title":"2145 Foobar","referee_forename":"Hansruedi","referee_surname":"W\u00fcrgler","referee_full_name":"Hansruedi W\u00fcrgler","category_title":"Installation - SAT","status_title":"Closed - Erfolgreich"},{"created_at":"2012-01-06T17:10:08Z","end_datetime":"2008-05-26T08:00:00Z","id":2146,"start_datetime":"2008-05-26T08:00:00Z","updated_at":"2012-01-06T17:10:08Z","title":"2146 Foobar","referee_forename":"Martina","referee_surname":"Issler","referee_full_name":"Martina Issler","category_title":"Installation - SAT","status_title":"Closed - Erfolgreich"},{"created_at":"2012-01-06T17:10:08Z","end_datetime":"2008-06-03T14:00:00Z","id":2147,"start_datetime":"2008-06-03T14:00:00Z","updated_at":"2012-01-06T17:10:08Z","title":"2147 Foobar","referee_forename":"Matthias ","referee_surname":"Kuhn","referee_full_name":"Matthias Kuhn","category_title":"Installation - SAT","status_title":"Closed - Erfolgreich"},{"created_at":"2012-01-06T17:10:12Z","end_datetime":"2008-07-07T07:00:00Z","id":2157,"start_datetime":"2008-07-07T07:00:00Z","updated_at":"2012-01-06T17:10:12Z","title":"2157 Foobar","referee_forename":"Eberhard","referee_surname":"Polatzek","referee_full_name":"Eberhard Polatzek","category_title":"Installation - SAT","status_title":"Closed - Erfolgreich"},{"created_at":"2012-01-06T17:10:13Z","end_datetime":"2008-07-11T08:00:00Z","id":2161,"start_datetime":"2008-07-11T08:00:00Z","updated_at":"2012-01-06T17:10:13Z","title":"2161 Foobar","referee_forename":"Magali","referee_surname":"Bohin","referee_full_name":"Magali Bohin","category_title":"Installation - SAT","status_title":"Closed - Erfolgreich"},{"created_at":"2012-01-06T17:10:14Z","end_datetime":"2008-07-25T08:30:00Z","id":2163,"start_datetime":"2008-07-25T08:30:00Z","updated_at":"2012-01-06T17:10:14Z","title":"2163 Foobar","referee_forename":"(Hotel Centrum Griesalp)","referee_surname":"Haltenegg Betriebs AG","referee_full_name":"(Hotel Centrum Griesalp) Haltenegg Betriebs AG","category_title":"Installation - SAT","status_title":"Closed - Erfolgreich"},{"created_at":"2012-01-06T17:10:16Z","end_datetime":"2008-08-07T09:00:00Z","id":2170,"start_datetime":"2008-08-07T09:00:00Z","updated_at":"2012-01-06T17:10:16Z","title":"2170 Foobar","referee_forename":".","referee_surname":"SAC Hollandiah\u00fctte","referee_full_name":". SAC Hollandiah\u00fctte","category_title":"Installation - SAT","status_title":"Closed - Erfolgreich"},{"created_at":"2012-01-06T17:10:16Z","end_datetime":"2009-05-07T06:30:00Z","i

Ah. Right, the problem isn't your connection or anything like that. Your service is returning an array - not an object - thus you should parse it like this:
HttpResponse response = ...
if (.. validate status ..) {
JSONArray array = new JSONArray(HttpEntityUtils.toString(response.getEntity()));
// Your JSONArray is now ready to play with.
}
And consider using an AsyncTask instead of a Thread, like this:
class AssignmentsTask extends AsyncTask<String, Void, JSONArray> {
#Override
protected JSONArray doInBackground(String... params) {
final String url = "http://api.i-v-o.ch/users/" + params[0]
+ "/assignments.json";
try {
HttpResponse response = mClient.execute(new HttpGet(url));
if (response.getStatusLine().getStatusCode() == 200) {
return new JSONArray(EntityUtils.toString(response.getEntity()));
} else {
Log.w(TAG, "Error receiving assignments for " + params[0] + ", " + response.getStatusLine());
}
} catch (ClientProtocolException e) {
Log.w(TAG, "Proto: Error fetching assignments for " + params[0], e);
} catch (IOException e) {
e.printStackTrace();
Log.w(TAG, "IO: Error reading assignments for " + params[0], e);
} catch (ParseException e) {
Log.w(TAG, "Parse: Error parsing assignments for " + params[0], e);
} catch (JSONException e) {
Log.w(TAG, "JSON: Error parsing JSON for " + params[0], e);
}
return null;
}
#Override
protected void onPostExecute(JSONArray result) {
// Stuff that handles the resulting JSONObject on
// the UI-thread goes here (i.e. update View:s)
// result is null if the operation failed
}
}
And to retrieve an order for the user "116":
new AssignmentsTask().execute("116");

The response size should be given by the web server you are contacting. You could read the response size using :
httpResponse.getEntity().getContentLength()
Also, what can happen is a connection timeout, making it impossible for the client to receive all data of the response. In that case, try using a timeout that is long enough to be sure you get all the data.
If your json is too large, then it's not a good idea in a mobile context to expect all the data coming in a single request, you could then have to design a web server that could give you chunks of a response, you would then require the first chunk, then the a different one, etc..
Usually, the http protocole's partial content is the answer for that problem.

Related

How to fix "400 bad request" with uploading file on android with java HttpClient?

I need to upload a file to server. If i use the "curl -i -F filedata=#"PATH TO FILE" http://█.199.166.14/audiostream " it return a 200 OK code (Or may be this command incorrect) .
But when I use java function
public String send()
{
try {
url = "http://█.199.166.14/audiostream";
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "test.pcm");
try {
Log.d("transmission", "started");
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
ResponseHandler Rh = new BasicResponseHandler();
InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
response.getEntity().getContentLength();
StringBuilder sb = new StringBuilder();
try {
BufferedReader reader =
new BufferedReader(new InputStreamReader(response.getEntity().getContent()), 65728);
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
}
catch (IOException e) { e.printStackTrace(); }
catch (Exception e) { e.printStackTrace(); }
Log.d("Response", sb.toString());
Log.d("Response", "StatusLine : " + response.getStatusLine() + " Entity: " + response.getEntity()+ " Locate: " + response.getLocale() + " " + Rh);
return sb.toString();
} catch (Exception e) {
// show error
Log.d ("Error", e.toString());
return e.toString();
}
}
catch (Exception e)
{
Log.d ("Error", e.toString());
return e.toString();
}
}
It's return 400 Bad request.
I'm also not sure that server proceed correctly my attempts to upload this file, but I can't check it.
From the error received its likely a bad formatted HTTP query. If audiostream is a php, write the full link.
Also it seems that there might be a wrong/bad encoded char at "http://█.199.166.14/audiostream, the link should be http://(IP or DNS)/(rest of URL)(the URI)
You should erase the link, then manually writte it again.
If those didnt fix the issue, its also possible that the Server (or its path equipment) might be blocking you. Check from the Access Log and the security rules of its accesses, that you are not blocked (some routers may block users from performing repeated querys as a sort of anti "Denial of Service" measure)

JSONExecption Unterminated String - Android

I am building an app that connects to a blog then gathers the data in JSON. Currently I amgeting this error (sorry about all JSON dat not sure whether to include):
Exception Caught
org.json.JSONException: Unterminated string at character 6564 of {"status":"ok","count":20,"count_total":1727,"pages":87,"posts":[{"id":23419,"url":"http:\/\/blog.teamtreehouse.com\/happy-mothers-day-ones-whove-shaped-web-careers","title":"Happy Mother\u2019s Day! Thanks, Mom, for Helping Us Learn","date":"2014-05-08 11:00:29","author":"Ryan Brinks","thumbnail":"http:\/\/blog.teamtreehouse.com\/wp-content\/uploads\/2014\/05\/mothers-dayHaik-Avanian-150x150.jpg"},{"id":23412,"url":"http:\/\/blog.teamtreehouse.com\/technology-brings-people-attitude-public-data-projects","title":"Public Data Brings ‘We the People’ Attitude to Technology","date":"2014-05-08 10:08:22","author":"Kelley King","thumbnail":"http:\/\/blog.teamtreehouse.com\/wp-content\/uploads\/2014\/05\/adoptahydrant-150x150.jpg"},{"id":23409,"url":"http:\/\/blog.teamtreehouse.com\/help-students-learn-computer-programming","title":"A Push for More Computer Programming in Public Schools","date":"2014-05-07 15:50:51","author":"Tim Skillern","thumbnail":"http:\/\/blog.teamtreehouse.com\/wp-content\/uploads\/2014\/05\/student-computer-class-woodleywonderworks-flickr-150x150.jpg"},{"id":23398,"url":"http:\/\/blog.teamtreehouse.com\/military-veterans-finding-technology-jobs-secure-bet","title":"Technology Jobs a Secure Bet for Military Veterans","date":"2014-05-06 13:45:13","author":"Anayat Durrani","thumbnail":"http:\/\/blog.teamtreehouse.com\/wp-content\/uploads\/2014\/05\/durrani-kopser-150x150.jpg"},{"id":23407,"url":"http:\/\/blog.teamtreehouse.com\/typography-sidebars-style-guides-treehouse-show-ep-89","title":"Typography, Sidebars, Style Guides | The Treehouse Show Ep 89","date":"2014-05-06 10:15:43","author":"Jason Seifer","thumbnail":null},{"id":23393,"url":"http:\/\/blog.teamtreehouse.com\/5-tips-creating-perfect-web-design-portfolio","title":"5 Tips for Creating the Perfect Web Design Portfolio","date":"2014-05-05 17:55:08","author":"Nick Pettit","thumbnail":"http:\/\/blog.teamtreehouse.com\/wp-content\/uploads\/2014\/05\/how-to-make-a-website-150x150.jpg"},{"id":23381,"url":"http:\/\/blog.teamtreehouse.com\/writing-tips-better-business-marketing","title":"11 Rules for Better Writing, or How Not to Use a Thesaurus","date":"2014-05-01 18:38:32","author":"Tim Skillern","thumbnail":"http:\/\/blog.teamtreehouse.com\/wp-content\/uploads\/2014\/05\/pencils-wikimedia-150x150.jpg"},{"id":23387,"url":"http:\/\/blog.teamtreehouse.com\/web-job-perks-unlimited-vacation-catered-lunch-part-amazing-opportunity-weebly-com-programmer","title":"Web Job Perks: Unlimited Vacation, Catered Lunch Part of \u2018Amazing Opportunity\u2019 for Weebly.com Programmer","date":"2014-05-01 17:00:28","author":"Jimmy Alford","thumbnail":"http:\/\/blog.teamtreehouse.com\/wp-content\/uploads\/2014\/05\/weebly-guy0-2-150x150.jpg"},{"id":23375,"url":"http:\/\/blog.teamtreehouse.com\/illustrator-ben-obrien-inspiration","title":"Noted Illustrator Ben O’Brien Talks About Finding Inspiration, Taking Chances","date":"2014-04-29 18:13:58","author":"Gillian Carson","thumbnail":"http:\/\/blog.teamtreehouse.com\/wp-content\/uploads\/2014\/04\/obrien3-150x150.jpg"},{"id":23373,"url":"http:\/\/blog.teamtreehouse.com\/gulp-sketch-3-bud-treehouse-show-episode-88","title":"Gulp | Sketch 3 | Bud | The Treehouse Show Episode 88","date":"2014-04-29 15:29:20","author":"Jason Seifer","thumbnail":null},{"id":23361,"url":"http:\/\/blog.teamtreehouse.com\/flexbox-next-generation-css-layout-arrived","title":"Flexbox: The Next Generation of CSS Layout Has Arrived","date":"2014-04-29 11:53:40","author":"Nick Pettit","thumbnail":"http:\/\/blog.teamtreehouse.com\/wp-content\/uploads\/2014\/04\/Screen-Shot-2014-04-28-at-1.00.03-AM-150x150.png"},{"id":23364,"url":"http:\/\/blog.teamtreehouse.com\/help-wanted-women-color-needed-technology-web-jobs","title":"Help Wanted: Women of Color Needed in Technology, Web Jobs","date":"2014-04-28 12:28:56","author":"Anayat Durrani","thumbnail":"http:\/\/blog.teamtreehouse.com\/wp-content\/uploads\/2014\/04\/poorn
This is where teh error is being caught:
public void updateList() {
if (mBlogData == null) {
// TODO: Handle Error
}
else {
try {
Log.d(TAG, mBlogData.toString(2));
}
catch (JSONException e) {
Log.e(TAG, "Exception Caught", e);
}
}
}
I am not sure what is causing this error so any suggestions are welcome. I can provide more code if needed. Thank You.
Just wanted to add to eMad's answer which helped me solve the same problem you are having. I hope this helps anybody who is to come after me because this darn bug killed 2 hours of my day (or night, I'm nocturnal). Well, with out further (ado? adieu?), here you go : P.S. the below code will go in your private class GetBlogPostsTask AsynnTask...
protected JSONObject doInBackground(Object... arg0) {
int responseCode = -1;
JSONObject jsonResponse = null;
try {
//set API URL
URL blogFeedUrl = new URL("http://blog.teamtreehouse.com/api/get_recent_summary/? count=" + NUMBER_OF_POSTS);
//open URL connection
URLConnection connection = blogFeedUrl.openConnection();
//create BufferedReader to read the InputStream return from the connection
BufferedReader in = new BufferedReader(
new InputStreamReader ( connection.getInputStream() )
);
//initiate strings to hold response data
String inputLine;
String responseData = "";
//read the InputStream with the BufferedReader line by line and add each line to responseData
while ( ( inputLine = in.readLine() ) != null ){
responseData += inputLine;
}
//check to make sure the responseData is not empty
if( responseData!= "" ){
/*initiate the jsonResponse as a JSONObject based on the string values added
to responseData by the BufferedReader */
jsonResponse = new JSONObject(responseData);
}
/*return the jsonResponse JSONObject to the postExecute() method
to update the UI of the context */
return jsonResponse;
}
catch (MalformedURLException e) {
Log.e(TAG, "Exception caught: ", e);
}
catch (IOException e) {
Log.e(TAG, "Exception caught: ", e);
}
catch (Exception e) {
Log.e(TAG, "Exception caught: ", e);
}
return jsonResponse;
}
#Override
protected void onPostExecute(JSONObject result) {
/* set the class' member JSONObject mBlogData to the result
to be used by the handleBlogResponse() method to update the UI */
mBlogData = result;
/*call the handleBlogResponse() method to update the UI with the result of this AsyncTask
which will be a JSONObject in best case scenario or a null object in worst case */
handleBlogResponse();
}
A friend of mine brought me a code that was generating the same output as yours. I think this is the solution that you're looking for. Given code is
// inside the class which connects to URL (Probably MainList)
InputStream inputStream = connection.getInputStream();
Reader reader = new InputStreamReader(inputStream);
int contentLength = connection.getContentLength();
char[] charArray = new char[contentLength];
reader.read(charArray);
String responseData = new String(charArray);
jsonResponse = new JSONObject(responseData);
But don't know why using above code, you either not get the full string or get the ContentLenght right but the last few characters aren't received properly. Use following code instead which reads complete response:
URLConnection yc = blogFeedUrl.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
responseData = "";
while ((inputLine = in.readLine()) != null) // read till you can receive any data
responseData += inputLine;
in.close();

Handling HTTP Get/ Delete Android using REST

I m implementing a REST based HTTP server in Android. The server responds for GET, DELETE and POST requests. Two android devices communicate using HTTP Post (I m using a service, where a device keeps listening on a port and post to next device and this keeps going on).
I m testing the GET and DELETE using Mozilla Poster. Should I add a separate socket/port to handle the same? Because when I try now, sometimes I get timeout error or no response found. However, I am able to see server response in Logcat window. Please help me.
Code to handle GET request:
if(method.equals("GET"))
{
if(checkFileExisting())
{
BufferedReader reader = new BufferedReader(new FileReader(new File(getFilesDir()+File.separator+"script.json")));
String read;
StringBuilder builder = new StringBuilder("");
while((read = reader.readLine()) != null)
{
builder.append(read);
}
String JSONContents = builder.toString();
reader.close();
JSONObject jsonObject;
try {
jsonObject = new JSONObject(JSONContents);
String name = jsonObject.getString("name");
JSONObject stateObject = jsonObject.getJSONObject("state");
String stateValue = stateObject.getString("value");
if(name.equals(target))
{
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");
response.setEntity(new StringEntity("State is:" + stateValue));
conn.sendResponseHeader(response);
conn.sendResponseEntity(response);
}
else
{
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 404, "Not Found");
response.setEntity(new StringEntity("The requested resource " + target + " could not be found due to mismatch!!"));
conn.sendResponseHeader(response);
conn.sendResponseEntity(response);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else
{
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 404, "Not Found");
response.setEntity(new StringEntity("The requested resource " + target + " could not be found!!"));
conn.sendResponseHeader(response);
conn.sendResponseEntity(response);
}
}
The link http://www.integratingstuff.com/2011/10/24/adding-a-webserver-to-an-android-app/ has a very good example. I missed conn.close() in my code.

How to put image attachment to CouchDB in Android?

I am use HttpClient and mime to put the image file from Android client to CouchDB.
But there are some error message like this
D/FormReviewer(4733): {"error":"bad_request","reason":"invalid UTF-8 JSON: <<45,45,103,75,66,70,69,104,121,102,121,106,72,66,101,80,\n
here is my code
final String ProfileBasicID = UUID.randomUUID().toString();
Data.postImage(IconFile, "http://spark.iriscouch.com/driver/"+ProfileBasicID,new Callback<String>())
public static void postImage(File image,String url, Callback<String> success ) throws IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPut method = new HttpPut(url);
try {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("type", new StringBody("photo"));
entity.addPart("form_file", new FileBody(image, "image/jpeg"));
method.setEntity(entity);
HttpResponse resp = httpclient.execute(method);
Log.d("httpPost", "Login form get: " + resp.getStatusLine());
StatusLine statusLine = resp.getStatusLine();
Log.d(tag, statusLine.toString());
if (entity != null) {
entity.consumeContent();
}
switch(resp.getStatusLine().getStatusCode()){
case HttpStatus.SC_CREATED:
success.call(EntityUtils.toString(resp.getEntity()));
break;
default:
throw new ClientProtocolException(statusLine.toString() +"\n"+ EntityUtils.toString(resp.getEntity()));
}
} catch (Exception ex) {
Log.d("FormReviewer", "Upload failed: " + ex.getMessage() +
" Stacktrace: " + ex.getStackTrace());
} finally {
// mDebugHandler.post(mFinishUpload);
httpclient.getConnectionManager().shutdown();
}
}
Please give me a hand,Thanks
RIGHT, forget what I posted here previously.
This is NOT as straightforward as we thought.
Some links I suggest you read:
CouchDB Document API
(Draft) Core API
Ok.
First decision is if you want "Standalone" or "inline attachments". Currently I don't know what the Pro's and Con's are, BUT based on your code, and what I did, we will go for "Standalone".
Firstly, you need the rev (revision) number of the document you want to attach your image to. As per the above link, do this by doing a Head request on that doc:
private String getParentRevision(String uuid, HttpClient httpClient) {
String rev = "";
try {
HttpHead head = new HttpHead("http://192.168.56.101/testforms/" + uuid + "/");
HttpResponse resp = httpClient.execute(head);
Header[] headers = resp.getAllHeaders();
getLog().debug("Dumping headers from head request");;
for (Header header : headers) {
getLog().debug(header.getName() + "=" + header.getValue());
if ("Etag".equals(header.getName())) {
StringBuilder arg = new StringBuilder(header.getValue());
if (arg.charAt(0) == '"') {
arg.delete(0, 1);
}
if (arg.charAt(arg.length()-1) == '"'){
arg.delete(arg.length()-1, arg.length());
}
rev = arg.toString();
break;
}
}
} catch (Exception ex) {
getLog().error("Failed to obtain DOC REV!", ex);
}
return rev;
}
I appologise for the hardcoding etc, I'm learning and experimenting here ;)
The "uuid" parameter is the UUID of the target document.
Note the removal of the wrapping '"' characters when we got the Etag (yes, the Etag header is the revision number).
THEN, when we got that, we can actually send the image:
String serveURL = "http://192.168.56.101/testforms/" + data.getString(PARENT_UUID) + "/" + imgUuid;
if (docRev != null && !docRev.trim().isEmpty()) {
//This is dumb...
serveURL += "?rev=" + docRev + "&_rev=" + docRev;
}
HttpPut post = new HttpPut(serveURL);
ByteArrayEntity entity = new ByteArrayEntity(imageData);
entity.setContentType(data.getString(MIME_TYPE));;
post.setEntity(entity);
HttpResponse formServResp = httpClient.execute(post);
With this, I was able to attache images to my docs ;)
As mentioned, please be aware that I'm also new to CouchDB, so there might be simpler ways to do this!
Something I just discovered now (but should have spotted earlier) is that there is the potential of a race condition here, if, for example, multiple clients are trying to attach images to the same document simultaneously. The reason is that the rev value changes with each change to the document.
In such a case, you will get a reply from the server like
{"error":"conflict","reason":"Document update conflict."}
Easiest solution is to just retry in such a case, until it works, or until a self imposed error limit is hit...
Cheers!

Android connectivity with MySQL

I am developing a final year project where I need to connect Android emulator with MySQL database in order to retrieve values. Java file:
public class connectivity extends Activity {
/** Called when the activity is first created. */
TextView txt;
public static final String KEY_121 = "http://10.0.2.2/mysqlcon.php";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout rootLayout = new LinearLayout(getApplicationContext());
txt = new TextView(getApplicationContext());
rootLayout.addView(txt);
setContentView(rootLayout);
// Set the text and call the connect function.
txt.setText("Connecting...");
// call the method to run the data retreival
txt.setText(getServerData(KEY_121));
}
private String getServerData(String returnString) {
InputStream is = null;
String result = null;
// the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year", "1970"));
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(KEY_121);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
Log.i("log_tag", "id: " + json_data.getInt("id") + ", name: " + json_data.getString("name") + ", sex: " + json_data.getInt("sex") + ", birthyear: " + json_data.getInt("birthyear"));
// Get an output to the screen
returnString += "\n\t" + jArray.getJSONObject(i);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return returnString;
}
}
I have also given an internet permission in my Android manifest file. But after running the application I get the following error in logcat:
ERROR PARSING DATA org.json.JSONException:A JSONArraytext must start with '[' at character 0
I think this goes to show that a null value is being returned. Please help me out as this is my final year project. I have spent hours trying to find the solutions but it has been of no use.
I am currently using Android 2.2. The wamp server is on the localhost so I am using the address 10.0.2.2 which is a special alias to localhost (127.0.0.1). Any help will be really appreciated.
Here is the PHP code:
<?php
mysql_connect("127.0.0.1","root","chetan");
mysql_select_db("db1");
$q=mysql_query("SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output,JSON_FORCE_OBJECT));
mysql_close();
This is actually an issue I've run into before. The problem is your server isn't outputting valid JSON. It's missing some of the markup. I suggest you print the raw text of the response to Logcat and examine it. Perhaps even pass it into a JSON validator. That will also help you figure out if it is returning an empty value. If it's returning an empty value, then you'll need to debug your server...not your client...
Additionally, try visiting the php page from your browser and letting it simply display the JSON response. This will allow you to see what's being written by the server and help you determine where the problem really is. Just be aware, because the server is expecting a POST the easiest way to test this would probably to be to create a simple html form to POST the test data to that page. Without doing that, getting a browser to do a POST on it's own can be a pain.
do u need to use connection to php??? if not you can directly connect to mysql db to retrieve the result:
// Assume function to be :
public String customerData() {
String customerInfo = ""; //To store result
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection(
"jdbc:mysql://10.0.2.2:3306/retailer","root","pswrd");
PreparedStatement statement = con.prepareStatement("SELECT * FROM customers");
ResultSet result = statement.executeQuery();
while(result.next()) {
customerInfo = customerInfo + result.getString("name") + "&" +
result.getString("C_ID") + "&" + result.getString("address") +
"&" + result.getString("email");
// Here "&"s are added to the return string. This is help to split the
// string in Android application
}
} catch(Exception exc) {
System.out.println(exc.getMessage());
}
return customerInfo;
}
But to your project library include Connector jar file for Mysql.

Categories

Resources