Create a cache for android application - android

I am developing an android application which aim is to send some datas to the server. However, sometimes there may not have wifi connection, so I would like to ask if it is possible to create a cache to store multiple sets of data, say maybe 3 sets, and then the app will send those datas automatically when a connection is available.
Here is the way I send my datas to server recently:
private class GrabURL extends AsyncTask<String, Void, Void>{
//ArrayList object for storing the string pairs
ArrayList<NameValuePair> nameValuePairs;
public GrabURL() {
//constructor of the class
nameValuePairs = new ArrayList<NameValuePair>();
}
protected void onPreExecute(String key, String value) {
//store the pair of values into the ArrayList
nameValuePairs.add(new BasicNameValuePair(key,value));
}
#Override
protected Void doInBackground(String... urls) {
// TODO Auto-generated method stub
//Operation being executed in another thread
try{
//set up the type of HTTPClient
HttpClient client = new DefaultHttpClient();
//set up the location of the server
HttpPost post = new HttpPost(urls[0]);
//translate form of pairs to UrlEncodedFormEntity
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(nameValuePairs,HTTP.UTF_8);
//set up the entity being sent by post method
post.setEntity(ent);
//execute the url and post the values
//client.execute(post);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
line = EntityUtils.toString(resEntity);
} catch (Exception e) {
//catch the exception
line = "Can't connect to server";
}
return null;
}
protected void onPostExecute(Void unused) {
Toast.makeText(getApplicationContext(), "Value updated", Toast.LENGTH_SHORT).show();
}
}

I think Cache data is simple, you can store it in memory or store them as files. You can listen the network state change events to be notified when there is a connection available.
Here is the Sample Code.

this may be helpful in having abstract caching lib for object+image caching;
generic-store-for-android >>

To store primitive things, you can simply use SharedPreferences, and as soon as network becomes available, you can check if something with a specific key exist in SharedPreferences. If you don' t write the data inside a persistent environment(like SharedPreferences, Sqlite, file inside SD card or internal storage, etc.) closing the application will cause your data to be loss.

Related

communication between server and android app

i try to send information from android app to server to save in data base my code runs correctly but no data saved in database and i didn't get any response. i don't know where is the mistake in my code
private class postData extends AsyncTask<String, Void, String> {
// private final ProgressDialog dialog = ProgressDialog.show(getActivity(), "",
// "Saving data to server. Please wait...", true);
#Override
protected String doInBackground(String... params) {
// perform long running operation operation
// SharedPreferences settings = context.getSharedPreferences(PREFS_FILE, 0);
//String server = settings.getString("server", "");
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://phone.com/request_job");
String json = "";
String responseStr="";
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("ticket", "welcome"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
try {
httpclient.execute(httppost);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// Execute HTTP Post Request
// ResponseHandler<String> responseHandler=new BasicResponseHandler();
//String responseBody = httpclient.execute(httppost, responseHandler);
// if (Boolean.parseBoolean(responseBody)) {
// dialog.cancel();
// }
HttpResponse response = httpclient.execute(httppost);
responseStr = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
// TODO Auto-generated catch block
Log.i("HTTP Failed", e.toString());
}
return responseStr;
}
protected void onPostExecute(String responseStr) {
super.onPostExecute(responseStr);
Toast.makeText(getActivity(),responseStr,Toast.LENGTH_LONG).show();
if(responseStr.equals("true")){
// Update your Button here
Toast.makeText(getActivity(),"donefinally",Toast.LENGTH_LONG).show();
}
}
}
my code in server
public function check_user(Request $request){
$ticket = new ticket;// this line responsible to set data in database
$ticket->ticket = $request->ticket;
return response()->json(['data','true']);
}
}
In your server, do
$ticket = new ticket;// this line responsible to set data in database
$ticket->ticket = $request->ticket;
$ticket->save(); //<-- this line will save
Or in one go
$ticket = Ticket::create([
'ticket' => $request->ticket
]);
...
Now, make sure you call your ticket class properly. Not sure whether it's capital T (Ticket) or lowercase (ticket).
Edit
Since it's not working, you need to debug it step by step to see where the bottleneck is. First, in your function, simply do
return response()->json($request->ticket);
//This will prove that the request makes it to the server
Once you are sure you request makes it to the server, try to manually save something like
Ticket::create([
'ticket' => 'random string'
]);
You can call this function directly from your browser to test if it works. If nothing is saved in the db, make sure you have a $fillable array in your model and that you can connect properly to the db.

Cannot post variable from android client to php server

I develop an android code for transmit and received between android apps and PHP. The received part which is based on JSON, is properly working. I have tested by set variable manually in PHP code. However, when I have posted the variable from android to php, it cannot receive it. Anyone can tell me the problem ?
#Override
protected String doInBackground(Void... params) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", <Your username here>));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(<Your URL to php file>);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse response = httpclient.execute(httppost); // Execute Post to URL
String st = EntityUtils.toString(response.getEntity()); // This is the result from php web
Log.d(TK_Configuration.TAG, "In the try Loop" + st); // Still executing
finalResult = st; // You should register a variable for finalResult;
} catch (Exception e) {
Log.d(TK_Configuration.TAG, "Connection error : " + e.toString());
}
return "OK";
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
// After that, you will have final result and process to do with it here
// Below is my simple code, please change it
if(finalResult.equals("1")){
Toast.makeText(context, context.getResources().getString(R.string.upload_bike_success), Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(context, context.getResources().getString(R.string.upload_bike_fail), Toast.LENGTH_SHORT).show();
}
// End
}
Please try this, and one more point, you should use Gson library to decode JSON quickly to Java Object after you got JSON string from server.
Note: Replace TK_Configuration.TAG << by your TAG.
you have commented this line it means you are not passing values from Android
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
remove comment from this line.
One more thing, you are passing username but from php you are trying to fetch value as $user = $_POST['name'];, both name must be same.

How to create a web server using android studio?

I want to send some data collected by the app to the computer through internet. And secondly, apart from this, want to show live feed of the camera on the computer via internet.
I think making a web server will be a good option for the first requirement. But as I am new to android development, so please guide me.
For the live feed option, please suggest how this can be acheived.
Im not sure if this is good idea if you are new to android. Maybe start with something easier but if you do plan to do it any way.
To send data collected by the app you will have to send it to some kind of backend you will have to make it i suggest making it in PHP and saving the data in a Mysql database.
For the sending part you will probably want to do it in the background with a AsyncTask and it will look something like this :
public class Backend extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String server = "http://example.com/foo/bar"
String uid = params[0];
String name = params[1];
String email = params[2];
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(server+"NewUser.php");
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(1);
nameValuePair.add(new BasicNameValuePair("uid", uid));
nameValuePair.add(new BasicNameValuePair("email", email));
nameValuePair.add(new BasicNameValuePair("name", name));
try {
// Probeer dat te zetten
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
// Execute
HttpResponse response = httpClient.execute(httpPost);
// Zet response om naar String
String responseBody = EntityUtils.toString(response.getEntity());
return responseBody;
} catch (ClientProtocolException e) {
e.printStackTrace();
return "0";
} catch (IOException e) {
e.printStackTrace();
return "0";
}
}
}
And you can execute this class like this:
new Backend().execute("1","maantje","email#example.com")
This will now POST uid, email, name to example.com/foo/bar/NewUser.php
So you will have to create that the data will be in $_POST['uid],$_POST['email'] and $_POST['name'].
Also don't forget the internet permissions in your manifest
<uses-permission android:name="android.permission.INTERNET" />
For the live feed option i have no experience with that but maybe this is a good place to start https://github.com/fyhertz/libstreaming
You are right. You need server which can handle your request from phone. Basically you need web-service which is called api. You can create those api by using java,node.js etc and you need database to store your data. For database purpose, you can use MongoDB or any other database.
Your api will handle POST request to hold the data from user request from the app. This is how, you can hold user data.
For live feed of the camera, I am not sure. Expecting to hear from some expert guys. Thanks and best of luck

Launch multiple tasks consecutively

I want to save certain information via http. This information is continuously stored in a local database (sqlite) and just keep it in the server (HttpPost) every so often.
How I can save that information releasing tasks individually by each data from my table? If possible an orderly manner.
Thus I launch a task and works perfectly (the code is generic, of course)
(I hope my english is right)
void SaveDataOnServer()
{
String data = db.getFirstData();
task = new SaveItemTask();
task.execute(data);
//if I have, say, 5 data, it would be nice to launch 5 row consecutive (for, while...)?
}
public class SaveItemTask extends AsyncTask<String, Void, Boolean>
{
protected Boolean doInBackground(String... param)
{
...
HttpClient client = new DefaultHttpClient();
HttpPost consult = new HttpPost(url + "?x=" + param[0]);
//making an HTTP POST request
try
{
HttpResponse response = client.execute(consult);
HttpEntity entity = response.getEntity();
...
}
catch...
}
....
#Override
protected void onPostExecute(final Boolean success)
{
...
if (success)
{
//Update row (set saved onserver=true)
}
...
}
http://developer.android.com/reference/android/os/AsyncTask.html
The task can be executed only once (an exception will be thrown if a
second execution is attempted.)
So either you re-create your SaveItemTask object every time, either you modify SaveItemTask in order to perform the HttpPost a target number of times.

Submit form with POST data in Android app

I've been searching the web for a way to do this for about a week now, and I just can't seem to figure it out.
I'm trying to implement an app that my college can use to allow users to log in to various services on the campus with ease. The way it works currently is they go to an online portal, select which service they want, fill in their user name and pwd, and click login. The form data is sent via post (it includes several hidden values as well as just the user name and pwd) to the corresponding login script which then signs them in and loads the service.
I've been trying to come at the problem in two ways. I first tried a WebView, but it doesn't seem to want to support all of the html that normally makes this form work. I get all of the elements I need, fields for user and pwd as well as a login button, but clicking the button doesn't do anything. I wondered if I needed to add an onclick handler for it, but I can't see how as the button is implemented in the html of the webview not using a separate android element.
The other possibility was using the xml widgets to create the form in a nice relative layout, which seems to load faster and looks better on the android screen. I used EditText fields for the input, a spinner widget for the service select, and the button widget for the login. I know how to make the onclick and item select handlers for the button and spinner, respectively, but I can't figure out how to send that data via POST in an intent that would then launch a browser. I can do an intent with the action url, but can't get the POST data to feed into it.
So here is what I have right now...
HttpParams params = new BasicHttpParams();
HttpClient client = new DefaultHttpClient(params);
HttpPost post = new HttpPost(action);
String endResult = null;
try
{
post.setEntity(new UrlEncodedFormEntity(myList));
}
catch (UnsupportedEncodingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
try
{
String response = client.execute(post, new BasicResponseHandler());
endResult = response;
}
catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
So my question now... is how do I take the endResult screen, which should be the page returned after I logged in to my service, and display it in a browser?
What's wrong with them just using the built in browser? You can also submit a form using UrlEncodedFormEntity and HttpClient.
HttpParams params = new DefaultHttpParams(); // setup whatever params you what
HttpClient client = new DefaultHttpClient(params);
HttpPost post = new HttpPost("someurl");
post.setEntity(new UrlEncodedFormEntity()); // with list of key-value pairs
client.execute(post, new ResponseHandler(){}); // implement ResponseHandler to handle response correctly.
Okay and after you have the response in a string. The response since its a page is going to be in html. You need to use a WebView to show the html. WebView has a method loadData() that takes a string of html and displays it.
Based on #RobbyPonds answer, for the benefit of people wandering past here, below is a generic implementation to post and receive a response from a URI (NOTE Also contains waiting implementation to return a response, probably not every day implementation of network call):
private static String responseValue;
#SuppressWarnings({ "unchecked", "rawtypes" })
public static String sendPostToTargetAndWaitForResponse() throws ClientProtocolException, IOException {
final Thread currentThread = Thread.currentThread();
synchronized (currentThread) {
HttpParams params = new BasicHttpParams();
HttpClient client = new DefaultHttpClient(params);
HttpPost post = new HttpPost(HTTP_POST_URI);
// List Creation with post data for UrlEncodedFormEntity
ArrayList<NameValuePair> mList = new ArrayList<NameValuePair>();
mList.add(new NameValuePair() {
#Override
public String getValue() {
return getSampleJSON();
}
#Override
public String getName() {
return "json";
}
});
post.setEntity(new UrlEncodedFormEntity(mList)); // with list of key-value pairs
client.execute(post, new ResponseHandler(){
#Override
public Object handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
responseValue = EntityUtils.toString(response.getEntity(), "UTF-8");
synchronized (currentThread) {
currentThread.notify();
}
return null;
}
});
try {
currentThread.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
return responseValue;
}
}

Categories

Resources