Passing ID with PHP and MySQL - java

I am programming an app where a teacher logs in with a username and password. After the login a new fragment in the app opens where the teacher sees all his students in a ListView. To login I only type the username and the password. I use for this php and mysql.
My problem is that my login.php doesn't pass the ID from the teacher to the get_data.php where I do a SQL query.
login.php
<?php
session_start();
if($_SERVER['REQUEST_METHOD']=='POST'){
$username = $_POST['username'];
$password = $_POST['password'];
if($username == '' || $password == ''){
echo '';
}else{
require_once('dbConnect.php');
$sql = "SELECT ID_Teacher, username, password FROM Lehrer WHERE username='$username' and password='$password'";
mysqli_error($con);
$check = mysqli_fetch_array(mysqli_query($con,$sql));
}
if(isset($check)){
echo "success";
$_SESSION['id'] = $check['ID_Teacher'];
}else{
echo "Wrong Password or Username";
}
}else{
echo "Error, try again!";
}
?>
get_data.php
<?php
session_start();
require_once('dbConnect.php');
$sql = "SELECT Student.Name,Student.Surname FROM Student WHERE Student.ID_Teacher = {$_SESSION['id']}";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res))
{
array_push($result, array('Name'=>$row[0], 'Surname'=>$row[1]));
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
?>
ActivityLogin.java
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.HashMap;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.HashMap;
public class ActivityLogin extends AppCompatActivity implements View.OnClickListener{
public static final String USER_NAME = "USER_NAME";
public static final String PASSWORD = "PASSWORD";
private static final String LOGIN_URL = "http://bachelormedinf.16mb.com/login.php";
private EditText editTextUserName;
private EditText editTextPassword;
private Button buttonLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_login);
editTextUserName = (EditText) findViewById(R.id.username);
editTextPassword = (EditText) findViewById(R.id.password);
buttonLogin = (Button) findViewById(R.id.buttonUserLogin);
buttonLogin.setOnClickListener(this);
}
private void login(){
String username = editTextUserName.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
userLogin(username,password);
}
private void userLogin(final String username, final String password){
class UserLoginClass extends AsyncTask<String,Void,String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(ActivityLogin.this,"Please Wait",null,true,true);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
if(s.equalsIgnoreCase("success")){
Intent intent = new Intent(ActivityLogin.this,ListView.class);
intent.putExtra(USER_NAME,username);
startActivity(intent);
}else{
Toast.makeText(ActivityLogin.this, s, Toast.LENGTH_LONG).show();
}
}
#Override
protected String doInBackground(String... params) {
HashMap<String,String> data = new HashMap<>();
data.put("username",params[0]);
data.put("password",params[1]);
RegisterUserClass ruc = new RegisterUserClass();
String result = ruc.sendPostRequest(LOGIN_URL,data);
return result;
}
}
UserLoginClass ulc = new UserLoginClass();
ulc.execute(username,password);
}
#Override
public void onClick(View v) {
if(v == buttonLogin){
login();
}
}}
ListView.java
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class ListView extends ActionBarActivity implements View.OnClickListener {
private TextView textViewJSON;
private Button buttonGet;
private Button buttonParse;
private TextView textView;
public static final String MY_JSON ="MY_JSON";
private static final String JSON_URL = "http://www.bachelormedinf.16mb.com/get_data.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewJSON = (TextView) findViewById(R.id.textViewJSON);
textViewJSON.setMovementMethod(new ScrollingMovementMethod());
buttonGet = (Button) findViewById(R.id.buttonGet);
buttonParse = (Button) findViewById(R.id.buttonParse);
buttonGet.setOnClickListener(this);
buttonParse.setOnClickListener(this);
textView = (TextView) findViewById(R.id.textViewUserName);
Intent intent = getIntent();
String username = intent.getStringExtra(ActivityLogin.USER_NAME);
textView.setText("Willkommen Dr. " + username);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
if(v==buttonGet){
getJSON(JSON_URL);
}
if(v==buttonParse){
showParseActivity();
}
}
private void showParseActivity() {
Intent intent = new Intent(this, ParseJSON.class);
intent.putExtra(MY_JSON,textViewJSON.getText().toString());
startActivity(intent);
}
private void getJSON(String url) {
class GetJSON extends AsyncTask<String, Void, String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(ListView.this, "Please Wait...",null,true,true);
}
#Override
protected String doInBackground(String... params) {
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while((json = bufferedReader.readLine())!= null){
sb.append(json+"\n");
}
return sb.toString().trim();
}catch(Exception e){
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
textViewJSON.setText(s);
}
}
GetJSON gj = new GetJSON();
gj.execute(url);
}}
RegisterUserClass.java
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
public class RegisterUserClass {
public String sendPostRequest(String requestURL,
HashMap<String, String> postDataParams) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
response = br.readLine();
}
else {
response="Error Registering";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
}

try this
$sql = "SELECT Student.Name,Student.Surname FROM Student WHERE Student.ID_Teacher = ".$_SESSION['id'];

Related

Android: How to retrieve a single data from a web server and display it to a textview?

i want to display an employee last clock-in from a web server. The problem is i'm not really sure how to retrieve a single last clock-in and display it to a textview. Here is my code, 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", "");
}
}
And here is the 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();
}
}
For your information, I have to retrieve the data from another web server url(http://........................./lastClock.php) and the name of the entity from the table is dclkrec(represent date) and cclktime(represent time).
Any help from you guys would be very appreciated. Thank you in advanced.
You are doing a lot of wheel reinvention here. There are tools for networking and serialising/deserialising data.
For networking I can recommend Retrofit
Working with JSON objects Gson
Try these and your life will be much easier. Trust me. It is worth investing a little time.

How can I compare my Encrypted password from database in android

Here are my Android and PHP codes available. I am able to compare the password and Login successfully if password is in form of normal String. But when I am entering the password in encrypted format I am not able to compare the password value.And therefore not able to Login Successfully.
SignUpActivity.Java
package com.kezinking.nupur.kezinking;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
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.HttpClient;
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.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static android.R.attr.id;
/**
* Created by Nupur on 8/2/2016.
*/
public class SignupActivity extends AppCompatActivity {
private static final String TAG ="" ;
TextView link_login;
Button btn_signup;
EditText input_username;
EditText input_email;
EditText input_password;
String username;
String email;
String password;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
link_login = (TextView) findViewById(R.id.link_login);
btn_signup = (Button) findViewById(R.id.btn_signup);
input_username=(EditText) findViewById(R.id.input_username);
input_email=(EditText) findViewById(R.id.input_email);
input_password=(EditText) findViewById(R.id.input_password);
link_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(SignupActivity.this, LoginActivity.class);
startActivity(intent);
SignupActivity.this.getIntent();
}
});
btn_signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
username = input_username.getText().toString();
email= input_email.getText().toString();
password = input_password.getText().toString();
SignUp();
}
});
}
public void SignUp() {
if (!validate()) {
onSignupFailed();
return;
}else{
insert(username,email,password);
}
}
public void insert(final String username, final String email,final String password){
class SendPostReqAsynTask extends AsyncTask<String,Void,String> {
#Override
protected String doInBackground(String... params) {
String paramUsername=params[0];
String paramPassword=params[1];
//String username = etUsername.getText().toString();
//String password = etPassword.getText().toString();
List<NameValuePair> nameValuePairs= new ArrayList<>();
nameValuePairs.add(new BasicNameValuePair("username",username));
nameValuePairs.add(new BasicNameValuePair("email",email));
nameValuePairs.add(new BasicNameValuePair("password",password));
try{
HttpClient httpClient = new DefaultHttpClient();
// HttpGet request = new HttpGet("http://www.example.com");
HttpPost httpPost = new HttpPost("http://kezinking.com/SignUpAndroid");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response= httpClient.execute(httpPost);
HttpEntity entity= response.getEntity();
int i =response.getStatusLine().getStatusCode();
System.out.println(i);
onSignupSuccess();
}catch(ClientProtocolException e){
}catch (IOException e){
}
return "Success";
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
TextView textViewResult = (TextView) findViewById(R.id.txtResultCheck);
textViewResult.setText("Successfully Registered");
}
}
SendPostReqAsynTask sendPostReqAsynTask=new SendPostReqAsynTask();
sendPostReqAsynTask.execute(username,password);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onSignupSuccess() {
//btn_signup.setEnabled(true);
Intent intent=new Intent(SignupActivity.this,MainActivity.class);
startActivity(intent);
SignupActivity.this.getIntent();
}
public void onSignupFailed() {
Toast.makeText(getBaseContext(), "Failed to Register", Toast.LENGTH_LONG).show();
// btn_signup.setEnabled(true);
}
public boolean validate() {
boolean valid = true;
String username = input_username.getText().toString();
String email = input_email.getText().toString();
String password = input_password.getText().toString();
if (username.isEmpty() || username.length() < 3) {
input_username.setError("at least 3 characters");
valid = false;
} else {
input_username.setError(null);
}
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
input_email.setError("enter a valid email address");
valid = false;
} else {
input_email.setError(null);
}
if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
input_password.setError("between 4 and 10 alphanumeric characters");
valid = false;
} else {
input_password.setError(null);
}
return valid;
}
}
LoginActivity.Java
package com.kezinking.nupur.kezinking;
import android.animation.ObjectAnimator;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Space;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by Nupur on 8/2/2016.
*/
public class LoginActivity extends AppCompatActivity {
public static final String MY_JSON = "MY_JSON";
private static final String JSON_URL = "http://kezinking.com/AndroidLogin";
EditText input_email, input_password;
Button btn_login, btnContactUs, btnWorkhr, btnDeltime, btnMoneyBack;
TextView link_signup, textViewJSON, txtcheck;
private static Boolean flag = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btn_login = (Button) findViewById(R.id.btn_login);
link_signup = (TextView) findViewById(R.id.link_signup);
input_email = (EditText) findViewById(R.id.input_email);
input_password = (EditText) findViewById(R.id.input_password);
textViewJSON = (TextView) findViewById(R.id.textViewJSON);
// value=(TextView)findViewById(R.id.value);
txtcheck = (TextView) findViewById(R.id.txtcheck);
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
login();
}
});
link_signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(LoginActivity.this, SignupActivity.class);
startActivity(intent);
LoginActivity.this.getIntent();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void login() {
if (!validate()) {
onLoginFailed();
return;
} else {
getJSON(JSON_URL);
}
}
public void getJSON(String url) {
class GetJSON extends AsyncTask<String, Void, String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(LoginActivity.this, "Please Wait...", null, true, true);
}
#Override
protected String doInBackground(String... params) {
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
//String result=null;
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
textViewJSON.setText(s);
String jsonString = textViewJSON.getText().toString();
//String jsonString = "{\"result\":[{\"Vendor_ID\":\"1\",\"username\":\"nupur\",\"password\":\"nupur\"},{\"Vendor_ID\":\"4\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"3\",\"username\":\"nupur\",\"password\":\"1234\"},{\"Vendor_ID\":\"5\",\"username\":\"RAJ\",\"password\":\"RAJ\"},{\"Vendor_ID\":\"6\",\"username\":\"RAJ\",\"password\":\"RAJ\"},{\"Vendor_ID\":\"7\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"8\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"9\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"10\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"11\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"12\",\"username\":\"RAM\",\"password\":\"RAM\"},{\"Vendor_ID\":\"13\",\"username\":\"RAM\",\"password\":\"RAM\"},{\"Vendor_ID\":\"14\",\"username\":\"RAM\",\"password\":\"RAM\"},{\"Vendor_ID\":\"15\",\"username\":\"RAM\",\"password\":\"RAM\"},{\"Vendor_ID\":\"16\",\"username\":\"Nupur\",\"password\":\"Nupur\"},{\"Vendor_ID\":\"17\",\"username\":\"Nupur\",\"password\":\"Nupur\"},{\"Vendor_ID\":\"18\",\"username\":\"Nupur\",\"password\":\"Nupur\"},{\"Vendor_ID\":\"19\",\"username\":\"Nupur\",\"password\":\"Nupur\"},{\"Vendor_ID\":\"20\",\"username\":\"Rohit\",\"password\":\"Rohit\"},{\"Vendor_ID\":\"21\",\"username\":\"RAM\",\"password\":\"RAM\"},{\"Vendor_ID\":\"22\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"23\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"24\",\"username\":\"RAM\",\"password\":\"RAM\"},{\"Vendor_ID\":\"35\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"34\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"33\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"32\",\"username\":\"RAM\",\"password\":\"RAM\"},{\"Vendor_ID\":\"31\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"36\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"37\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"38\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"39\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"40\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"41\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"73\",\"username\":\"\",\"password\":\"\"},{\"Vendor_ID\":\"43\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"44\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"45\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"46\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"47\",\"username\":\"username\",\"password\":\"password\"},{\"Vendor_ID\":\"74\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"75\",\"username\":\"SAGAR\",\"password\":\"SAGAR\"},{\"Vendor_ID\":\"72\",\"username\":\"Krishna\",\"password\":\"Krishna\"},{\"Vendor_ID\":\"68\",\"username\":\"Honey\",\"password\":\"Honey\"},{\"Vendor_ID\":\"69\",\"username\":\"Ram\",\"password\":\"Ram\"},{\"Vendor_ID\":\"70\",\"username\":\"Ram\",\"password\":\"Ram\"},{\"Vendor_ID\":\"71\",\"username\":\"Ram\",\"password\":\"Ram\"}]}";
//String email = (input_email.getText().toString());
//txtcheck.setText(jsonString);
String email = input_email.getText().toString();
String password = input_password.getText().toString();
// final String myResult = (email) + (password);
String value = (String.valueOf(email + password));
System.out.println(value);
// String value=(input_email.getText().toString()+input_password.getText().toString());
//String input_email = "";
//String input_password = "";
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray result = jsonObject.getJSONArray("result");
//System.out.println("result " + result);
//iterate through json array and check if id is same with your search
//System.out.println("length " + result.length());
for (int i = 0; i < result.length(); i++) {
System.out.println(i);
JSONObject item = result.getJSONObject(i);
String Email = item.getString("email");
String Password = item.getString("password");
//System.out.println("Email from json "+ Email);
//System.out.println("Password from json " + Password);
if (Email.equals(email) && Password.equals(password)) {
System.out.println("Email from json"+ Email);
System.out.println("Password from json" + Password);
flag=true;
onLoginSuccess();
break;
}
}
if(!flag){
onLoginFailed();
}
} catch (JSONException e) {
e.printStackTrace();
}
//here you can show the result
Log.v(this.getClass().getSimpleName(), "email = " + email);
Log.v(this.getClass().getSimpleName(), "password = " + password);
//txtcheck.setText(email);
}
}
GetJSON gj = new GetJSON();
gj.execute(url);
}
#Override
public void onBackPressed() {
// disable going back to the MainActivity
moveTaskToBack(true);
}
public void onLoginSuccess() {
btn_login.setEnabled(true);
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
LoginActivity.this.getIntent();
// finish();
}
public void onLoginFailed() {
Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show();
// btn_login.setEnabled(true);
}
public boolean validate() {
boolean valid = true;
String email = input_email.getText().toString();
String password = input_password.getText().toString();
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
input_email.setError("enter a valid email address");
valid = false;
} else {
input_email.setError(null);
}
if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
input_password.setError("between 4 and 10 alphanumeric characters");
valid = false;
} else {
input_password.setError(null);
}
return valid;
}
}
PHP- AndroidLogin.php
<?php
$con=mysqli_connect("localhost","amodbina0106","Amodbina200","kezin_king");
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
?>
<?php
$sql=mysqli_query($con,"SELECT email,password FROM `users` WHERE 1");
$result=array();
while($row=mysqli_fetch_assoc($sql))
{
$result[]=$row;
}
echo json_encode(array("result"=>$result));
?>
PHP-SignUpAndroid.php
<?php
$con=mysqli_connect("localhost","amodbina0106","Amodbina200","kezin_king");
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
echo "Connected successfully";
?>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<table style="width: 100%">
<?php
$username=($_POST['username']);
$email=($_POST['email']);
$password=($_POST['password']);
$encryptedpassword=md5($password);
$sql=mysqli_query($con,"INSERT INTO `kezin_king`.`users` (`user_id`, `username`, `name`, `shop-name`, `password`, `email`, `adr`, `con_no`, `type`, `profile`, `doj`, `banner`, `banner1`, `lat`, `lon`, `email_code`, `activation`) VALUES (NULL, '$username', '', '', '$encryptedpassword', '$email', '', '', '', '', '', '', '', '', '', '', '1')");
$sql=mysqli_query($con,"SELECT name,username,password,email FROM `user` WHERE 1");
while($row=mysqli_fetch_assoc($sql))
{
$username=$row['username'];
$email=$row['email'];
$password=$row['password'];
?>
<tr>
<th><?php echo $username; ?></th>
<th><?php echo $email; ?></th>
<th><?php echo $password; ?></th>
</tr>
<?php }?>
</table>
Please help me.We can do the login if password is Encrypted ?
Thanks in Advance
Error/Output:-
V/GetJSON: email = check#check.com
V/GetJSON: password = check1
I/ViewRootImpl: CPU Rendering VSync enable = true
"LoginFailed"

why replace words to question mark in send data to server

I try send data to server but when I send Persian words it sends question marks, for example if I send "سلام" it sends "????"
How can I fix this ?
This is my FragmentForm.class :
package com.skyline.jimmy;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import com.skyline.jimmy.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
public class FragmentForm extends Fragment {
// An interface to display or dismiss of ProgressBar
public interface OnSendingRequestToServer {
public void DisplayLoding(boolean setVisibility);
}
private final String TAG = "FragmentForm";
private OnSendingRequestToServer onRequestToServer;
private Context context;
private EditText etName;
private EditText etComment;
private RatingBar ratingBar;
private ImageButton ibSubmit;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
onRequestToServer = (OnSendingRequestToServer) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnConnectingToServer interface.");
}
context = activity.getApplicationContext();
Log.d(TAG, "Fragment attached to activity.");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_form, container, false);
etName = (EditText) view.findViewById(R.id.etName);
etComment = (EditText) view.findViewById(R.id.etComment);
ratingBar = (RatingBar) view.findViewById(R.id.ratingBar);
ibSubmit = (ImageButton) view.findViewById(R.id.ibSubmit);
//TextView tvcm = (TextView) view.findViewById(R.id.tvComment);
Log.d(TAG, "Fragment created.");
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ibSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String strName = etName.getText().toString().trim();
if(strName.length() <= 0) {
Toast.makeText(context, "نام خود را وارد کنید", Toast.LENGTH_LONG).show();
return;
}
String strComment = etComment.getText().toString().trim();
if(strComment.length() <= 0) {
Toast.makeText(context, "متن جک را وارد کنید", Toast.LENGTH_LONG).show();
return;
}
int rate = (int) ratingBar.getRating();
if(rate <= 0) {
Toast.makeText(context, "امتیاز جکتان را وارد کنید", Toast.LENGTH_LONG).show();
return;
}
String deviceId = getDeviceId();
new SendFormTask(deviceId, strName, rate, strComment).execute();
}
private TextView findViewById(int tvcomment) {
// TODO Auto-generated method stub
return null;
}
});
}
private String getDeviceId() {
return Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
}
/*----------------------------------------------------------------------------
* This method is responsible for creating another thread in parallel with
* main UI thread in order to send a request to server and get data (if any).
* ---------------------------------------------------------------------------*/
public class SendFormTask extends AsyncTask<Void, Void, Boolean> {
String deviceId, name, comment;
int rate;
SendFormTask(String deviceId, String strName, int rate, String strComment) {
this.deviceId = deviceId;
this.name = strName;
this.rate = rate;
this.comment = strComment;
}
#Override
protected void onPreExecute() {
Log.d(TAG, "SendFormTask is about to start....");
onRequestToServer.DisplayLoding(true);
}
#Override
protected Boolean doInBackground(Void... params) {
boolean status = false;
HttpURLConnection urlConnection = null;
try {
//URL url = new URL(LinkManager.getFormAPI(deviceId, name, rate, comment));
//URL url = new URL(LinkManager.getFormAPI(deviceId, name, rate, comment));
String url1 = LinkManager.getFormAPI(deviceId, name, rate, comment) ;
//String stUrl = URLEncoder.encode(url1, "UTF-8");
URL url = new URL(url1);
Log.d(TAG, "Try to open: " + url.toString());
urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
Log.d(TAG, "Response code is: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream())
);
if (in != null) {
StringBuilder strBuilder = new StringBuilder();
// Read character by character
int ch = 0;
while ((ch = in.read()) != -1)
strBuilder.append((char) ch);
// get returned message and show it
String response = strBuilder.toString();
Log.d("Server response:", response);
if(response.equalsIgnoreCase("1"))
status = true;
}
in.close();
}
}
catch(MalformedURLException e){
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
return status;
}
#Override
protected void onPostExecute(Boolean result) {
Log.d(TAG, "SendFormTask finished its task.");
onRequestToServer.DisplayLoding(false);
if(result)
Toast.makeText(context, "جک شما ارسال شد, منتظر تایید آن باشید", Toast.LENGTH_LONG).show();
else
Toast.makeText(context, "جک شما ارسال شد , منتظر تایید آن باشید", Toast.LENGTH_LONG).show();
}
}
}
and my LinkManager.class :
package com.skyline.jimmy;
public class LinkManager {
private final static String API_FORM = "http://jimmy.ir/jimmy/sendjoke.php?p1=###&p2=####&p3=#####&p4=######";
private final static String API_Comment = "http://jimmy.ir/jimmy/index.php?p1=###";
public static String getFormAPI(String deviceId, String name, int rate, String comment) {
String url = API_FORM;
url = url.replaceAll("###", deviceId);
url = url.replaceAll("####", name);
url = url.replaceAll("#####", Integer.toString(rate));
url = url.replaceAll("######", comment);
return url;
}
public static String getCommentAPI(String deviceId) {
String url = API_Comment;
url = url.replaceAll("###", deviceId);
return url;
}
}
See this link for accepted characters in URL. Persian characters are not supported as get parameters in a url. You can use http post for sending the data to the server.
first make sure that you are sending right word (persian ) from android side , maybe your java code not sending text in UTF-8 , then make sure that your server, database , and table collection are utf8_persian_ci
and change this
BufferedReader in = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
to this:
BufferedReader in = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream(), "utf-8"),8);

Error org.json.JSONException: Value <html><head><title> Error of type java.lang.String cannot be converted to JSONObject

I have a Android app about Public Transportation, and I have a PHP script that connects to mySQL database. This is the main.java
package com.chera.trans;
import com.chera.trans.R;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public class Main extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.traseu2:
Intent traseu2 = new Intent(this, Traseu2.class);
this.startActivity(traseu2);
break;
case R.id.traseu401:
Intent traseu401 = new Intent(this, Traseu401.class);
this.startActivity(traseu401);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
}
And this is the code for Traseu2.java
package com.chera.trans;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.chera.trans.R;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class Traseu2 extends Activity {
private String jsonResult;
private String url = "http://transploiesti.tk/2.php";
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.traseu2);
listView = (ListView) findViewById(R.id.listView1);
accessWebService();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.traseu2:
Intent traseu2 = new Intent(this, Traseu2.class);
this.startActivity(traseu2);
break;
case R.id.traseu401:
Intent traseu401 = new Intent(this, Traseu401.class);
this.startActivity(traseu401);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
// Async Task to access the web
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
}
catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
}// end async task
public void accessWebService() {
JsonReadTask task = new JsonReadTask();
// passes values for the urls string array
task.execute(new String[] { url });
}
// build hash set for list view
public void ListDrwaer() {
List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("traseudoi");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String name = jsonChildNode.optString("Statie");
String number = jsonChildNode.optString("Oraplecare");
String outPut = "Autobuzul pleaca din " + name + " la ora " + number;
employeeList.add(createEmployee("employees", outPut));
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList,
android.R.layout.simple_list_item_1,
new String[] { "employees" }, new int[] { android.R.id.text1 });
listView.setAdapter(simpleAdapter);
}
private HashMap<String, String> createEmployee(String name, String number) {
HashMap<String, String> employeeNameNo = new HashMap<String, String>();
employeeNameNo.put(name, number);
return employeeNameNo;
}
}
` Why I receive this error when I m running the app? Thanks!
HTML is not JSON, and it can not be parsed into JSONObjects. The top answer for org.json.JSONException: Value <!DOCTYPE of type java.lang.String cannot be converted to JSONObject is pretty good at explaining this further.

after logged in ,remain in home_screen until logout

I want to send the username and password to the server and it returns a response whether the username and password matches. I do not want to ask for login each time my app starts, instead I want to remain in the home_screen until I logout from my android app. How can I do this? any example will be thankfull..
package com.example.test5;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity implements OnClickListener{
private EditText username;
private EditText password;
private Button login;
static String u;
static String p;
Context context = MainActivity.this;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText)findViewById(R.id.editText1);//Visibility
password = (EditText)findViewById(R.id.editText2);//Visibility
login = (Button)findViewById(R.id.button1);//Visibility
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
u = username.getText().toString();
p = password.getText().toString();
Toast.makeText(MainActivity.this, "Checking User Login",Toast.LENGTH_SHORT).show();
new MyAsyncTask_Login(context).execute(u,p);
}
});
}
#Override
public void onClick(DialogInterface dialog, int which) {
}
}
my asynctask class
package com.example.test5;
import java.io.StringReader;
import java.util.LinkedList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.XmlResourceParser;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.widget.Toast;
public class MyAsyncTask_Login extends AsyncTask<String, Void, String>{
public static final String MyPREFERENCES = "MyPrefs" ; //editor: never used
public static final String userName = "name";
public static final String Password = "password";
SharedPreferences sharedpreferences; //editor: never used
private Context context;
public MyAsyncTask_Login(Context context) {
this.context = context;
}
#Override
protected String doInBackground(String... params) {
String response = new Login_WebService().checkLogin(params[0], params[1]);
return response;
}
#Override
protected void onPostExecute(String result) {
String strResponse = result;
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser parser = factory.newPullParser();
parser.setInput(new StringReader(strResponse));
List<String> tags = new LinkedList<String>();
tags.add("valid");
for (int type = parser.next(); type != XmlResourceParser.END_DOCUMENT; type = parser.next()) {
if (type == XmlResourceParser.START_TAG) {
String name = parser.getName();
if (tags.contains(name)) {
type = parser.next();
if (parser.getText().trim().equals("1")) {
Toast.makeText(context, "logged in succesfully.",Toast.LENGTH_SHORT).show();
try {
String user = MainActivity.u;
String pass = MainActivity.p;
Intent i = new Intent(context,Home_page.class);
context.startActivity(i);
}
catch (Exception e) {
Toast.makeText(context, e.toString(),Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(context, "Invalid User",Toast.LENGTH_SHORT).show();
}
}
}
}
}
catch (Exception e) {
}
}
}
You can do like this:
Save your login data in shared Preferences.
When the user login:
protected void doInBackground(Activity... params) {
Activity activity = (Activity) params[0];
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);//Pass activity in params o
Editor editor = prefs.edit();
editor.putString("username",u);
editor.putString("password",p);
editor.commit();
}
in on create when the user restart the app read the shared preferences:
u = prefs.getString("username", "");
p = prefs.getString("password", "");
if(u.equals("") || p.equals(""))
//user needs new login
else
//user already login
To make logout put "" in sharedpreferences.

Categories

Resources