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

时间:2017-01-13 09:13:56

标签: java android android-networking

我想从网络服务器显示员工的最后一个时钟。问题是我不确定如何检索单个最后一个时钟并将其显示到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;
    }
}

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", "");
    }

}

这是MainActivity.java:

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();
    }

}

为了您的信息,我必须从另一个Web服务器URL(http://........................./lastClock.php)检索数据,表中的实体名称是dclkrec(表示日期)和cclktime(表示时间)。

你们的任何帮助都将非常感激。先谢谢你。

1 个答案:

答案 0 :(得分:2)

你在这里做了很多车轮改造。有用于联网和序列化/反序列化数据的工具。

对于网络,我可以推荐Retrofit

使用JSON对象Gson

尝试这些,你的生活会更容易。相信我。值得投资一点时间。