HTTP GET on Android - android

I have a method to insert data into server like this:
public void doInsert(){
try {
// setiap parameter yang akan dikirim melalui http
// harus encode agar
// dapat terbaca dengan baik oleh server
String no_imei = URLEncoder.encode(noImei.getText().toString(), "utf-8");
String nik = URLEncoder.encode(user.getText().toString(), "utf-8");
String pass = URLEncoder.encode(password.getText().toString(), "utf-8");
url += "?no_imei=" + no_imei + "&&nik=" + nik + "&&password=" + pass;
getRequest(url);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Another method that I have:
public void getRequest(String Url) {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try {
HttpResponse response = client.execute(request);
Toast.makeText(this, "Tambah Data " + request(response) + " ",Toast.LENGTH_SHORT).show();
} catch (Exception ex) {
//Toast.makeText(this, "Tambah Data Gagal !", Toast.LENGTH_SHORT).show();
}
}
And like this:
public static String request(HttpResponse response) {
String result = "";
try {
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 + "\n");
}
in.close();
result = str.toString();
} catch (Exception ex) {
result = "Error";
}
return result;
}
onClick method:
private View.OnClickListener onSave=new View.OnClickListener()
{
public void onClick(View v)
{
//Dbhelper helper = new Dbhelper(UserForm.this);
Cursor c = helper.Login(almagId);
if (noImei.getText().toString().equals("")||
user.getText().toString().equals("")||
password.getText().toString().equals("")
) {
Toast.makeText(UserForm.this, "Data Harus di isi", Toast.LENGTH_LONG).show();
}else if(c.moveToFirst()){
if(noImei.getText().equals(c.getString(0))||
user.getText().equals(c.getString(1))){
Toast.makeText(UserForm.this, "Data Sudah ada", Toast.LENGTH_LONG).show();
helper.close();
}
}else
{
doInsert();
helper.insertUser(noImei.getText().toString(),user.getText().toString(),password.getText().toString());
//Toast.makeText(UserForm.this, "Data Berhasil disimpan", Toast.LENGTH_LONG).show();
}
startActivity(new Intent(UserForm.this,MenuUtama.class));
user.setText("");
password.setText("");
return;
}
};
In the onClick method when response from server SUCCESS I want to do some activity. How can I do that? I tried with condition if my activity not running.

You should probably go with
if (response != null && response.getStatusLine().getStatusCode() == 200) { }

You have to add your activity in AndroidManifest.xml. Refer this link : Using Intent in an Android application to show another activity

looks like login in your if statement is little off.
if(request(response).equals("SUCCESS")){ startActivityForResult(new Intent(this,MainMenu.class))}
first, this does not make sense
if(request(response).equals("SUCCESS"))
what are you trying to do, cast request into response???
second:
.equals("SUCCESS"))
response is not an String object, are you looking for status code??
read over Android's HttpResponse
http://developer.android.com/reference/org/apache/http/HttpResponse.html
Example Code
if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//Do Something
}

Related

Save data from xml file when internet is available in android studio

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.

Android automatic webview login

I am trying to get my webview to show a page that is only accesible after i am logged in. but whatever i try i cant get past the login url.
How can i open/show the SEND_VISUM_URL after i login.
this is what i have so far:
String LOGIN_URL = "http://10.35.50.125/BCS/index.php?module=";
String SEND_VISUM_URL = "http://10.35.50.1/BCS/index.php?module=ScanVisa&Action=save";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView)findViewById(R.id.webviewer);
webView.loadUrl(LOGIN_URL);
cookieManager = new CookieManager();
Button login = (Button) findViewById(R.id.PostData);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
new loginTask().execute(getLoginData());
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
public class loginTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String loginData = params[0];
String text = "";
BufferedReader reader = null;
// Send data
try {
// Defined URL where to send data
URL login_url = new URL(LOGIN_URL);
// getting cookies:
URLConnection conn = login_url.openConnection();
conn.connect();
// setting cookies
cookieManager.storeCookies(conn);
cookieManager.setCookies(login_url.openConnection());
cookiestring = cookieManager.toString();
Log.d("Cookie in logintask:", cookiestring);
conn.getContent();
conn.setDoOutput(true);
conn.setConnectTimeout(3000);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
try {
wr.write(loginData); //post
wr.flush();
} catch (Exception e) {
e.printStackTrace();
}
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
if (line.length() > 0) {
sb.append(line + "\n");
if (line == null) {
continue;
}
}
}
text = sb.toString();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (reader != null) reader.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
return text;
}
protected void onPostExecute(String line) {
if (!line.contains("I107")) { //I107 is an error code that is returend when a login failed
Toast.makeText(getBaseContext(), "Login succesfull", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show();
}
}
}
public void setCookies(URLConnection conn) throws IOException {
// let's determine the domain and path to retrieve the appropriate cookies
URL url = conn.getURL();
String domain = getDomainFromHost(url.getHost());
String path = url.getPath();
Map domainStore = (Map)store.get(domain);
if (domainStore == null) return;
StringBuffer cookieStringBuffer = new StringBuffer();
Iterator cookieNames = domainStore.keySet().iterator();
while(cookieNames.hasNext()) {
String cookieName = (String)cookieNames.next();
Map cookie = (Map)domainStore.get(cookieName);
// check cookie to ensure path matches and cookie is not expired
// if all is cool, add cookie to header string
if (comparePaths((String)cookie.get(PATH), path) && isNotExpired((String)cookie.get(EXPIRES))) {
cookieStringBuffer.append(cookieName);
cookieStringBuffer.append("=");
cookieStringBuffer.append((String)cookie.get(cookieName));
if (cookieNames.hasNext()) cookieStringBuffer.append(SET_COOKIE_SEPARATOR);
}
}
try {
conn.setRequestProperty(COOKIE, cookieStringBuffer.toString());
} catch (java.lang.IllegalStateException ise) {
IOException ioe = new IOException("Illegal State! Cookies cannot be set on a URLConnection that is already connected. "
+ "Only call setCookies(java.net.URLConnection) AFTER calling java.net.URLConnection.connect().");
throw ioe;
}
}
any help would be greatly appreciated!

HttpUrlConnection does not work on mobile device but on emulator

all of a sudden my mobile device can't connect to the local server anymore. async tasks are not executed and i just can't figure out why. slowly i'm getting really desperate because in my opinion i didn't change anything to cause this.
as an example, this is a background task which is not working
public class Login extends AsyncTask<String, Void, String>{
private String loginUrl = "http://...";
private int loginSuccess = 0;
public String getToken(String fromJson) throws JSONException {
JSONObject json = new JSONObject(fromJson);
if(json.has("api_authtoken")) {
loginSuccess = 1;
String appToken = json.getString("api_authtoken");
return appToken;
}
else {
return json.toString();
}
}
public String doInBackground(String... arg0) {
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String authToken;
try {
// get logged in to get the api_authtoken
String email = (String) arg0[0];
String password = (String) arg0[1];
URL url = new URL(loginUrl);
// Create the request and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
//put values of edittexts into json-Object
JSONObject data = new JSONObject();
try {
data.put("email", email);
data.put("password", password);
} catch(JSONException e) {
Log.e("EXCEPTION", "unexpected JSON exception", e);
e.printStackTrace();
}
urlConnection.connect();
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(data.toString());
wr.flush();
reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
//read server response
while((line = reader.readLine()) != null) {
sb.append(line);
}
//receive server "answer"
try {
return getToken(sb.toString());
}catch(JSONException e) {
Log.e("LOG", "unexpected JSON exception", e);
e.printStackTrace();
} finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("MainActivity", "Error closing stream", e);
}
}
}
//return sb.toString();
return null;
}
catch(IOException e) {
Log.e("LoginTask", "Error ", e);
// If the code didn't successfully get the data, there's no point in attempting
// to parse it.
//forecastJsonStr = null;
return null;
}
}
public void onPostExecute(String result) {
super.onPostExecute(result);
//Log.v("RESULT", result);
if(result == null) {
CharSequence text = "no internet connection";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(MainActivity.this, text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
}
if(loginSuccess == 0) {
// if the request wasn't successful
// give user a message via toast
CharSequence text = "wrong password or user. please try again";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(MainActivity.this, text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
}
else {
// save token in shared preferences
SharedPreferences tokenPref = getSharedPreferences(getString(R.string.preference_token), Context.MODE_PRIVATE);
SharedPreferences.Editor editorToken = tokenPref.edit();
editorToken.putString(getString(R.string.saved_auth_token), result);
editorToken.commit();
//save login status = 1 in shared preferences
SharedPreferences loginPref = getSharedPreferences(getString(R.string.preference_logged_in), Context.MODE_PRIVATE);
SharedPreferences.Editor editorLogin = loginPref.edit();
editorLogin.putString(getString(R.string.saved_login), "1");
editorLogin.commit();
Intent mapsIntent = new Intent(getApplicationContext(), MapsActivity.class);
startActivity(mapsIntent);
}
}
}
HttpClient is not supported any more in sdk 23. You have to use URLConnection or downgrade to sdk 22 (compile 'com.android.support:appcompat-v7:22.2.0')
If you need sdk 23, add this to your gradle:
android {
useLibrary 'org.apache.http.legacy'
}
HttpClient won't import in Android Studio
You should think about using a HTTP library, there is a bunch of them on internet, some are really easy to use, optimize and errorless.
For example, Volley (made by Google, I really like this one), okHttp or Picasso (for image).
You should take a look at this.
If you want to send (output), for example with POST or PUT requests you need to use this :-
urlConnection.setDoOutput(true);
In your code :-
public class Login extends AsyncTask<String, Void, String>{
private String loginUrl = "http://...";
private int loginSuccess = 0;
public String getToken(String fromJson) throws JSONException {
JSONObject json = new JSONObject(fromJson);
if(json.has("api_authtoken")) {
loginSuccess = 1;
String appToken = json.getString("api_authtoken");
return appToken;
}
else {
return json.toString();
}
}
public String doInBackground(String... arg0) {
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String authToken;
try {
// get logged in to get the api_authtoken
String email = (String) arg0[0];
String password = (String) arg0[1];
URL url = new URL(loginUrl);
// Create the request and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setDoOutput(true); // HERE
//put values of edittexts into json-Object
JSONObject data = new JSONObject();
try {
data.put("email", email);
data.put("password", password);
} catch(JSONException e) {
Log.e("EXCEPTION", "unexpected JSON exception", e);
e.printStackTrace();
}
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(data.toString());
wr.flush();
urlConnection.connect();
reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
//read server response
while((line = reader.readLine()) != null) {
sb.append(line);
}
//receive server "answer"
try {
return getToken(sb.toString());
}catch(JSONException e) {
Log.e("LOG", "unexpected JSON exception", e);
e.printStackTrace();
} finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("MainActivity", "Error closing stream", e);
}
}
}
//return sb.toString();
return null;
}
catch(IOException e) {
Log.e("LoginTask", "Error ", e);
// If the code didn't successfully get the data, there's no point in attempting
// to parse it.
//forecastJsonStr = null;
return null;
}
}
public void onPostExecute(String result) {
super.onPostExecute(result);
//Log.v("RESULT", result);
if(result == null) {
CharSequence text = "no internet connection";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(MainActivity.this, text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
}
if(loginSuccess == 0) {
// if the request wasn't successful
// give user a message via toast
CharSequence text = "wrong password or user. please try again";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(MainActivity.this, text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
}
else {
// save token in shared preferences
SharedPreferences tokenPref = getSharedPreferences(getString(R.string.preference_token), Context.MODE_PRIVATE);
SharedPreferences.Editor editorToken = tokenPref.edit();
editorToken.putString(getString(R.string.saved_auth_token), result);
editorToken.commit();
//save login status = 1 in shared preferences
SharedPreferences loginPref = getSharedPreferences(getString(R.string.preference_logged_in), Context.MODE_PRIVATE);
SharedPreferences.Editor editorLogin = loginPref.edit();
editorLogin.putString(getString(R.string.saved_login), "1");
editorLogin.commit();
Intent mapsIntent = new Intent(getApplicationContext(), MapsActivity.class);
startActivity(mapsIntent);
}
}
}

Android HttpPost request to server

i want to send data from android SqLite database to my Codeigniter web App controller which take the post data and save it to MySql database
so i made buttn to make this sync task in android app and its code:
public void syncAttendance(View v) {
try
{
/** Retrieving data from database **/
//use cursor to keep all data
//cursor can keep data of any data type
Cursor c=db.rawQuery("select * from mytable", null);
int memNum = 1;
//move cursor to first position
c.moveToFirst();
//fetch all data one by one
do
{
//we can use c.getString(0) here
//or we can get data using column index
String memID = c.getString(c.getColumnIndex("memID"));
String currTime = c.getString(c.getColumnIndex("currTime"));
String dayName = c.getString(c.getColumnIndex("dayName"));
////////////////////////////////////////
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://mywebsite.com/index.php/admin/attendance/scan_qr");
JSONObject json = new JSONObject();
/** try {**/
// JSON data:
json.put("memID", memID);
json.put("currTime", currTime);
json.put("dayName", dayName);
JSONArray postjson=new JSONArray();
postjson.put(json);
// Post the data:
httppost.setHeader("json",json.toString());
httppost.getParams().setParameter("jsonpost",postjson);
// Execute HTTP Post Request
System.out.print(json);
HttpResponse response = httpclient.execute(httppost);
// for JSON:
if(response != null)
{
InputStream is = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
text = sb.toString();
}
//tv.setText(text);
/**
}catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
**/
//////////////////////////////////////////
/** show confirmation toast **/
Toast toast = Toast.makeText(this, memNum + memID + currTime + dayName, Toast.LENGTH_LONG);
toast.show();
memNum ++;
//move next position until end of the data
}while(c.moveToNext());
/** show confirmation toast **/
Toast toast = Toast.makeText(this, "Synchronization Completed", Toast.LENGTH_LONG);
toast.show();
}
catch(Exception e)
{
e.printStackTrace();
}
}
and the php codeigniter controller code is:
public function scan_qr()
{
$json = $_SERVER['HTTP_JSON'];
var_dump($json);
$data = json_decode($json);
var_dump($data);
$memID = $data->memID;
$currTime = $data->currTime;
$dayName = $data->dayName;
$ma7abawy_year = 3;
$data= array(
'member_id' => $memID,
//'points' => $points,
'presence_time' => $currTime,
//'event' => $eventname,
'event_date' => $dayName,
'ma7abawy_year' => $ma7abawy_year
);
$this->db->insert('attendance',$data);
}
i have no exception but nothing is happened
any ideas would be appreciated
I would suggest to use retrofit (see API docs) library to consume the service. Afterwards, see what you get back in the response and it will be a simple matter of saving the data to the sqlite3 db. See example for saving data.

clientprotocolexception DefaultHttpClient.execute()

I am using the following code to request a response from a webserver. The server sends a malformed response without headers which causes a ClientProtocolException. I have tried to use inspectors but they are not called before the exception is fired. I cannot change the server (it is within an embedded device, ALFA router R36).
Any suggestions to deal with this problem (btw: the code works perfect if the server response is well-formed)
Thanks in advance, Ton
class httpRequestTask extends AsyncTask <Integer, Integer, Integer> {
StringBuffer respTxt = new StringBuffer("");
int reqCode = 0;
protected Integer doInBackground(Integer... requestCode) {
Integer reqStatus = 0;
String url = "http://192.168.2.1/";
String authString = ("admin:admin");
switch( reqCode = requestCode[0].intValue()){
case Constants.HTTP_GET_STATUS_INFO: url += "/adm/status_info.asp"; break;
case Constants.HTTP_SCAN: url += "/goform/getUsbStaBSSIDListForm"; break;
}
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
HttpResponse response;
request.setURI( new URI( url));
request.addHeader("Authorization", "Basic " + Base64.encodeToString(authString.getBytes(),Base64.NO_WRAP));
response = client.execute(request);
reqStatus = response.getStatusLine().getStatusCode();
String line;
BufferedReader in = new BufferedReader( new InputStreamReader(response.getEntity().getContent()));
while((line = in.readLine()) != null) respTxt.append(line);
} catch ( ClientProtocolException e){
Log.e("ALFA", "HTTPReq:ClientProtocolException " + e.toString());
} catch ( IOException e){
Log.e("ALFA", "HTTPReq:IOException " + e.toString());
} catch ( Exception e){
Log.e("ALFA", "HTTPReq:Exception " + e.toString());
}
return reqStatus;
}
protected void onPostExecute(Integer reqStatus) {
Intent intent = new Intent(Constants.HTTP_RESPONSE);
intent.putExtra( "reqCode", reqCode);
intent.putExtra( "reqStatus", reqStatus);
intent.putExtra( "rspTxt", respTxt.toString());
getBaseContext().sendBroadcast(intent);
}
}
Looking further to find a solution to the problem I found a suggestion to use a socket to request the server. I used Fiddler in combination with a browser on my PC to examine the data send to and received from the buggy server and read an article on Wikipedia, explaining the HTTP protocol. With that info and by using a Socket, I wrote a very basic httpRequestHandler than deals with the miss formed response from the buggy web server.
class httpSocketRequest extends AsyncTask<Integer, Integer, Integer> {
StringBuffer respTxt = new StringBuffer("");
int reqCode = 0;
int reqStatus = 0;
protected Integer doInBackground(Integer... requestCode) {
String ip = "192.168.2.1";
String path = "";
String authString = ("admin:admin");
Socket socket = null;
switch( reqCode = requestCode[0].intValue()){
case Constants.HTTP_GET_STATUS_INFO: path = "adm/status_info.asp"; break;
case Constants.HTTP_SCAN: path = "goform/getUsbStaBSSIDListForm"; break;
}
try {
socket = new Socket( ip, 80);
PrintWriter out = new PrintWriter( socket.getOutputStream());
out.println( "GET http://" + ip + "/" + path + " HTTP/1.0");
out.println( "Authorization: Basic " + Base64.encodeToString(authString.getBytes(),Base64.NO_WRAP));
out.println( "");
out.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
int lineCnt = 0;
while((line = in.readLine()) != null){
if( lineCnt >= 0){
lineCnt++;
if(lineCnt == 1){ // first line should start with "HTTP/1.x " followed by a 3 digit status
if( line.length() > 12 && line.substring(0, 6).equals("HTTP/1")){
int p = line.indexOf(" ");
reqStatus = Integer.parseInt(line.substring(p+1, p+4));
continue;
} else { // not a well formed response
lineCnt = -1; // just put everything into respTxt
reqStatus = 200; // and assume everything went OK
}
} else if( lineCnt > 1){ // process rest of headers
if( line.length() == 0){
lineCnt = -1; // done with headers
} else {
// TODO insert code to process other headers
}
continue;
}
}
respTxt.append(line + "\n");
}
} catch (Exception e) {
Log.e("ALFA", "HTTPReq:Exception " + e.toString());
} finally {
try {
if( socket != null) socket.close();
} catch (IOException e) {
Log.e("ALFA", "HTTPReq:Exception closing socket" + e.toString());
}
}
return reqStatus;
}
protected void onPostExecute(Integer reqStatus) {
Intent intent = new Intent(Constants.HTTP_RESPONSE);
intent.putExtra( "reqCode", reqCode);
intent.putExtra( "reqStatus", reqStatus);
intent.putExtra( "rspTxt", respTxt.toString());
getBaseContext().sendBroadcast(intent);
}
}

Categories

Resources