I am new to android development and now i am developing an e commerce application in android for online shopping.So far in this project i have created a shopping cart to hold articles selected by user. But every thing i have done works statically.
Now i have to communicate with the server to get updates about products and discounts.
I know how to consume webservices using json.
1.I am confused about that everytime i start my application i should communicate with server using webservice ?? or should i store the data in application when application is executed for the first time on device.
2.And what approach to store data should i follow
I should store it in device cache or
I should store it in applications sqlite db
Edit :
get data from webservice
try {
Log.v("inside webservice call ", "1");
HttpPost request = new HttpPost(url);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
// Build JSON string
Log.v("inside webservice call ", "2");
JSONStringer JsonString = new JSONStringer().object().key("prodid")
.value("4057339").endObject();
StringEntity entity = new StringEntity(JsonString.toString());
request.setEntity(entity);
Log.v("data", JsonString.toString());
Log.v("inside webservice call ", "2");
DefaultHttpClient httpClient1 = new DefaultHttpClient();
HttpResponse response = httpClient1.execute(request);
Log.v("inside webservice call ", "3");
Log.v("response code", response.getStatusLine().getStatusCode()
+ "");
HttpEntity responseEntity = response.getEntity();
// Read response data into buffer
char[] buffer = new char[(int) responseEntity.getContentLength()];
InputStream stream = responseEntity.getContent();
InputStreamReader reader = new InputStreamReader(stream);
reader.read(buffer);
stream.close();
Log.v("inside webservice call ", "4");
results = new JSONObject(new String(buffer));
// Populate text fields
String message = results.getString("message");
String isvalid = results.getString("isvalid");
Log.v("tag", message + isvalid);
Log.v("inside webservice call ", "5");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
I do this to get data from server
but unable to put this data in sqlite db please guide me
1.I am confused about that everytime i start my application i should communicate with server using webservice ?? or should i store the data in application when application is executed for the first time on device.
This totally depends on your requirement of the project,means if the data is going to be updated frequently then you should load it everytime,you can also load data periodically and if possible make one extra service from server that notify you for updates and you just need to check that only everytime.
For the images and other media you can store them to SDCard once and next time just check if they alreay exist then don't go for loading,this can save your process time.
2.And what approach to store data should i follow
To store the data as you are loading many specific and formatted and categoriesed information then sqlite db would be more help ful to store and retrieve data.
Depends on the architecture of your app. If this data does not change, then you just might download it on first start and then reuse it.
Device cache? I know of no such thing. Normally complex data is stored in database. But this really depends on the type of data and access requirements you have (searching, etc..). See all data storage options on Android.
Depending on the kind of data your storing, I would use one or the other. For caching binary data I use the file system ("device cache" as you say), but for more complex structures I prefer to use SQLite DB. An advantage of SQLite is, that you can alter your structure with every update easily using well known SQL Queries.
Oh #Frankenstein, was faster than me :D
EDIT: If you plan to cache categories and product collections I would always use a SQLite DB!
If the media files are static, you can even ship them with your application resources. In case they are never changing.
Related
There are lots of tutorials out there describing how to fetch JSON objects from the web and map them to Core Data.
I'm currently working on an iOS (later: Android as well) app which loads json objects from web and displays them to the user. In my opinion all this mapping from and to Core Data is an overhead in this case, it would be much easier to save the JSON objects directly and use them as "cache" in the app. Are there libraries/documented ways how to achieve fetching json objects, save them locally and fetch them with a predefined identifier?
I would love to fetch e.g. 10 objects, show them to the user and save the data locally. The next time the user is on that list the local data is shown and in the background the json-file is fetched again to be up-to-date. I guess this is a common use case but I didn't find any tutorials/frameworks enabling exactly this.
You can simply use NSURLCache to cache http responses instead saving JSONs
http://nshipster.com/nsurlcache/
There are many ways to implement this. You can implement cache using either file storage or database depending on the complexity as well as quantity of your data. If you're using files, you just need to store JSON response and load it whenever activity/fragment is crated. What I have done sometimes is store the JSON response in the form of string in a file, and then retrieve it on activity/fragment load. Here's an example of reading and writing string files:
Writing files:
FileOutputStream outputStream = context.openFileOutput("myfilename",Context.MODE_PRIVATE);
String stringToBeSaved = myJSONObject.toString();
outputStream.write(stringToBeSaved.getBytes());
Reading from files
FileInputStream inputStream= context.openFileInput("myfilename");
int c;
String temp="";
while( (c = inputStream.read()) != -1){
temp = temp + Character.toString((char)c);
You can convert this string to JSONObject using :
JSONObject jsonObject = new JSONObject(temp);
Or you can use the string according to your needs.
I want to get the data from a JSON URL. It contains 22 fields and it has above 6000 rows. I want to parse this JSON data and store it in an SQLite database.
I know the basics of JSON but when I use it I get an "out of memory" error.
After a lots of R&D and googling I found that I have to use GSON for Heavy URL, but I'm not familiar with it.
Can I implement paging in JSON? In other words, can I do something like getting partial data from JSON and storing it into a database and then request certain data and store it into a database, continuing the process until the full JSON file is parsed?
You must implement pagination mechanism on server side (the one, that serves you JSON data) and pass range parameters as part of the URL you mentioned.
If I knew I was going to have lot of rows/data, then I would run some simple SQL call to determine the size of the data. Then break up the original JSON within Android to deal with the data in smaller chunks, committing after each segment. So in your example, you know that you have 6000+ rows - store that in memory in Android as an int, then call 1000 rows at a time.
Some code after further queries:
String locationCountPath = "http://mywebserver/countAllMD5UserLocations";
try {
//My method to return a count of locations
int locCount = MyJSONUtilities.countAllUsersLocations(
locationCountPath, MyJSONUtilities.writeUserDetailsJSON(
username.toUpperCase(), password));
// Compare new count with count on phone
if (countLocs != locCount && locCount > 0) {
try {
// Grab the new set of locations
askToSyncLocations();
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
So, if you replace the askToSyncLocations() method with your own way of handling your 6000+ rows in a loop as batched of 1000 at a time, it should not encounter any memory problems?
I am new t ajax, but quite familiar with android. I am converting a ajax program to android app. As a part of it, i need to post data to the server. Below is the given post command in ajax.
var postTo = 'xyz.php';
$.post(postTo,{employee_name: $('[name=employee_name]').val() , phone: $('[name=phone]').val(), employee_type: 'guest' } ,
function(data) {
if(data.success){
window.localStorage["sa_id"] = data.mid;
window.location="getempdb.html";
}
if(data.message) {
$('#output').html(data.message);
} else {
$('#output').html('Could not connect');
}
},'json');
I want to implement this in android but under very little from the above statements. Could anyone who is good at ajax help me out with this thing. As of now, i get the user name and telephone number as a edit text input. I need to send this to php using http client. I know how to send data using php, but do not know what format to send and whether its a string to send or as a json object to send. Please help in interpreting the above code and oblige.
Apparently, this uses UrlEncodedFormEntity if you are using HttpClient in android.
This is created by using a List of NameValuePair.
from the parameters to the $.post:
{employee_name: $('[name=employee_name]').val() , phone: $('[name=phone]').val(), employee_type: 'guest' }
You have to create a NameValuePair for employee_name, one for phone ... each of which is fetched from a HTML element name employee_name, phone ... This is where you put the values from your EditTexts.
It returns a JSON formatted String, which you have to parse (typically using JSONObject obj = new JSONObject(result); once you have fetched the result from the server)
In this JSON object, you have a key named success, which format is not specified, except you can assume things went well if it is present ; a key mid, and a key message.
I have created a couple of web services of type .asmx (.NET) getting data from a local MySQL database and displaying it as XML in the browser. This is already up and running.
I want to parse said XML and display it in an Android application I'm working on. As the MySQL database will only be updated a few times every month I don't see the need to query the web service (and consequently the MySQL DB) every time I want to display the data in the Android application.
I figured it would make sense to download the XML returned by my web service and store it on the Android file system and parse it from there. Is this just incredibly backwards or is it doable?
When I access one of my local web service methods at
http://localhost/../WebService.asmx/GetLastDBUpdate
it returns a timestamp indicating when the database was last changed as XML in the browser, but I can't figure out how to download the file raw XML file.
Can I do this, or should I do this differently?
Any suggestions are welcome.
One simple way to do the synchronization, is to pass the timestamp of the last update to the server. The server then either gives an empty response (no updates), or a list of objects that where updated since that timestamp. In both cases, it gives a new timestamp, so the client doesn't have to stay in sync with the server.
Request POST /WebService.asmx/GetUpdates
<GetUpdates>
<Timestamp>2012-07-19T13:42:13Z</Timestamp>
<UpdateNow>True</UpdateNow>
</GetUpdates>
If there is no previous update from that client, pass an empty timestamp, or leave it out. Set UpdateNow to False, to just see if there are any updates (<Objects> will always be empty).
Response
<Updates>
<Timestamp>2012-07-23T17:54:13Z</Timestamp>
<Count>23</Count>
<Objects>
<Object>...</Object>
<Object>...</Object>
...
</Objects>
</Updates>
OR
<Updates>
<Timestamp>2012-07-19T13:42:13Z</Timestamp>
<Count>0</Count>
<Objects/>
</Updates>
The <Timestamp> could either be the time of the request, or the time of the latest update.
Process: Parse the XML, and write it to an SQLite database. Save the timestamp for future updates.
To make the actual request to the web-service, you could use kSoap2 for Android:
public SoapObject GetUpdates(String timestamp, boolean updateNow) {
SoapObject request = new SoapObject("http://tempuri.org/", "GetUpdates");
request.addProperty("Timestamp", timestmap);
request.addProperty("UpdateNow", updateNow ? "True" : "False");
SoapSerializationEnvelope envelope =
new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE transport = new HttpTransportSE(
"http://www.example.com/WebService.asmx/GetUpdates");
transport.call("GetUpdates", envelope);
return (SoapObject) transport.bodyIn;
}
I am implementing an android application and i can't figure out how to solve this problem : When user clicks to the update button , i want to connect to the my server and check if there is any update on the data , if there is , i want to get data from server and update the database.Should i use xml structure to check and get updates from server or is there any smarter ways to achieve this ?
Yes, there's a smarter way to do so, it will require some work on both server and client side though. This is how it works: all data should be available to download in JSON or XML format (I'd rather prefer JSON). So, you will have something like this in the server: http://example.com/resource.json. In order to know if there's a new version of the data, what you can do is adding a header version to the HTTP response (that way you don't have to download and parse the whole resource in order to know if there's a new version).
In order for you to check those headers, you will have something like this:
URLConnection urlConnection = null;
try {
urlConnection = url.openConnection();
urlConnection.connect();
String currentVersionHeader = urlConnection.getHeaderField("your-version-header");
if( currentVersionHeader == null ) {
currentVersionHeader = "-1";
}
int version = Long.parseLong(currentVersionHeader);
// then you compare with the old version
if( oldVersion < version ){
// download the data
}
} catch (Exception e) {}
Downloading and parsing a JSON resource is something that has been already treated and you will find a bunch of tutorials and references on Google and here.
You are not providing details of the server side (is PHP? Java? .NET?), so I also won't give you details of how to implement/add a version header. I'm just explained you what's one the best way to do this kind of things based on my own experience.