Java Android:如何从web服务器检索单个数据并将其显示到textview?

Java Android:如何从web服务器检索单个数据并将其显示到textview?,java,android,android-networking,Java,Android,Android Networking,我想显示一个员工上一次从web服务器打卡上班。问题是我真的不确定如何检索中的最后一个时钟并将其显示到textview。以下是我的代码JSONParser.java: package com.example.win7.simpleloginapp; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; impo

我想显示一个员工上一次从web服务器打卡上班。问题是我真的不确定如何检索中的最后一个时钟并将其显示到textview。以下是我的代码JSONParser.java:

package com.example.win7.simpleloginapp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;

public class JSONParser {
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    int timeout=10000; //in milisecond = 10 detik

// constructor
public JSONParser() {
    //timeout = new Values().gettimeout();
}

// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
                                  List<NameValuePair> params) {

    // Making HTTP request
    try {

        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeout);
        HttpConnectionParams.setSoTimeout(httpParameters, timeout);

        // check for request method
        if(method == "POST"){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (SocketException ste)
    {
        Log.e("Timeout Exception: ", ste.toString());
    }
    catch (ConnectTimeoutException e)
    {
        Log.e("Timeout Exception: ", e.toString());
    }
    catch (IOException e) {
        e.printStackTrace();
    }

    try {
        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();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;
    }
}
package com.example.win7.simpleloginapp;
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.io.UnsupportedEncodingException;
导入java.net.SocketException;
导入java.util.List;
导入org.apache.http.HttpEntity;
导入org.apache.http.HttpResponse;
导入org.apache.http.NameValuePair;
导入org.apache.http.client.ClientProtocolException;
导入org.apache.http.client.entity.UrlEncodedFormEntity;
导入org.apache.http.client.methods.HttpGet;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.client.utils.URLEncodedUtils;
导入org.apache.http.conn.ConnectTimeoutException;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.apache.http.params.BasicHttpParams;
导入org.apache.http.params.HttpConnectionParams;
导入org.apache.http.params.HttpParams;
导入org.json.JSONException;
导入org.json.JSONObject;
导入android.util.Log;
公共类JSONParser{
静态InputStream为空;
静态JSONObject jObj=null;
静态字符串json=“”;
int timeout=10000;//以毫秒为单位=10分
//建造师
公共JSONParser(){
//超时=新值();
}
//函数从url获取json
//通过使用HTTP POST或GET方法
公共JSONObject makeHttpRequest(字符串url、字符串方法、,
列表参数){
//发出HTTP请求
试一试{
HttpParams httpParameters=新的BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters,超时);
HttpConnectionParams.setSoTimeout(httpParameters,超时);
//检查请求方法
如果(方法==“POST”){
//请求方法为POST
//defaultHttpClient
DefaultHttpClient httpClient=新的DefaultHttpClient(httpParameters);
HttpPost HttpPost=新的HttpPost(url);
setEntity(新的UrlEncodedFormEntity(参数));
HttpResponse HttpResponse=httpClient.execute(httpPost);
HttpEntity HttpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}else if(方法==“GET”){
//请求方法是GET
DefaultHttpClient httpClient=新的DefaultHttpClient(httpParameters);
String paramString=URLEncodedUtils.format(params,“utf-8”);
url+=“?”+参数字符串;
HttpGet HttpGet=新的HttpGet(url);
HttpResponse HttpResponse=httpClient.execute(httpGet);
HttpEntity HttpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}
}捕获(不支持的编码异常e){
e、 printStackTrace();
}捕获(客户端协议例外e){
e、 printStackTrace();
}捕获(SocketException ste)
{
Log.e(“超时异常:,ste.toString());
}
捕获(ConnectTimeoutException e)
{
Log.e(“超时异常:,e.toString());
}
捕获(IOE异常){
e、 printStackTrace();
}
试一试{
BufferedReader reader=新的BufferedReader(新的InputStreamReader(
is,“iso-8859-1”),8);
StringBuilder sb=新的StringBuilder();
字符串行=null;
而((line=reader.readLine())!=null){
sb.追加(第+行“\n”);
}
is.close();
json=sb.toString();
}捕获(例外e){
Log.e(“缓冲区错误”,“错误转换结果”+e.toString());
}
//尝试将字符串解析为JSON对象
试一试{
jObj=新的JSONObject(json);
}捕获(JSONException e){
Log.e(“JSON解析器”,“错误解析数据”+e.toString());
}
//返回JSON字符串
返回jObj;
}
}
ServerRequest.java:

package com.example.win7.simpleloginapp;


import android.app.Activity;
import android.app.Application;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.io.HttpRequestParser;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;


public class ServerRequest   {

    ProgressDialog progressDialog;
    public static final int CONNECTION_TIMEOUT = 1000 * 15;
    public static final String SERVER_ADDRESS =  ".................net";

    final static String TAG_USER = "user";

    private Context mContext;

    SharedPreferences sharedPreferences;
    public static final String mypreference = "mypref";
    public static final String NameStr = "Name";

    JSONArray user;
    JSONParser jsonParser = new JSONParser();

    public ServerRequest(Context context) {
        progressDialog = new ProgressDialog(context);
        progressDialog.setCancelable(false);
        progressDialog.setTitle("Processing..");
        progressDialog.setMessage("Please Wait....");
        mContext = context;

    }

    public void storeUserDataInBackground(user user, GetUserCallback userCallback) {
    progressDialog.show();
    new StoreUserDataAsyncTask(user, userCallback).execute();
}

public void fetchUserDataInBackground(user user, GetUserCallback callBack) {
    progressDialog.show();
    new fetchUserDataAsyncTask(user, callBack).execute();
}

public class StoreUserDataAsyncTask extends AsyncTask<Void, Void, Void> {
    user user;
    GetUserCallback userCallback;

    public StoreUserDataAsyncTask(user user, GetUserCallback userCallback) {
        this.user = user;
        this.userCallback = userCallback;
    }

    @Override
    protected Void doInBackground(Void... params) {
        ArrayList<NameValuePair> dataToSend = new ArrayList<>();

        dataToSend.add(new BasicNameValuePair("username", user.username));
        dataToSend.add(new BasicNameValuePair("password", user.password));

        HttpParams httpRequestParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);
        HttpClient client = new DefaultHttpClient(httpRequestParams);
        HttpPost post = new HttpPost("http://.........................../register.php");
        try {
            post.setEntity(new UrlEncodedFormEntity(dataToSend));
            client.execute(post);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        progressDialog.dismiss();
        userCallback.done(null);
        super.onPostExecute(aVoid);

    }
}

public class fetchUserDataAsyncTask extends AsyncTask< Void, Void, user> {
    user user;
    GetUserCallback userCallback;

    public fetchUserDataAsyncTask(user user, GetUserCallback userCallback) {
        this.user = user;
        this.userCallback = userCallback;
    }

    @Override
    protected user doInBackground(Void... params) {
        ArrayList<NameValuePair> dataToSend = new ArrayList<>();
        dataToSend.add(new BasicNameValuePair("username", user.username));
        dataToSend.add(new BasicNameValuePair("password", user.password));

        HttpParams httpRequestParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);
        HttpClient client = new DefaultHttpClient(httpRequestParams);
        HttpPost post = new HttpPost("................................../fetchUserData.php");

        user returnedUser = null;
        try {
            post.setEntity(new UrlEncodedFormEntity(dataToSend));
            HttpResponse httpResponse = client.execute(post);

            HttpEntity entity = httpResponse.getEntity();
            String result = EntityUtils.toString(entity);
            JSONObject jObject = new JSONObject(result);

            if(jObject.length()==0)
            {
                returnedUser = null;

            }
            else
            {
                String Name1 = jObject.getString("Name");
                //String Name1 = "ekin";

                storeData(Name1);

                //Name1 = "hello";

                returnedUser = new user(user.username, user.password);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return returnedUser;
    }

    @Override
    protected void onPostExecute(user returnedUser) {
        progressDialog.dismiss();
        userCallback.done(returnedUser);
        super.onPostExecute(returnedUser);

    }

}

public SharedPreferences getSharedPref(){
    return mContext.getSharedPreferences(mContext.getPackageName(), Context.MODE_PRIVATE);
}

public void storeData(String Name1) {


    getSharedPref().edit().putString("data", Name1).apply();
}

public String getData(){


    return getSharedPref().getString("data", "");
    }

}
package com.example.win7.simpleloginapp;
导入android.app.Activity;
导入android.app.Application;
导入android.app.ProgressDialog;
导入android.content.Context;
导入android.content.Intent;
导入android.content.SharedReferences;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.preference.PreferenceManager;
导入android.provider.Settings;
导入android.util.Log;
导入org.apache.http.HttpEntity;
导入org.apache.http.HttpResponse;
导入org.apache.http.NameValuePair;
导入org.apache.http.client.HttpClient;
导入org.apache.http.client.entity.UrlEncodedFormEntity;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.apache.http.impl.io.HttpRequestParser;
导入org.apache.http.message.BasicNameValuePair;
导入org.apache.http.params.BasicHttpParams;
导入org.apache.http.params.HttpConnectionParams;
导入org.apache.http.params.HttpParams;
导入org.apache.http.util.EntityUtils;
导入org.json.JSONArray;
导入org.json.JSONObject;
导入java.util.ArrayList;
公共类服务器请求{
进行对话进行对话;
公共静态最终int连接\u超时=1000*15;
公共静态最终字符串服务器_ADDRESS=“……..net”;
最终静态字符串标记\u USER=“USER”;
私有上下文;
SharedReferences SharedReferences;
公共静态最终字符串mypreference=“mypref”;
公共静态最终字符串NameStr=“Name”;
JSONArray用户;
JSONParser JSONParser=新的JSONParser();
公共服务器请求(上下文){
progressDialog=新建progressDialog(上下文);
progressDialog.setCancelable(假);
progressDialog.setTitle(“处理…”);
progressDialog.setMessage(“请稍候…”);
mContext=上下文;
}
public void storeUserDataInBackground(用户使用
package com.example.win7.simpleloginapp;


import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.InputFilter;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AnalogClock;
import android.widget.Button;
import android.widget.DigitalClock;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.json.JSONException;
import android.app.AlertDialog;
import android.location.LocationListener;

import com.example.win7.simpleloginapp.model.JSONParser2;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

public class MainActivity extends  ActionBarActivity  {

    Button button_logout;
    TextView etUsername , etName, lastTimeDisp, lastDateDisp;       //baru
    UserLocalStore userLocalStore;
    Button clockIN1, clockOUT1;
    Date date = new Date();
    String AndroidId;
    String username;
    double longitude;
    double latitude;
    private TextView locationText;
    private TextView addressText;
    private GoogleMap map;
    private LocationManager locationMangaer = null;
    private LocationListener locationListener = null;
    private Button btnGetLocation = null;
    private EditText editLocation = null;
    private ProgressBar pb = null;
    private static final String TAG = "Debug";
    private Boolean flag = false;
    JSONArray user = null;
    JSONParser jsonParser = new JSONParser();
    public static final String TAG_SUCCESS = "success";
    public static final String TAG_USER = "user";
    public static final String TAG_STAFF_ID = "staffID";
    public static final String TAG_DATE = "date";
    public static final String TAG_TIME = "time";
    public static final String TAG_LONG = "longitude";
    public static final String TAG_LAT = "latitude";
    private Button scannerButton;
    private Button camButton;
    String staffIDStr, dateStr, timeStr, latitudeStr, longitudeStr;
    String user_name;
    SharedPreferences sharedPreferences;
    public static final String mypreference = "MyPrefs" ;
    public static final String NameStr = "Name";
    ActionBar actionbar;
    TextView textview;
    LayoutParams layoutparams;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        ActionBarTitleGravity();
        LocationManager locationManager = (LocationManager)         getSystemService(LOCATION_SERVICE);

        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
            Toast.makeText(this, "GPS is Enabled in your device",     Toast.LENGTH_SHORT).show();
        }else{
           showGPSDisabledAlertToUser();
        }

    ActionBar actionBar = getSupportActionBar();
    actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3B5999")));
    actionBar.setDisplayUseLogoEnabled(true);
    actionBar.setDisplayShowHomeEnabled(true);

    setContentView(R.layout.activity_main);

    etUsername = (TextView) findViewById(R.id.etUsername);
    etName = (TextView) findViewById(R.id.etName);
    lastTimeDisp = (TextView) findViewById(R.id.lastTimeDisp);      //baru
    lastDateDisp = (TextView) findViewById(R.id.lastDateDisp);      //baru
    button_logout = (Button) findViewById(R.id.bLogout);
    AnalogClock ac = (AnalogClock) findViewById(R.id.analogClock1);
    DigitalClock dc = (DigitalClock) findViewById(R.id.digitalClock1);
    clockIN1 = (Button) findViewById(R.id.clockIN);
    clockOUT1 = (Button) findViewById(R.id.clockOUT);
    etUsername.setFilters(new InputFilter[]{new InputFilter.AllCaps()});
    etName.setFilters(new InputFilter[]{new InputFilter.AllCaps()});
    super.onPause();
    SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString("lastActivity", getClass().getName());
    editor.apply();     //baru - tukar commit() ke apply()
    ServerRequest serverRequest = new ServerRequest(getApplicationContext());
    ServerRequest2 serverRequest2 = new ServerRequest2(getApplicationContext());
    Log.d("", "The value is : " + serverRequest.getData());

    String username1 = serverRequest.getData();
    String timeL = serverRequest2.getData();
    String dateL = serverRequest2.getData();

    etName.setText(username1);
    lastTimeDisp.setText(timeL);        //baru
    lastDateDisp.setText(dateL);     //baru

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    locationText = (TextView) findViewById(R.id.location);
    addressText = (TextView) findViewById(R.id.address);
    replaceMapFragment();

    clockIN1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //date.setTime(System.currentTimeMillis()); //set to current time

            clockIN1.setClickable(false);
            Calendar c = Calendar.getInstance();
            dateStr = c.get(Calendar.YEAR) + "-" + c.get(Calendar.MONTH) + "-" + c.get(Calendar.DAY_OF_MONTH);
            timeStr = c.get(Calendar.HOUR_OF_DAY) + ":" + c.get(Calendar.MINUTE);
            staffIDStr = etUsername.getText().toString();
            new createClockIn().execute();
            clockIN1.setEnabled(false);
            clockIN1.setClickable(false);
        }
    });
    userLocalStore = new UserLocalStore(this);
}

private void ActionBarTitleGravity() {
    actionbar = getSupportActionBar();
    textview = new TextView(getApplicationContext());
    layoutparams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    textview.setLayoutParams(layoutparams);
    textview.setText("MysysESS");
    textview.setTextColor(Color.WHITE);
    textview.setGravity(Gravity.CENTER);
    textview.setTextSize(25);
    textview.setTypeface(Typeface.DEFAULT_BOLD);
    actionbar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
    actionbar.setCustomView(textview);
}

class createClockIn extends AsyncTask<String, String, String> {
    ProgressDialog dialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        dialog = new ProgressDialog(MainActivity.this);
        dialog.setMessage("LOADING.");
        dialog.setIndeterminate(false);
        dialog.setCancelable(false);
        dialog.show();
    }

    protected String doInBackground(String... args) {

        List<NameValuePair> params = new ArrayList<NameValuePair>();

        params.add(new BasicNameValuePair(TAG_STAFF_ID, staffIDStr));
        params.add(new BasicNameValuePair(TAG_DATE, dateStr));
        params.add(new BasicNameValuePair(TAG_TIME, timeStr));
        params.add(new BasicNameValuePair(TAG_LONG, longitudeStr));
        params.add(new BasicNameValuePair(TAG_LAT, latitudeStr));

        JSONObject json = jsonParser.makeHttpRequest("http://.........................../createClockIN.php", "POST", params);

        try {
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {

                finish();
            } else {
                return "gagal_database";
            }
        } catch (JSONException e)

        {
            e.printStackTrace();
            return "gagal_koneksi_or_exception";
        }
        return "sukses";
    }

    protected void onPostExecute(String result) {

        super.onPostExecute(result);
        if (result.equalsIgnoreCase("gagal_database")) {
            dialog.dismiss();
            Toast.makeText(MainActivity.this, "There is a problem , check your connection DB!", Toast.LENGTH_SHORT).show();
        } else if (result.equalsIgnoreCase("gagal_koneksi_or_exception")) {
            dialog.dismiss();
            Toast.makeText(MainActivity.this, "There is a problem , check your connection!", Toast.LENGTH_SHORT).show();

        } else if (result.equalsIgnoreCase("sukses")) {
            dialog.dismiss();
            Toast.makeText(MainActivity.this, "Lets work!", Toast.LENGTH_SHORT).show();
            String staffID1 = etUsername.getText().toString();
            Intent intent = new Intent(getApplicationContext(), MainActivity.class);
            intent.putExtra("username", staffID1);
            startActivity(intent);
        }
    }
}

//on start function login function
@Override
protected void onStart() {
    super.onStart();
    if (authenticate() == true)
        displayUserDetails();
    else
        startActivity(new Intent(MainActivity.this, login.class));
}

private boolean authenticate() {
    return userLocalStore.getUserLoggedIn();
}

private void displayUserDetails() {
    user user = userLocalStore.getLoggedInUser();

    etUsername.setText(user.username);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater menuInflater = getMenuInflater();
    menuInflater.inflate(R.menu.menu_main, menu);
    return super.onCreateOptionsMenu(menu);
}

public boolean onOptionsItemSelected(MenuItem item) {

    LinearLayout main_view = (LinearLayout) findViewById(R.id.main_view);
    switch (item.getItemId()) {

        case R.id.logout:
            userLocalStore.clearUserData();
            startActivity(new Intent(this, login.class));
            finish();
            return true;

        case R.id.history:
            if (item.isChecked())
                item.setChecked(false);
            else
                item.setChecked(true);
            String username1 = etUsername.getText().toString();
            Intent intent = new Intent(getApplicationContext(), ListHistory.class);
            intent.putExtra("username", username1);
            startActivity(intent);
            return true;

        case R.id.location:
            if (item.isChecked())
                item.setChecked(false);
            else
                item.setChecked(true);
            String username2 = etUsername.getText().toString();
            Intent intent2 = new Intent(getApplicationContext(), LocationActivity.class);
            intent2.putExtra("username", username2);
            startActivity(intent2);
            return true;

        default:
            return super.onOptionsItemSelected(item);

    }

}

@Override
public void onBackPressed() {

    // super.onBackPressed(); // Comment this super call to avoid calling finish()
}

public void callBackDataFromAsyncTask(String address) {
    addressText.setText(address);
}

private void replaceMapFragment() {
    map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map))
            .getMap();

    View frag = findViewById(R.id.map);
    frag.setVisibility(View.INVISIBLE);
    map.getUiSettings().setZoomGesturesEnabled(true);
    map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
    map.setMyLocationEnabled(true);
    map.setOnMyLocationChangeListener(myLocationChangeListener());
}

private GoogleMap.OnMyLocationChangeListener myLocationChangeListener() {
    return new GoogleMap.OnMyLocationChangeListener() {
        @Override
        public void onMyLocationChange(Location location) {

            LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
            double longitude = location.getLongitude();
            double latitude = location.getLatitude();

            Marker marker;
            marker = map.addMarker(new MarkerOptions().position(loc));
            map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
            locationText.setText("You are at [" + longitude + " ; " + latitude + " ]");

            longitudeStr = Double.toString(longitude);
            latitudeStr = Double.toString(latitude);

            if ((longitude > 101.650000 && longitude < 101.670000 && latitude > 2.925000 && latitude < 2.927000) ||
                (longitude > 101.640000 && longitude < 101.660000 && latitude > 2.900000 && latitude < 2.920000) ||
                (longitude > 101.680000 && longitude < 101.700000 && latitude > 3.140000 && latitude < 3.170000) ||
                (longitude > 103.620000 && longitude < 103.640000 && latitude > 1.640000 && latitude < 1.660000))

            {
                clockIN1.setEnabled(true);
                scannerButton.setEnabled(true);
                camButton.setEnabled(true);
            } else {
                Toast.makeText(MainActivity.this, "YOU ARE NOT IN THE OFFICE!", Toast.LENGTH_SHORT).show();
                clockIN1.setEnabled(false);
                scannerButton.setEnabled(false);
                camButton.setEnabled(false);
            }

            new GetAddressTask(MainActivity.this).execute(String.valueOf(latitude), String.valueOf(longitude));
        }
    };
}

private void showGPSDisabledAlertToUser()
{
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
    alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
            .setCancelable(false)
            .setPositiveButton("Settings your GPS",
                    new DialogInterface.OnClickListener()
                    {
                        public void onClick(DialogInterface dialog, int id)
                        {
                            Intent callGPSSettingIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivity(callGPSSettingIntent);
                        }
                    });
    alertDialogBuilder.setNegativeButton("Cancel",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                }
            });
    AlertDialog alert = alertDialogBuilder.create();
    alert.show();
    }

}