Is it possible to check on startup of an Android app whether the user has the latest version of it and force him to update if he has not? Or at least checkt whether there is a new version and tell him, that the app only will work again when he downloads and installs the update?
Background is that I have an app that needs to communicate with a server. When I change something in the interface between server and client I want to assure that the client has the latest version.
Is there any native way to do this? Or do I have to check this on my own?
Is this only accessible if you have a mysql database? is it possible to do this with just plain text on a webpage and have it checked with the current app version?
is it possible to do this with just
plain text on a webpage and have it
checked with the current app version?
That's what I would do:
Checking latest version on your server, in a text file:
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
String latestVersion = "";
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
str.append(line);
}
in.close();
latestVersion = str.toString();
and then compare it to the installed version:
private String getSoftwareVersion() {
try {
PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
return packageInfo.versionName;//EDIT: versionCode would be better
} catch (PackageManager.NameNotFoundException e) {
Log.e(TAG, "Package name not found", e);
};
}
Related
I have following code where I am calling an API which is a PHP built. The code returns json stated as below which I am collecting in a stringBuilder object. Problem is its working on some carriers and on few devices with other carriers / wifi connection its throwing JSONException end of input at character 0 exception, i know this comes when input string is empty, it means stringBuilder object is empty. Problem is i don't have access to the devices on which its throwing these errors.
I am not getting on some device why following code returns empty string and on some its working fine, user has tested on 3G as well as wifi these devices are in other country on different carriers.
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost postRequest = new HttpPost(ServiceUrls.base_url + ServiceUrls.get_profile_url);
JSONObject object = new JSONObject();
object.put("username", params[0]);
StringEntity input = new StringEntity(object.toString());
input.setContentType("application/json");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String output;
StringBuilder stringBuilder = new StringBuilder();
while ((output = br.readLine()) != null) {
stringBuilder.append(output);
}
If it was for all API call then it was logical but doest happen for other API call, this API call returns bigger size JSON string as follows in stringbuilder
{
"status":1,
"parking":{
"name":"ghgjjghghg",
"cost":3,
"ownerId":29,
"address":"xyz pqr",
"slots":4,
"image":"d4bc95c1dd031685746f2c3570788acf.jpg",
"details":"gjhjghjgg",
"amenities":"gjhg",
"id":70,
"lon":73.7898023,
"lat":19.9974533,
"type":0,
"available":1
},
"rating":0,
"ratingCount":0,
"owner":{
"id":29,
"username":"vd#gmail.com",
"password":"",
"fullname":"vi hdjh",
"phone":"23434fddf",
"ccNum":null,
"ccType":null,
"type":1,
"authType":1,
"image":"582e3a77d76ae3203cfd6d6a346da429.jpg",
"dni":"abc123",
"account":"ABCBANK"
}
}
I have no clue whats happening , please help. Any input will be appreciated.
There is nothing unusual about the code you posted. No clues there.
Let me summarize what I think you said about the symptoms.
For some devices / carriers, a specific API call fails. But not all devices / carriers.
For the same devices / carriers as above, other API calls work, all if the time.
The client-side code is identical in all cases, apart from the URLs.
To me, this is pointing at a problem on the server side that is triggered by what the requests look like to it. But either the way, I would try to investigate this by looking at the requests and responses on the server side, and checking the server-side logs. See if there are significant differences in the requests coming from different devices / carriers. Especially the ones that work versus the ones that don't work. And see if the responses are empty when the server sends them.
I found the theory of Leonidos usefull:
https://stackoverflow.com/a/19540249/6076711
And here is my end of solution you can try using the following code.
string output = "";
while(br.ready() && (br.readLine() != null))
{
output += (String.valueOf(br.readLine()))+"\n";
}
The code can be improved by checking (before putting it in the string builder) whether the length of the content is bigger than 0.
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost postRequest = new HttpPost(ServiceUrls.base_url +
ServiceUrls.get_profile_url);
JSONObject object = new JSONObject();
object.put("username", params[0]);
StringEntity input = new StringEntity(object.toString());
input.setContentType("application/json");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);
String output;
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
} else {
HttpEntity entity = response.getEntity();
if ((entity != null) && (entity.getContentLength() != 0)) {
// Use writing to output stream to prevent problems with chunked responses
ByteArrayOutputStream os = new ByteArrayOutputStream();
entity.writeTo(os);
output = new String(os.toByteArray(),"UTF-8");
} else {
// Handle case there is not content returned
System.out.println("Received no content (HTTP response code " + response.getStatusLine().getStatusCode() + " , reason: " + getReasonPhrase() +")");
}
}
The code above however doesn't solve the issue why you get an empty response. I its only handling the fact it is happening is a more elegant way.
I noted however that you require a username in the request. Are you sure the user exist on the device and in case of non existing user, should there be returned something else?
below I include some of my code:
Here is my code:
int responseCode = httpCon.getResponseCode();
if (responseCode==-1) { httpCon.connect(); }
InputStream is = httpCon.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
}
rd.close();
try {
OutputStream file = openFileOutput("configND", Context.MODE_PRIVATE);
DataOutputStream wrf = new DataOutputStream(file);
wrf.writeBytes(line);
wrf.close();
} catch (Exception e){
e.printStackTrace();
}
I'm trying receive data (JSON string) from PHP file and then create a file with a content but something is wrong. I can't receive a JSON string and the file can not be created.
I use HttpURLconnection and I don't use apache library. I might add that sending JSON is working properly.
Help!
If you receive nothing from the server, the problem might be simply in your PHP script.
For the Android part of the "problem", if you don't want to use Volley and simply handle this with Android APIs, these two links should make your day :)
http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/
http://www.codeproject.com/Articles/267023/Send-and-receive-json-between-android-and-php
Personnally, when I learned Android some years ago, I followed AndroidHive ressources and it works pretty well.
im having a strange problem when receiving json results from the server. I have no idea what the problem is. The thing is that my String json result is corrupted, with strange symbols.
The result is like this (taken from eclipse debug)
Image :
Another strange thing that happens is that when I change the URL of the service to an alternative one, it works and the data is not corrupted. The URLs are the same but once redirects everything to the other.
The URL is use always is (example) http://www.hello.com
The URL that works is http://www.hello.com.uy
(cant post the exact link for security reasons)
The second one redirects everything to the first one, its the only thing it does.
I have tried changing the encoding to UTF-8 and it is still not working, here is the code (with one of the URLs commented)
I have also tried using Dev HTTP Client extension from chrome to check the service and it works fine, no corrupted data. Also, it works perfectly on iOS so i think its just and android/java issue.
DevClient:
try {
JSONObject json = new JSONObject();
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
HttpClient client = new DefaultHttpClient(httpParams);
//String url = TAG_BASEURL_REST +"Sucursal";
String url = "http://www.-------.com/rest/Sucursal";
//String url = "http://www.--------.com.uy/rest/Sucursal";
HttpGet request = new HttpGet(url);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream is = entity.getContent();
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();
String jsonRes = sb.toString();
JSONArray jObj = new JSONArray(jsonRes);
return jObj;
}
} catch (Throwable t) {
Log.i("Error", "Request failed: " + t.toString(), t);
}
return null;
InputStream is = entity.getContent();
// check if the response is gzipped
Header encoding = response.getFirstHeader("Content-Encoding");
if (encoding != null && encoding.getValue().equals("gzip")) {
is = new GZIPInputStream(is);
}
I am trying to connect to mysql db using PHP web service. This is the way I am forming the request
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://localhost/android_connect/getbrowsedata.php");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF8"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
System.out.println("result::"+sb.toString());
}catch(Exception e){
// Log.e("log_tag", "Error converting result "+e.toString());
}
When i run this from a normal java application, I am getting the appropriate result as JSON, which i am able to parse.I am also able to launch it from my browser. When i use this same code in android project,response returns a html with 403 you dont have permission to access .php file on this server (instead of local host i am using my ip address). I have included the user permission in android manifest file. I have also modified the httpd.conf in my WAMP server, changing all the denied to granted as found in the other posts.Is this an issue with any other configuration of the WAMP server.
Any one faced this issue? Any suggestion would be of great help
The whole thing works perfectly, except image won't show, no errors, Using RoR. What am I missing? All called by async class btw. Been trying several different methods with no avail, if someone could help me out that would be great. Willing to post more if needed.
Thanks!
public static void multiPart(Bitmap image, String topicid, String topost, Context c){
String responseString = "";
{
try {
String imageName = System.currentTimeMillis() + ".jpg";
HttpClient httpClient = new MyHttpClient(c);
HttpPost postRequest = new HttpPost("https://urlofmyapi");
if (image==null){
Log.d("TAG", "NULL IMAGE");
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
image.compress(CompressFormat.JPEG, 75, bos);
byte[] data = bos.toByteArray();
ByteArrayBody bab = new ByteArrayBody(data, imageName);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("feed", new StringBody(topost));
reqEntity.addPart("post_to", new StringBody(topicid));
reqEntity.addPart("upload_file", bab);
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
responseString = s.toString();
System.out.println("Response: " + responseString);
} catch (Exception e) {
Log.e(e.getClass().getName(), e.getMessage());
}
}
}
Perhaps you can do following step to import library into your Android.
requirement library:
apache-mime4j-0.6.jar
httpmime-4.0.1.jar
Right click your project and click properties
select java build path
select tab called "Order and Export"
Apply it
Fully uninstall you apk file with the adb uninstall due to existing apk not cater for new library
install again your apk
run it
Thanks,
Jenz
HTTP POSTing images from Java to RoR always seems to have undue issues for me. Have you tried attaching the binary as a org.apache.http.entity.mime.content.FileBody object, like this Android Multipart Upload question?