I am making an app
in android studio
in which i am getting data from JSON files
and populating it in a spinner. Below is my image of app
I have two options for saving data with the following conditions.
- When internet is off the data will be saved into a local
xml
file. - When internet is on the app
will
check for the connectivity and if available then it will check the file and then upload it to the server.
For now i am able to implement the both points separately i.e. I have created a method which will check for the connectivity of the internet. Passed this method into a condition and if the connection is available it will save the data into a local file aka xml
file and if internet is not available then it will save the new data only to the server.
My script is below
require_once ('config.php');
$return_arr = array();
$ref_no = ($_POST['ref_no']);
$meter_type = ($_POST['meter_type']);
$lattitude = ($_POST['lattitude']);
$longitude = ($_POST['longitude']);
$site_status = ($_POST['site_status']);
$comm_status = ($_POST['comm_status']);
$pole_type = ($_POST['pole_type']);
$meter_placement = ($_POST['meter_placement']);
$date_time = ($_POST['datetime']);
$record_save = "INSERT INTO `survey`(`s_id`,`ref_no`,`meter_type`, `lattitude`,`longitude`,`site_status`,`comm_status`,`pole_type`,`meter_placement`, `datetime`) values (NULL,'".$ref_no."','".$meter_type."','".$lattitude."','".$longitude."','".$site_status."','".$comm_status."','".$pole_type."','".$meter_placement."','".$date_time."')";
mysqli_query ($con,$record_save);
$row_array['errorcode1'] = 1;
I am saving all the data in a string format like below
String DateTime,refr_no, meter_type, Latitude, Longitude, site_status, comm_status, pole_type,rb_text;
On button click i am asking a permission
for saving file in local storage and then on permission granted
i have placed checks like below
btn_save_data.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(refr_no == "Select a reference number" || meter_type == "Select Meter Type" || Latitude == " " || Longitude == ""
|| site_status == "Select Site Status" || comm_status == "" || pole_type == "Select pole type" || DateTime == "" )
{
Toast.makeText(MainActivity.this, " Data not saved.... you must be missing some thing.. Please check!!! " , Toast.LENGTH_LONG ).show();
}else {
new TedPermission(MainActivity.this)
.setPermissionListener(ListenerSaveData)
.setRationaleMessage("This activity will need your permission to save file ")
.setPermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE)
.check();
Toast.makeText(MainActivity.this,"Data saved successfully", Toast.LENGTH_SHORT).show();
}
}
});
final PermissionListener ListenerSaveData = new PermissionListener() {
@Override
public void onPermissionGranted() {
if(refr_no == "Select a reference number" || meter_type == "Select Meter Type" || Latitude == " " || Longitude == ""
|| site_status == "Select Site Status" || comm_status == "" || pole_type == "Select pole type" || DateTime == "" )
{
Toast.makeText(MainActivity.this, " Data not saved.... you must be missing some thing.. Please check!!! " , Toast.LENGTH_LONG ).show();
}else {
if (!isOnline()) {
try {
File file = new File(getApplicationContext().getExternalFilesDir(null), filename);
file.createNewFile();
FileOutputStream fileos = new FileOutputStream(file, true);
XmlSerializer xmlSerializer = Xml.newSerializer();
StringWriter writer = new StringWriter();
xmlSerializer.setOutput(writer);
xmlSerializer.startDocument("UTF-8", true);
xmlSerializer.startTag(null, "record");
xmlSerializer.startTag(null, "ref_no");
xmlSerializer.text(refr_no);
xmlSerializer.endTag(null, "ref_no");
xmlSerializer.startTag(null, "meter_type");
xmlSerializer.text(meter_type);
xmlSerializer.endTag(null, "meter_type");
xmlSerializer.startTag(null, "lat");
xmlSerializer.text(Latitude);
xmlSerializer.endTag(null, "lat");
xmlSerializer.startTag(null, "long");
xmlSerializer.text(Longitude);
xmlSerializer.endTag(null, "long");
xmlSerializer.startTag(null, "site_status");
xmlSerializer.text(site_status);
xmlSerializer.endTag(null, "site_status");
xmlSerializer.startTag(null, "communication_status");
xmlSerializer.text(comm_status);
xmlSerializer.endTag(null, "communication_status");
xmlSerializer.startTag(null, "pole_type");
xmlSerializer.text(pole_type);
xmlSerializer.endTag(null, "pole_type");
xmlSerializer.startTag(null, "meter_placement");
xmlSerializer.text(rb_text);
xmlSerializer.endTag(null, "meter_placement");
xmlSerializer.startTag(null, "date_time");
xmlSerializer.text(DateTime);
xmlSerializer.endTag(null, "date_time");
xmlSerializer.endTag(null, "record");
xmlSerializer.endDocument();
xmlSerializer.flush();
String dataWrite = writer.toString();
fileos.write(dataWrite.getBytes());
fileos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dd_ref.setSelection(0);
dd_pole_type.setSelection(0);
dd_site_status.setSelection(0);
dd_m_type.setSelection(0);
_latitude.setText("");
_longitude.setText("");
comment.setText("");
DateTime = "";
refr_no = "";
Latitude = "";
Longitude = "";
site_status = "";
comm_status = "";
pole_type = "";
rb_text = "";
rg_meter_placement.clearCheck();
}else if (isOnline())
{
new SaveData().execute(refr_no,meter_type,Latitude,Longitude,site_status,comm_status,pole_type,rb_text,DateTime);
}
}
}
@Override
public void onPermissionDenied(ArrayList<String> deniedPermissions) {
}
};
Here the isOnline
method is checking the internet connectivity as below
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if(netInfo != null && netInfo.isConnectedOrConnecting())
{
Toast.makeText(MainActivity.this, "Internet is Connected", Toast.LENGTH_SHORT).show();
return true;
}
else {
Toast.makeText(MainActivity.this, "Internet is NOT Connected", Toast.LENGTH_SHORT).show();
return false;
}
}
For SaveData()
method the code is below
private class SaveData extends AsyncTask<String, Void, String>{
ProgressDialog mProgressDialog;
String res;
@Override
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(MainActivity.this,
"", "Saving Data Please wait...");
mProgressDialog.show();
}
@Override
protected String doInBackground(String... params) {
res = null;
PutUtility put = new PutUtility();
put.setParam("ref_no",params[0].toString());
put.setParam("meter_type", params[1].toString());
put.setParam("lattitude", params[2].toString());
put.setParam("longitude", params[3].toString());
put.setParam("site_status",params[4].toString());
put.setParam("comm_status",params[5].toString());
put.setParam("pole_type",params[6].toString());
put.setParam("meter_placement",params[7].toString());
put.setParam("datetime",params[8].toString());
try {
res = put.postData("http://192.168.100.12:8000/new/post_data.php");
Log.v("res", res);
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
protected void onPostExecute(String res) {
if(refr_no == "Select a reference number" || meter_type == "Select Meter Type" || Latitude == " " || Longitude == ""
|| site_status == "Select Site Status" || comm_status == "" || pole_type == "Select pole type" || DateTime == "" )
{
Toast.makeText(MainActivity.this, " Data not saved.... you must be missing some thing.. Please check!!! " , Toast.LENGTH_LONG ).show();
}else {
Toast.makeText(getApplicationContext(), " Data Saved Successfully ", Toast.LENGTH_SHORT).show();
dd_ref.setSelection(0);
dd_pole_type.setSelection(0);
dd_site_status.setSelection(0);
dd_m_type.setSelection(0);
_latitude.setText("");
_longitude.setText("");
comment.setText("");
DateTime = "";
refr_no = "";
Latitude = "";
Longitude = "";
site_status = "";
comm_status = "";
pole_type = "";
rb_text = "";
rg_meter_placement.clearCheck();
}
mProgressDialog.dismiss();
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
While the PutUtility
class is below
public class PutUtility {
private Map<String, String> params = new HashMap<>();
private static HttpURLConnection httpConnection;
private static BufferedReader reader;
private StringBuffer response;
public void setParam(String key, String value) {
params.put(key, value);
}
public String postData(String Url) {
StringBuilder sb = new StringBuilder();
for (String key : params.keySet()) {
String value = null;
value = params.get(key);
if (sb.length() > 0) {
sb.append("&");
}
sb.append(key + "=" + value);
}
try {
// Defined URL where to send data
URL url = new URL(Url);
URLConnection conn = null;
conn = url.openConnection();
// Send POST data request
httpConnection = (HttpURLConnection) conn;
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpConnection.setRequestMethod("POST");
httpConnection.setDoInput(true);
httpConnection.setDoOutput(true);
OutputStreamWriter wr = null;
wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(sb.toString());
wr.flush();
BufferedReader in = new BufferedReader(
new InputStreamReader(httpConnection.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return response.toString();
}}
I want to implement the second point that whenever the app
is connected to the internet then all the data in the file (xml file) will be uploaded to the server.
As a newbie i don't have any idea how to do it.
Any help would be highly appreciated.