Hi i have a problem with display data from my database on my app
That's part of Java file
#Override
protected String doInBackground(String... params)
{
String result ="";
String host = "http://192.168.0.12/LoginRegister/workelectricallist.php";
try
{
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(host));
HttpResponse response = client.execute(request);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer stringBuffer = new StringBuffer("");
String line = "";
while ((line = reader.readLine()) != null)
{
stringBuffer.append(line);
break;
}
reader.close();
result = stringBuffer.toString();
}
catch (Exception e)
{
return new String("There exception: " + e.getMessage());
}
return result;
}
#Override
protected void onPostExecute(String result)
{
try
{
Toast.makeText(getApplicationContext(),"1 enter", Toast.LENGTH_SHORT).show();
JSONObject jsonResult = new JSONObject(result);
int success = jsonResult.getInt("success");
if (success == 1)
{
Toast.makeText(getApplicationContext(),"2 enter", Toast.LENGTH_SHORT).show();
JSONArray ad = jsonResult.getJSONArray("ad");
for(int i=0; i < ad.length(); i++)
{
JSONObject object = ad.getJSONObject(i);
int id = object.getInt("id");
String user_name = object.getString("user_name");
String NameAd = object.getString("NameAd");
double Content = object.getDouble("Content");
String TypeOfAd = object.getString("TypeOfAd");
String line = id + "-" + user_name + "-" + NameAd + "-" + Content + "-" + TypeOfAd;
adapter.add(line);
}
}
else
{
Toast.makeText(getApplicationContext(),"No Ad to display", Toast.LENGTH_SHORT).show();
}
}
catch (JSONException e)
{
Toast.makeText(getApplicationContext(),e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
php file take data from MySQL data base, i can see array of data on a broswer
but on my app, i can see only "1 enter" and "no value for a success"
Like it didn't go to if, but there is no "No ad to display" so it didnt go to else
That's php file
<?php
$host ='localhost';
$user ='root';
$pwd ='';
$db ='loginregister';
$conn = mysqli_connect($host, $user, $pwd, $db);
if(!$conn)
{
die("Error in connection" . $mysqli_connect_error());
}
$response = array();
$sql_query = "select *from ad";
$result = mysqli_query($conn, $sql_query);
if(mysqli_num_rows($result) > 0)
{
$response['succes'] = 1;
$ad = array();
while ($row = mysqli_fetch_assoc($result))
{
array_push($ad, $row);
}
$response['ad'] = $ad;
}
else
{
$response['succes']=0;
$response['succes']='no data';
}
echo json_encode($response);
mysqli_close($conn);
?>
Using a local service you also need to see your development environment. If the app runs on the same machines where the site is hosted there should be no problem. If, on the other hand, the app is used externally, the error may be caused by the http request not being able to get a response because it does not know who to ask for the response.
I invite you to analyze the try and catch since there is the error "no value for a success". It is very likely that the result string do not get readed correctly or is not in a json format and because of that sends you the exception.
By googling "JSONException no value for" it possible to find extra information about this kind of issue like Android - JSONException No value for
Related
I have the following function in my Android app:
void sendEmail(String PHPfileUurl, String receiverEmail, String fromEmail) {
ParseUser currentUser = ParseUser.getCurrentUser();
StringBuilder messageBuilder = new StringBuilder();
for (int i=0; i<productsOrdered.size(); i++){
messageBuilder.append(productsOrdered.get(i)).append("\n");
}
String mess = messageBuilder.toString();
String parameters = "name=" + currentUser.getString(Configurations.USER_FULLNAME) +
"&fromEmail=" + fromEmail +
"&receiverEmail=" + receiverEmail +
"&messageBody=" + mess +
"&storeName=" + Configurations.MERCHANT_NAME +
"&shippingAddress=" + currentUser.getString(Configurations.USER_SHIPPING_ADDRESS);
String strURL = PHPfileUurl + parameters;
strURL = strURL.replace(" ", "%20");
strURL = strURL.replace("\n", "%20");
Log.i(Configurations.TAG, "PHP STRING URL: " + strURL);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
URL url;
url = new URL(strURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(20000);
conn.setReadTimeout(20000);
conn.setDoInput(true);
conn.setDoOutput(true);
if( conn.getResponseCode() == HttpURLConnection.HTTP_OK ){
InputStream is = conn.getInputStream();
Log.i(Configurations.TAG, "EMAIL RESPONSE: " + conn.getResponseMessage());
} else {
InputStream err = conn.getErrorStream();
Log.i(Configurations.TAG, "ERROR ON EMAIL: " + err);
}
} catch (IOException e) {e.printStackTrace(); }
}
When I call that function the Logcat prints out this message:
I/log-: PHP STRING URL: http://example.com/myapp/email-admin.php?name=Mark%20Doe&fromEmail=myemail#gmail.com&receiverEmail=admin#mydomain.com&messageBody=PRODUCT%20ID:%20Q3nQgZdlFG%20---%20PRODUCT:%20Nike%20Sport%20Shoes%20black%20%20---%20QUANTITY:%201%20---%20SIZE:%20L%20&storeName=Z%20Store%20Inc.&shippingAddress=John%20Doe,%20121%20Church%20Avenue,%20ASD123,%20London,%20UK
I/log-: EMAIL RESPONSE: OK
So I assume everything is fine since the RESPONSE = OK. But it's not, because I will not receive any email at admin#mydomain.com (there is another email address, I've posted a fake one just as an example, the Logcat prints out my real email address as receiverEmail).
Here's my mail.php file:
// POST Variables
$name = $_POST['name'];
$fromEmail = $_POST['fromEmail'];
$receiverEmail = $_POST['receiverEmail'];
$messageBody = $_POST['messageBody'];
$storeName = $_POST['storeName'];
$shippingAddress = $_POST['shippingAddress'];
$headers = 'From: ' .$fromEmail;
// SUBJECT
$subject = "New order from " .$name. " on '" .$storeName. "'";
// COMPOSE MESSAGE
$message =
"ORDER DETAILS:\n".
$messageBody.
"\n\nName: " .$name.
"\nUser Email: " .$fromEmail.
"\nShipping Address: " .$shippingAddress
;
/* Finally send email */
mail($receiverEmail,
$subject,
$message,
$headers
);
/* Result */
echo "Email Sent to: " .$receiverEmail. "\n Message: " .$message;
Does my code have something wrong? is there another way to call a mail.php file from my own server? I've also tried this question, but I cannot import the DefaultHttpClient class in my project.
it's would be easier if you change the $_POST to $_GET
but the problem in the $_GET method if the message have (&something=) inside
it you will receive only half the message as the &something= would be set to an other $_GET , Also you might get some problems if the message is too long ,
so if you want to use the $_POST method instead of the $_GET
you need to change your java code ,
make sure to import Map and then change it to this
void sendEmail(String PHPfileUurl, String receiverEmail, String fromEmail) {
ParseUser currentUser = ParseUser.getCurrentUser();
StringBuilder messageBuilder = new StringBuilder();
for (int i=0; i<productsOrdered.size(); i++){
messageBuilder.append(productsOrdered.get(i)).append("\n");
}
String mess = messageBuilder.toString();
Map<String,Object> params = new LinkedHashMap<>();
params.put("name", currentUser.getString(Configurations.USER_FULLNAME));
params.put("fromEmail", fromEmail);
params.put("receiverEmail", receiverEmail);
params.put("messageBody", mess);
params.put("storeName", Configurations.MERCHANT_NAME);
params.put("shippingAddress", currentUser.getString(Configurations.USER_SHIPPING_ADDRESS);
StringBuilder postData = new StringBuilder();
for (Map.Entry<String,Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append('&');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
String strURL = PHPfileUurl;
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
URL url;
url = new URL(strURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(20000);
conn.setReadTimeout(20000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
if( conn.getResponseCode() == HttpURLConnection.HTTP_OK ){
InputStream is = conn.getInputStream();
Log.i(Configurations.TAG, "EMAIL RESPONSE: " + conn.getResponseMessage());
} else {
InputStream err = conn.getErrorStream();
Log.i(Configurations.TAG, "ERROR ON EMAIL: " + err);
}
} catch (IOException e) {e.printStackTrace(); }
}
Use $_GET instead of $_POST ,
change all variable from
$name = $_POST['name'];
to
$name = $_GET['name'];
I am trying to get data from MySQL database to my android app using where condition. I already create a method for get data. This method give me all data as a string array from a single column.
Look the bellow method :
String adress = "http://myserver_link/get_data.php";
InputStream inputStream = null;
String line = null, result = null, data[];
private void get_data(){
try {
URL url = new URL(adress);
HttpURLConnection httpsURLConnection = (HttpURLConnection) url.openConnection();
httpsURLConnection.setRequestMethod("GET");
inputStream = new BufferedInputStream(httpsURLConnection.getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// read input stream into a string
try{
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null){
stringBuilder.append(line + "\n");
}
inputStream.close();
result = stringBuilder.toString();
}
catch (Exception e) {
e.printStackTrace();
}
// Parse json data
try{
JSONArray jsonArray = new JSONArray(result);
JSONObject jsonObject = null;
data = new String[jsonArray.length()];
for (int i=0; i<jsonArray.length(); i++){
jsonObject = jsonArray.getJSONObject(i);
data[i] = jsonObject.getString("user_adress"); // column name
}
}
catch (Exception e){
e.printStackTrace();
}
}
This is my get data java method. And my get_data.php code is :
<?php
require "conn.php";
$query = mysqli_query($conn, "select * from android_data");
if ($query) {
while ($row = mysqli_fetch_array($query)) {
$flag[] = $row;
}
print(json_encode($flag));
}
$conn->close();
?>
Now I want to write my get_data.php file like bellow :
<?php
require "conn.php";
$user_name = $_POST["username"];
$query = mysqli_query($conn, "select * from android_data where username='$user_name'");
if ($query) {
while ($row = mysqli_fetch_array($query)) {
$flag[] = $row;
}
print(json_encode($flag));
}
$conn->close();
?>
But how I can send username using get_data() java method from my app?
You should probably send this as a parameter on the URL...
String adress = "http://myserver_link/get_data.php?username=xxxxx";
Not done Java for a while, but you can create this string using the appropriate value for xxxxx.
This will then be passed in as $_GET["username"] instead of $_POST["username"]. So just replace this line
$user_name = $_POST["username"];
with
$user_name = $_GET["username"];
Or you can change the Request method to POST in your Java code.
I'm trying to connect Android json output with Ruby web application.
I'm having difficulty to connect Android json post request with receiving from Ruby app. When Android jsonobject has another jsonobject inside, it is not recognised in the ruby app. Here is my code.
Android Code
JSONObject events_array = new JSONObject();
JSONObject parent=new JSONObject();
for (int i = 0; i < classtimeList.size(); i++) {
events_array.put(classtimeList.get(i).toString(),priorityList.get(i).toString());
}
parent.put("token","token_information");
parent.put("class_type", "something");
parent.put("class_frequency", "5");
parent.put("course_id", "20");
parent.put("events_array", events_array);
String urlParameters = "info="+parent.toString();
Log.i("parameters", urlParameters);
This is a log info for parameters.
info={"token":"token_information","class_type":"something","class_frequency":"5","course_id":"20","events_array":{"3074":"3","3134":"1","3140":"1","3146":"3","3152":"1","3075":"3","3076":"3","3077":"3","3078":"3","3079":"3","3216":"3","3217":"3","3218":"1","3219":"3"}}
I pass this information to Ruby app and I am having difficulty to extract "events_array" information. Below is my Ruby Code.
My full Android code looks like
class apply extends AsyncTask<String, String, String> {
ProgressDialog pd;
private Exception exception;
protected void onPreExecute() {
pd = new ProgressDialog(ClassApply2.this);
pd.setMessage("loading");
pd.show();
}
protected String doInBackground(String... args) {
String token = args[0];
try {
URL url = new URL("https://www.ringleplus.com/api/v1/apply/test");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
JSONObject events_array = new JSONObject();
JSONObject parent=new JSONObject();
for (int i = 0; i < classtimeList.size(); i++) {
events_array.put(classtimeList.get(i).toString(),priorityList.get(i).toString());
}
parent.put("token","token_information");
parent.put("class_type", "something");
parent.put("class_frequency", "5");
parent.put("course_id", "20");
parent.put("events_array", events_array);
connection.setRequestMethod("POST");
connection.setDoOutput(true);
String urlParameters = "info=" + parent.toString();
DataOutputStream dStream = new DataOutputStream(connection.getOutputStream());
dStream.writeBytes(urlParameters);
//dStream.write(data); // <!-- 여기에 url parameter가 들어감
dStream.flush();
dStream.close();
Log.i("parameters", parent.toString());
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line).append("\n");
}
reader.close();
connection.disconnect();
JSONObject jsonObj = null;
jsonObj = new JSONObject(buffer.toString().trim());
String output = jsonObj.getString("item");
return output;
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if(response == null) {
response = "THERE WAS AN ERROR";
}
//progressBar.setVisibility(View.GONE);
Log.i("INFO", response);
if (pd != null) {
pd.dismiss();
}
adapter.notifyDataSetChanged();
}
Ruby Code
post :test do
parsed_json = ActiveSupport::JSON.decode(params[:info].to_json)
token = parsed_json["token"]
events_array = parsed_json["events_array"]
output = Array.new
if events_array != nil
events_array.each do |start_time, priority|
if priority.to_i == 1 || priority.to_i == 2
userapply = Userapply.new
userapply.classtime_id = start_time
userapply.user_id = user.id
userapply.priority = priority
userapply.save
output << {:userapply_id => userapply.id, :classtime_id => userapply.classtime_id, :user_id => userapply.user_id, :priority => userapply.priority}
end
end
end
return {status: 'ok', item: events_array}
end
What it supposed to be returned is the information about events_array (i.e. {"3074":"3","3134":"1","3140":"1","3146":"3","3152":"1","3075":"3","3076":"3","3077":"3","3078":"3","3079":"3","3216":"3","3217":"3","3218":"1","3219":"3"} )
but, the Android output log is
I/INFO: events_array
but the token extraction seems working.
token = parsed_json["token"]
If this works, then my gut feeling is parsed_json["events_array"] also should work in some sense. But I'm not stuck here.
If this is resolved, then I want to receive parsed_json["events_array"] as a hash information and want to process the full code and get the "output" instead of events_array to check why this doesn't work.
Please let me know if there is anything I'm missing. I really need some help.
Looking forward to seeing anyone's reply.
I finally figured out where the problem came from. I compared what you send to your server with curl in comment above, and what you try to send from android. And these two things are completly difirent. To send the same from androdid, you should form your urlParameter like that:
JSONObject info = new JSONObject();
info.put("info",parent);
urlParameters = info.toString();
And don't forget to do connection.setRequestProperty("Content-Type", "application/json") after connection.setDoOutput(true).
I tested it outside android, and it returned pretty the same as curl command from your comment above. It should work just fine in android.
PS: Please, be more more attentive next time.
I am trying to make a post request using the reference of this documentation. But the problem is that the PHP developer at the other end is not able to receive the value of the parameter hence is not able to send a proper response. Am I missing something out here.
// Edits ;
I am making a HTTP Post request. As you can seen the code below. I am writing the arguments and parameters (location_id=3) to the outputstream. I have also pasted the code for PHP which i have been using. Now the problem is:
The parameter value ( which is 3 ) is not received at the PHP code so I am getting a response which is surrounded by the else block. So I just want to know if there is an error in the android code or the PHP code
#Override
protected Boolean doInBackground(String... params) {
Log.d(Constants.LOG_TAG,Constants.FETCH_ALL_THEMES_ASYNC_TASK);
Log.d(Constants.LOG_TAG," The url to be fetched "+params[0]);
try {
url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
// /* optional request header */
// urlConnection.setRequestProperty("Content-Type", "application/json");
//
// /* optional request header */
// urlConnection.setRequestProperty("Accept", "application/json");
/* for Get request */
urlConnection.setChunkedStreamingMode(0);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("POST");
List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>();
nameValuePairs.add(new BasicNameValuePair("location_id",params[1]));
outputStream = urlConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
bufferedWriter.write(writeToOutputStream(nameValuePairs));
int statusCode = urlConnection.getResponseCode();
/* 200 represents HTTP OK */
if (statusCode == 200) {
inputStream = new BufferedInputStream(urlConnection.getInputStream());
response = convertInputStreamToString(inputStream);
Log.d(Constants.LOG_TAG, " The response is " + response);
return true;
}
else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(inputStream != null){
inputStream.close();
}
if(outputStream != null){
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
// Here is the code for writeToOutputStream
public String writeToOutputStream(List<BasicNameValuePair> keyValuePair)throws UnsupportedEncodingException{
String result="";
boolean firstTime = true;
for(BasicNameValuePair pair : keyValuePair){
if(firstTime){
firstTime = false;
}
else{
result = result.concat("&");
}
result = result + URLEncoder.encode(pair.getKey(), "UTF-8");
result = result + "=";
result = result+ URLEncoder.encode(pair.getValue(),"UTF-8");
}
Log.d(Constants.LOG_TAG," The result is "+result);
return result;
}
// Here is the code for convertInputStream to String
public String convertInputStreamToString(InputStream is) throws IOException {
String line="";
String result="";
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
while((line = bufferedReader.readLine()) != null){
Log.d(Constants.LOG_TAG," The line value is "+line);
result += line;
}
/* Close Stream */
if(null!=inputStream){
inputStream.close();
}
return result;
}
Here is the PHP CODE
<?php
include 'config.php';
header ('Content-Type:application/json');
if(isset($_POST['location_id']))
{
$id=$_POST['location_id'];
$selectThemeQuery = mysql_query("select theme_id from location_theme where location_id='$id'",$conn) or die (mysql_error());
$noRows = mysql_num_rows($selectThemeQuery);
//echo "HI";
if($noRows > 0)
{
$result = array();
while($row = mysql_fetch_assoc($selectThemeQuery))
{
$themeid = $row['theme_id'];
//echo "HI";
$selectNameQuery = mysql_query("select theme_name,theme_image from theme where theme_id='$themeid'",$conn) or die(mysql_error());
$numRows = mysql_num_rows($selectNameQuery);
if($numRows > 0)
{
while($rows = mysql_fetch_assoc($selectNameQuery))
{
$name = $rows['theme_name'];
$image = $rows['theme_image'];
$result[] = array('theme_id'=>$themeid,'theme_name'=>$name, 'theme_image'=>$image);
}
}
}
//echo json_encode($result);
echo json_encode("Hi");
}
else
{
$data2[] = array('Notice'=>false);
echo json_encode($data2);
}
}
else
{
echo "Not Proper Data";
}
?>
Remove:
urlConnection.setChunkedStreamingMode(0);
You use a buffered writer so it can only buffer instead of write.
To force all been written:
bufferedWriter.write(writeToOutputStream(nameValuePairs));
bufferedWriter.flush();
And then ask for a response code. And don't call a response code a status code.
writeToOutputStream() ??? What a terrible name. That function does not write to an output stream. It justs makes a text string.
For Android, I would suggest using a library like Spring-Android.
Spring-Android contains a RestTemplate class, which is a quite effective REST-Client. For example, a simple POST request would be...
myRestTemplate.exchange("http://www.example.net", HttpMethod.POST, new HttpEntity( ...some JSON string ...), String.class );
To create the JSON String, I suggest a library like Jackson, which should work fine on Android, see for example here. Not sure if Jackson integrates as fine in Spring-Android as it does in Spring-Web, but in any case, using it to create the Json Strings manually should work just fine.
for post method
create a string builder first
StringBuilder strbul=new StringBuilder();
then append the data like
strbul.append("name=sangeet&state=kerala");
then write to output stream like
httpurlconnection.getOutput().write(strbul.toString().getBytes("UTF-8"));
php script will recieve that data on
$_POST['name'] and $_POST['state']
I try to query Sugar through its REST API using Java for entries in Meetings module for a specific user, namely the one who is logged in currently.
I am trying this a few days already while googling around for asolution.
I made a login() call, where I got a session ID, than I make a call to get_user_id(). With the returned user ID I try to query the Meetings module by using get_entry_list().
To get the Meetings assigned to the UserID it works with following query string, where mUserId holds the returned user id of get_user_id():
queryString = "meetings.assigned_user_id='"+mUserId+"'";
But I not only want to get the meetings, where a user is assigned to, but all Meetings where he participates. For that I try a subquery on meetings_users table in my query.
Here is a query strings I tried, which os working on MySQL prompt. But when I try this over REST, it returns "Invalid Session ID":
queryString = "meetings.id IN ( SELECT meetings_users.meeting_id FROM meetings_users WHERE meetings_users.user_id = '"+mUserId+"' )";
Does anyone have a hint on this? Which conditions lead to an "Invalid Session ID" at all?
What also does not work e.g. is appending "and deleted = '0'" to the first stated query:
queryString = "meetings.assigned_user_id='"+mUserId+"' and deleted = '0'";
also fails.
As requested here is the full code example, platform is Android, API Level 8:
private JSONArray getEntryList(String moduleName,
String selectFields[], String queryString, String orderBy, int max_results) throws JSONException, IOException, KeyManagementException, NoSuchAlgorithmException
{
JSONArray jsoSub = new JSONArray();
if (selectFields.length > 0)
{
for (int i = 0; i < selectFields.length; i++)
{
jsoSub.put(selectFields[i]);
}
}
// get_entry_list expects parameters to be ordered, JSONObject does
// not provide this, so I built my JSON String on my own
String sessionIDPrefix = "{\"session\":\""+ mSessionId+ "\"," +
"\"modulename\":\""+ moduleName+ "\"," +
"\"query\":\""+ queryString + "\"," +
"\"order_by\":\""+ orderBy + "\"," +
"\"offset\":\""+ mNextOffset+ "\"," +
"\"select_fields\":["+ jsoSub.toString().substring(
1, jsoSub.toString().length()-2)+ "\"],"+
"\"max_results\":\""+ 20 + "\"}";
String restData = sessionIDPrefix;
Log.d(TAG, restData);
String data = null;
String baseurl = mUrl + REST_URI_APPEND;
data = httpPost(baseurl+"?method=get_entry_list&input_type=json&response_type=json&rest_data="+restData);
Log.d(TAG, data);
JSONObject jsondata = new JSONObject(data);
mResultCount = jsondata.getInt("result_count");
mNextOffset = jsondata.getInt("next_offset");
return jsondata.getJSONArray("entry_list");
}
private String httpPost(String urlStr) throws IOException{
String urlSplitted [] = urlStr.split("/", 4);
String hostPort[] = urlSplitted[2].split(":");
String hostname = hostPort[0];
int port = 80;
if (hostPort.length > 1)
port = new Integer(hostPort[1]);
String file = "/"+urlSplitted[3];
Log.d(TAG, hostname + ", " + port + ", " +file);
URL url = null;
try {
url = new URL("http", hostname, port, file);
} catch (MalformedURLException e) {
throw new IOException(mContext.getText(R.string.error_malformed_url).toString());
}
Log.d(TAG, "URL "+url.toString());
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
throw new IOException(mContext.getText(R.string.error_conn_creat).toString());
}
conn.setConnectTimeout(60 * 1000);
conn.setReadTimeout(60 * 1000);
try {
conn.setRequestMethod("POST");
} catch (ProtocolException e) {
throw new IOException(mContext.getText(R.string.error_post).toString());
}
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
try {
conn.connect();
} catch (IOException e) {
throw new IOException(mContext.getText(R.string.error_conn_open).toString()
+ "\n" + e.getMessage());
}
int response = 0;
String responseMessage = null;
try {
response = conn.getResponseCode();
responseMessage = conn.getResponseMessage();
} catch (IOException e) {
conn.disconnect();
throw new IOException(mContext.getText(R.string.error_resp_io).toString());
}
Log.d(TAG, "Exception Response "+ response);
if (response != 200) {
conn.disconnect();
throw new IOException(mContext.getText(R.string.error_http).toString()
+ "\n" + response + " " + responseMessage);
}
StringBuilder sb = null;
try {
BufferedReader rd = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
Log.d(TAG,"line " + line);
sb.append(line);
}
rd.close();
} catch (IOException e) {
conn.disconnect();
throw new IOException(mContext.getText(R.string.error_resp_read).toString());
}
conn.disconnect();
if (sb.toString() == null)
{
throw new IOException(mContext.getText(R.string.error_resp_empty).toString());
}
return sb.toString();
}
Calling the code above:
if (login() != OK)
return null;
mResultCount = -1;
mNextOffset = 0;
mUserId = getUserId();
String fields[] = new String [] {
"id",
"name",
"description",
"location",
"date_start",
"date_end",
"status",
"type",
"reminder_time",
"parent_type",
"parent_id",
"deleted",
"date_modified"
};
String queryString = null;
if (syncAllUsers)
queryString = "";
else
{
queryString = "meetings.assigned_user_id = 'seed_sarah_id' and meetings.deleted = '0'";
//queryString = "meetings.id IN ( SELECT meeting_id FROM meetings_users WHERE user_id ='"+mUserId+"'";
}
entryList.clear();
while (mResultCount != 0)
{
if (!seamless_login())
return null;
JSONArray serverEntryList = getEntryList(
"Meetings", fields, queryString, "date_start", 0);
//... do sth with data
}
totalContactsResults += mResultCount;
}
logout();
login() returns valid session id, and getUserId() returns right id. The whole code is already working for fetching contacts, and also working for a simple query as stated above.
Thanks in advance
Marc
After further testing, I realized, that whitespaces in the query string are the problem. They lead to an URL containing whitespace. To avoid that some kind of URL encoding has to be done.
I had not success in encoding the whole URL in my httpPost methods (seems not to be necessary). But replacing spaces with '+' in the query string works for me:
queryString = "meetings.id+IN+(SELECT+meetings_users.meeting_id+FROM meetings_users+WHERE+meetings_users.user_id='"+mUserId+"')";
If anyone has a more elegant method of doing this, please let me know.
You would probably be better off using the get_relationships web service call.
SugarRest.call('get_relationships', [SugarRest.session, 'Users', SugarRest.user_id, 'meetings', '', ['name'], 0, ''])
That should be all you need. In the parameter after 'meetings' you can also pass in an additional filter.