I'm trying to create Log in using localhost - java

I want to create an survey application, but it stuck on if (con == null) {z = "Please check your internet connection"; i have searched on google, and i am a newbie in java, i know this means that the application is not yet connected to the connection but i don't know where i did wrong
this is Connectionclass.java for connecting to the localhost
import android.annotation.SuppressLint;
import android.os.StrictMode;
import android.util.Log;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class ConnectionClass {
#SuppressLint("NewAPI")
public Connection Conn() {
String kelas = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://10.0.2.2:3306/kartu_tani";
String uname = "";
String password = "";
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection connection = null;
try {
Class.forName(kelas).newInstance();
connection = DriverManager.getConnection(url, uname, password);
} catch (ClassNotFoundException e) {
Log.e("ERROR", e.getMessage());
} catch (SQLException e) {
Log.e("ERROR", e.getMessage());
} catch (Exception e) {
Log.e("ERROR", e.getMessage());
}
return connection;
}
}
and this is the login page
import androidx.appcompat.app.AppCompatActivity;
import android.app.DownloadManager;
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.telecom.Call;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.e_survey.Background;
import com.example.e_survey.ConnectionClass;
import com.example.e_survey.Model.ProfilDesa;
import com.example.e_survey.R;
import com.example.e_survey.Util.Constant;
import com.example.e_survey.Util.SharedPreferenceCustom;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import static com.bumptech.glide.request.Request.*;
public class LoginActivity extends AppCompatActivity {
Button btnLogin;
SharedPreferenceCustom sharedPreferenceCustom;
EditText etUsername,etPassword;
ConnectionClass connectionClass;
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
etUsername = findViewById(R.id.et_username);
etPassword = findViewById(R.id.et_password);
btnLogin = findViewById(R.id.btnLogin);
connectionClass = new ConnectionClass();
progressDialog = new ProgressDialog(this);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doLogin doLogin = new doLogin();
doLogin.execute("");
}
});
/*sharedPreferenceCustom = SharedPreferenceCustom.getInstance(this);
initProgresDialog();
initFindView();*/
}
/*private void initProgresDialog() {
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Please Wait...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(false);
}*/
private class doLogin extends AsyncTask<String, String, String> {
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
String z = "";
boolean isSuccess = false;
String un, pw;
#Override
protected void onPreExecute() {
progressDialog.setMessage("Please Wait");
progressDialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
if (username.trim().equals("")) {
z = "Masukkan Username Anda!";
} else if (password.trim().equals("")) {
z = "Masukkan Password Anda!";
} else {
try {
ConnectionClass db = new ConnectionClass();
Connection con = db.Conn();
if (con == null) {
z = "Please check your internet connection";
} else {
String query = "select * from userlogin where username = '"+ username +"' and password = '"+ password +"'";
Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery(query);
while (rs.next()) {
un = rs.getString(1);
pw = rs.getString(2);
if (un.equals(username) && pw.equals(password)) {
isSuccess = true;
z = "Login Successfull";
} else {
isSuccess = false;
}
}
}
} catch (Exception e) {
isSuccess = false;
z = "Exception" + e;
}
}
return z;
}
#Override
protected void onPostExecute(String s) {
Toast.makeText(getBaseContext(), "" + z, Toast.LENGTH_LONG).show();
if (isSuccess) {
Intent intent = new Intent(LoginActivity.this, ProfilDesaActivity.class);
startActivity(intent);
}
progressDialog.hide();
}
}
}
thank you

Related

my php code to connect with database for android

im trying to connect my android app with the data base im using for the website but somehow it doesnt want to connect
this is my java code im using for the connect
Android manifest i added
<uses-permission android:name="android.permission.INTERNET"></uses-
permission>
background.java
package com.example.myapplication;
import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class backgroundworker extends AsyncTask<String,Void, String> {
Context context;
AlertDialog alertDialog;
backgroundworker(Context ctx){
context =ctx;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://10.0.2.2//android/login.php";
if (type.equals("login")){
try {
String Email = params[1];
String Password = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection =
(HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new
OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("Email","UTF-
8")+"="+URLEncoder.encode(Email,"UTF-8")+"&"
+ URLEncoder.encode("Password","UTF-
8")+"="+URLEncoder.encode(Password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine())!=null){
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
alertDialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
login.java
package com.example.myapplication;
import android.content.Intent;
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.TextView;
public class login extends AppCompatActivity implements View.OnClickListener
{
Button liButton;
EditText liEmail, liPassword;
TextView liSignup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
liEmail = (EditText) findViewById(R.id.liEmail);
liPassword = (EditText) findViewById(R.id.liPassword);
liButton =(Button) findViewById(R.id.liButton);
liSignup= (TextView) findViewById(R.id.liSignup);
liButton.setOnClickListener(this);
liSignup.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.liButton:
String Email = liEmail.getText().toString();
String Password = liPassword.getText().toString();
String type = "login";
BackgroundWorker backgroundworker = new BackgroundWorker(this);
backgroundworker.execute(type, Email, Password);
break;
case R.id.liSignup:
startActivity(new Intent(this, signup.class));
break;
}
}
}
this is my php code
<?php
$conn = mysqli_connect('127.0.0.1','root','','signup');
?>
<?php
include('conn.php');
if(!session_id())
session_start();
if (isset($_POST['Email'])
and isset($_POST['Password'])
and !empty($_POST['Email'])
and !empty($_POST['Password'])){
$Email = $_POST['Email'];
$Password= $_POST['Password'];
$getinfo = "SELECT * FROM users WHERE Email ='$Email' LIMIT 1";
$res = mysqli_query($conn,$getinfo);
$row = mysqli_fetch_assoc($res);
if (mysqli_num_rows($res)>0) {
$dbPassword = $row['Password'];
$Password = PASSWORD_VERIFY($Password, $dbPassword);
if ($Email == $row ['Email'] and $Password == $dbPassword) {
$id = $row['id'];
$_SESSION['id'] = $id;
exit();
} else{
echo 'Wrong Email or Password.';
}
} else{
echo 'Wrong Email or Password.';
}
}
?>
i believe my java code is right but im not sure what to do with my php if there is something wrong
this line
if ($Email == $row ['Email'] and $Password == $dbPassword) {
is wrong/the problem. You already password_verified, which returns a boolan, so it should be.
if ($Email == $row ['Email'] and $Password) {
And you don't need to re-check if $Email == $row ['Email'], because you queried for it already.
So you can reduce your code to:
if (mysqli_num_rows($res)>0) {
$dbPassword = $row['Password'];
if (PASSWORD_VERIFY($Password, $dbPassword)) {
$id = $row['id'];
$_SESSION['id'] = $id;
exit();
} else {
//...

Send an image and other string parameters to server using HttpURLConnection and Base64

I am trying to send an image and some string values from android to a php script using HttpURLConnection. I have successfully done so with strings, but can't seem to get it right with the image. I am using Base64 (android.util.Base64) to convert my image to a string to send it. Now, I have a separate HttpParse.java file I use to send all my info to the server, and I think that is where the change needs to be made to allow the image, but I'm not sure, (I am newer to java/android development). I've researched several similar questions, but they aren't fully clicking for me for what I'm doing wrong. Also, I have tested that I am successfully converting the image to a string. Here is my code:
EDIT I got a little farther... After testing, I am getting the issue because the three variables I try to get with getArguments() are coming back as null... But, I can't figure out how to get them to come through successfully... I added the code for how I start my fragment and how I try to get my bundle
My fragment start:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_units);
Intent intent = getIntent();
LexaUser = intent.getStringExtra("UserName");
ReadOnly = intent.getStringExtra("ReadOnly");
Password = intent.getStringExtra("Password");
QA = intent.getStringExtra("QA");
SearchValue = intent.getStringExtra("SearchInput");
bottomNavigation = (BottomNavigationView)findViewById(R.id.bottom_navigation);
bottomNavigation.inflateMenu(R.menu.bottom_menu);
fragmentManager = getSupportFragmentManager();
bottomNavigation.getMenu().getItem(0).setChecked(true);
UnitDetailsHeader = findViewById(R.id.UnitDetailsViewTitle);
UnitDetailsHeader.setText(SearchValue);
UnitSizeText = findViewById(R.id.UnitSize);
UnitStatusText = findViewById(R.id.UnitStatus);
if (SearchValue.contains("-")) {
getUnitDetails(SearchValue, LexaUser);
} else {
getSiblings();
}
bottomNavigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.action_search:
fragment = new NewUnitStatusFragment();
break;
case R.id.action_cart:
fragment = new PendingUnitStatusFragment();
break;
case R.id.action_hot_deals:
fragment = new FinalUnitStatusFragment();
break;
case R.id.action_siblings:
fragment = new SiblingUnitFragment();
break;
}
Bundle connBundle = new Bundle();
connBundle.putString("SearchValue", SearchValue);
connBundle.putString("LexaUser", LexaUser);
connBundle.putString("Password", Password);
connBundle.putString("QA", QA);
fragment.setArguments(connBundle);
final FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.main_container, fragment).commit();
return true;
}
});
}
And where I try to get my arguments: (I originally had in onCreateView but then tried to move it to onCreate. But the behavior was the same)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
SearchValue = getArguments().getString("SearchValue");
LexaUser = getArguments().getString("LexaUser");
Password = getArguments().getString("Password");
}
}
My fragment where I get the image and send my data:
package [my_package];
import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import android.util.Base64;
import java.util.HashMap;
import static android.app.Activity.RESULT_OK;
public class NewUnitStatusFragment extends Fragment {
Context newUnitStatusContext;
Activity newUnitStatusActivity;
Intent cameraIntent;
ProgressDialog progressDialog;
String ReadOnly;
String LexaUser;
String Password;
String SearchValue;
String finalResultNewUnitStatus;
String HttpURLNewUnitStatus = "https://[path/to/file]/insertNewUnitStatus.php";
HashMap<String, String> hashMapNewUnitStatus = new HashMap<>();
HttpParse httpParse = new HttpParse();
Spinner statusSpinner;
Spinner generalCauseSpinner;
EditText newUSComment;
Button addPhotoBtn;
ImageView newUnitStatusImage;
Button addNewUnitStatus;
String newUnitStatus;
String generalCause;
String newUnitStatusComment;
String newUnitStatusPhoto;
String message;
private static final int PICK_FROM_GALLERY = 1;
public NewUnitStatusFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_newunitstatus, container, false);
newUnitStatusContext = getContext();
newUnitStatusActivity = getActivity();
statusSpinner = view.findViewById(R.id.Status);
generalCauseSpinner = view.findViewById(R.id.GeneralCause);
newUSComment = view.findViewById(R.id.NewComment);
newUnitStatusImage = view.findViewById(R.id.AddPhoto);
addPhotoBtn = view.findViewById(R.id.AddPhotosLabel);
addNewUnitStatus = view.findViewById(R.id.addBtnNewUnitStatus);
ArrayAdapter<CharSequence> statusSpinnerAdapter = ArrayAdapter.createFromResource(newUnitStatusContext,
R.array.new_unit_status_array, android.R.layout.simple_spinner_item);
statusSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
statusSpinner.setAdapter(statusSpinnerAdapter);
newUnitStatus = statusSpinner.getSelectedItem().toString();
ArrayAdapter<CharSequence> generalCauseSpinnerAdapter = ArrayAdapter.createFromResource(newUnitStatusContext,
R.array.status_general_cause_array, android.R.layout.simple_spinner_item);
generalCauseSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
generalCauseSpinner.setAdapter(generalCauseSpinnerAdapter);
generalCause = generalCauseSpinner.getSelectedItem().toString();
addPhotoBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startGallery();
}
});
// Set a click listener for the text view
addNewUnitStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
newUnitStatus = statusSpinner.toString();
generalCause = generalCauseSpinner.toString();
newUnitStatusComment = newUSComment.toString();
if (getArguments() != null) {
SearchValue = getArguments().getString("SearchValue");
LexaUser = getArguments().getString("LexaUser");
Password = getArguments().getString("Password");
}
addNewUnitStatus(SearchValue, newUnitStatus, generalCause, newUnitStatusComment, newUnitStatusPhoto, LexaUser, Password);
}
});
return view;
}
private void startGallery() {
cameraIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
cameraIntent.setType("image/*");
cameraIntent.setAction(Intent.ACTION_GET_CONTENT);
if (cameraIntent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(cameraIntent, 1000);
} else {
Toast.makeText(newUnitStatusContext, "Error: " + cameraIntent + " - cameraIntent.resolveActivity(getActivity().getPackageManager()) = null", Toast.LENGTH_LONG).show();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//super method removed
if (resultCode == RESULT_OK) {
if (requestCode == 1000) {
Uri returnUri = data.getData();
try {
Bitmap bitmapImage = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), returnUri);
newUnitStatusImage.setImageBitmap(bitmapImage);
newUnitStatusImage.buildDrawingCache();
Bitmap bm = newUnitStatusImage.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
newUnitStatusPhoto = Base64.encodeToString(b, Base64.DEFAULT);
} catch (IOException ioEx) {
ioEx.printStackTrace();
Toast.makeText(newUnitStatusContext, "ioEx Error: " + ioEx, Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(newUnitStatusContext, "Error: " + requestCode, Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(newUnitStatusContext, "Error: " + resultCode, Toast.LENGTH_LONG).show();
}
}
public void addNewUnitStatus(String searchInput, String newUnitStatus, String generalCause, String newUnitStatusComment, String newUnitStatusPhoto, String lexaUser, String password) {
class NewUnitStatusClass extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(newUnitStatusContext, "Loading Data", null, true, true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
if (httpResponseMsg != null) {
try {
JSONObject object = new JSONObject(httpResponseMsg);
message = object.getString("message");
Toast.makeText(newUnitStatusContext, httpResponseMsg, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
Toast.makeText(newUnitStatusContext, "Error: " + e.toString(), Toast.LENGTH_LONG).show();
} // catch (JSONException e)
progressDialog.dismiss();
} else {
progressDialog.dismiss();
Toast.makeText(newUnitStatusContext, "HttpResponseMsg is null.", Toast.LENGTH_LONG).show();
}
}
#Override
protected String doInBackground(String... params) {
hashMapNewUnitStatus.put("searchinput", params[0]);
hashMapNewUnitStatus.put("newUnitStatus", params[1]);
hashMapNewUnitStatus.put("generalCause", params[2]);
hashMapNewUnitStatus.put("newUnitStatusComment", params[3]);
hashMapNewUnitStatus.put("newUnitStatusPhoto", params[4]);
hashMapNewUnitStatus.put("lexauser", params[5]);
hashMapNewUnitStatus.put("password", params[6]);
finalResultNewUnitStatus = httpParse.postRequest(hashMapNewUnitStatus, HttpURLNewUnitStatus);
return finalResultNewUnitStatus;
}
}
NewUnitStatusClass newUnitStatusClass = new NewUnitStatusClass();
newUnitStatusClass.execute(searchInput, newUnitStatus, generalCause, newUnitStatusComment, newUnitStatusPhoto, lexaUser, password);
}
}
And my code to do that actuall HttpURLConnection: HttpParse.java
package [my_package];
import android.app.ListActivity;
import android.widget.ArrayAdapter;
import org.json.JSONArray;
import org.json.JSONObject;
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;
public class HttpParse extends ListActivity {
String FinalHttpData = "";
String Result;
BufferedWriter bufferedWriter;
OutputStream outputStream;
BufferedReader bufferedReader;
StringBuilder stringBuilder = new StringBuilder();
URL url;
public String postRequest(HashMap<String, String> Data, String HttpUrlHolder) {
try {
url = new URL(HttpUrlHolder);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setReadTimeout(14000);
httpURLConnection.setConnectTimeout(14000);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
outputStream = httpURLConnection.getOutputStream();
bufferedWriter = new BufferedWriter(
new OutputStreamWriter(outputStream, "UTF-8"));
bufferedWriter.write(FinalDataParse(Data));
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
bufferedReader = new BufferedReader(
new InputStreamReader(
httpURLConnection.getInputStream()
)
);
FinalHttpData = bufferedReader.readLine();
}
else {
FinalHttpData = "Something Went Wrong";
}
} catch (Exception e) {
e.printStackTrace();
}
return FinalHttpData;
}
public String FinalDataParse(HashMap<String,String> hashMap2) throws UnsupportedEncodingException {
for(Map.Entry<String,String> map_entry : hashMap2.entrySet()){
stringBuilder.append("&");
stringBuilder.append(URLEncoder.encode(map_entry.getKey(), "UTF-8"));
stringBuilder.append("=");
stringBuilder.append(URLEncoder.encode(map_entry.getValue(), "UTF-8"));
}
Result = stringBuilder.toString();
return Result ;
}
}
All help is appreciated! Thank you!
P.S. my app shows the following error:
W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
This then leads to this:
E/JSONException: Error: org.json.JSONException: End of input at character 0 of

onPostExecute of AsyncTask not called

I'm relatively new to Android app development and wonder what I'm doing wrong. I have an AsyncTask that connects to my web server with username and password and returns the user dataset as json object. Unfortunately I can't get the json string, because onPostExecute() in my AsyncHttpReading class doesn't seem to get called. Why?
MainActivity.java
package com.alphavoice.sampleproject;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import com.alphavoice.sampleproject.community.user.User;
import com.alphavoice.sampleproject.util.HttpReader;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean isLoggedIn = (appPrefs.getInt("userId", 0) != 0) ? true : false;
if (isLoggedIn) {
renderCommunityView();
}
else {
setContentView(R.layout.activity_main);
final Button btnLogin = (Button) findViewById(R.id.btn_login);
final EditText etUsername = (EditText) findViewById(R.id.et_username);
final EditText etPassword = (EditText) findViewById(R.id.et_password);
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
String loginUrl = "http://example.com/websrv/get_user.php?username=" + username + "&password=" + password;
AsyncHttpReading httpReading = new AsyncHttpReading();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
int corePoolSize = 60;
int maximumPoolSize = 80;
int keepAliveTime = 10;
BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>(maximumPoolSize);
Executor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, workQueue);
// httpReading.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, loginUrl);
httpReading.executeOnExecutor(threadPoolExecutor, loginUrl);
}
else {
httpReading.execute(loginUrl);
}
if (httpReading.getLoggedInUser() != null) {
// renderCommunityView();
btnLogin.setBackgroundColor(Color.GREEN);
}
else {
// wrong combination of username & password => try again
etUsername.setBackgroundColor(Color.rgb(255, 204, 204));
etPassword.setBackgroundColor(Color.rgb(255, 204, 204));
}
}
});
}
}
private void renderCommunityView() {
setContentView(R.layout.activity_community);
}
private class AsyncHttpReading extends AsyncTask<String, Void, String> {
private String response = "";
private User loggedInUser = null;
public AsyncHttpReading() { }
public String getResponse() {
return response;
}
public User getLoggedInUser() {
return loggedInUser;
}
#Override
protected String doInBackground(String... urls) {
HttpReader httpReader = new HttpReader(urls[0]);
response = httpReader.getResponse();
return response;
}
#Override
protected void onPostExecute(String response) {
try {
JSONObject userData = new JSONObject(this.getResponse()).getJSONObject("0");
if (userData != null) {
loggedInUser = new User(userData);
}
} catch (JSONException e) {
Log.e("SAMPLEPROJECT", "Could not parse json data!");
}
}
}
}
HttpReader.java
package com.alphavoice.sampleproject.util;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import android.util.Log;
public class HttpReader {
private String url = "";
public HttpReader(String url) {
this.url = url;
}
public String getURL() {
return url;
}
public String getResponse() {
URL urlObj = null;
HttpURLConnection connection = null;
// http request
try {
urlObj = new URL(url);
connection = (HttpURLConnection) urlObj.openConnection();
connection.setReadTimeout(10000);
connection.setConnectTimeout(15000);
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
} catch (Exception e) {
Log.e("SAMPLEPROJECT", "Could not connect to web server!");
}
// read stream
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(urlObj.openStream()));
StringBuffer buffer = new StringBuffer();
char[] chars = new char[1024];
int read = 0;
while ((read = reader.read(chars)) != -1) {
buffer.append(chars, 0, read);
}
reader.close();
return buffer.toString();
} catch (IOException e) {
Log.e("SAMPLEPROJECT", "Could not open stream!");
}
return null;
}
}
User.java
package com.alphavoice.sampleproject.community.user;
import org.json.JSONObject;
public class User {
public User(JSONObject dataset) {
}
}

unable get json from url

i have to create simple login page where after entering username and password we click to submit button. when we click on submit button then it goes to server and check the username and other information if the info matches then it moves to next activity otherwise nothing will happen . below is my code . i dont know how to do after getting response from the server.
package com.example.dev_1.myapplication;
import android.app.DownloadManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.net.Uri
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.ref.ReferenceQueue;
import java.net.HttpURLConnection;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.sql.Connection;
public class MainActivity extends AppCompatActivity {
Button button;
String connectionString, params;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText username = (EditText) findViewById(R.id.editText);
final EditText password = (EditText) findViewById(R.id.editText2);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener((new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.button1) {
String userNameString = username.getText().toString();
String passwordString = password.getText().toString();
String url = "http://122.160.78.189:82/androidserver/LoginSalesPerson";
String params = null;
try {
params = "user=" + URLEncoder.encode(userNameString, "UTF-8") + "&password=" + URLEncoder.encode(passwordString, "UTF-8") + "&appVersion=1.26";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
JSONArray dataJsonArr = null;
new Mytask().execute(url, params);
}
}
}));
}
private void checkLogin(String result) throws JSONException {
String url = "http://122.160.78.189:82/androidserver/LoginSalesPerson";
JSONArray user = null;
try{
// Creating new JSON Parser
///JSONParser jParser = new JSONParser();
// Getting JSON from URL
// JSONObject json = jParser.getJSONFromUrl(url);
if (result != null)
{
//JSONObject emp=(new JSONObject(url).getJSONObject("username"));
JSONObject emp = new JSONObject(result.toString());
String username=emp.getString("userName");
//String empspassword=emp.getString("password");
String str="username:"+username;
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
intent.putExtra("username", str);
startActivity(intent);}
}catch (Exception e) {
e.printStackTrace();
}
}
// EditText usernameString = (EditText) findViewById(R.id.editText);
// String str = usernameString.getText().toString();
// if (sharedPreferences.equals(str)) {
// Intent intent = new Intent(MainActivity.this, Main2Activity.class);
// intent.putExtra("username", str);
//startActivity(intent);
// To retrieve value from shared preference in another activity
// sharedPreferences = getApplicationContext().getSharedPreferences(
// "sharedPrefName", 0);
// id = sharedPreferences.getString("key_name", "defaultvalue");
class Mytask extends AsyncTask<String, Void, String> {
// Runs in UI before background thread is called
#Override
protected void onPreExecute() {
setProgressBarVisibility(true);
// Do something like display a progress bar
}
// This is run in a background thread
#Override
protected String doInBackground(String... params) {
return getFromServer(params[0], params[1]);
}
// This runs in UI when background thread finishes
#Override
protected void onPostExecute(String result) {
try {
checkLogin(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
public String getFromServer(String connectionString, String params) {
String response = "";
try {
// android.os.Debug.waitForDebugger();
URL url = new URL(connectionString);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setConnectTimeout(10 * 1000); //10 Seconds
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Content-Length", "" + Integer.toString(params.getBytes().length));
con.setRequestProperty("Content-Language", "en-US");
con.setUseCaches(false);
con.setDoInput(true);
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(params);
wr.flush();
wr.close();
InputStream is = con.getInputStream();
response = read(is);
} catch (Exception e) {
e.printStackTrace();
} finally {
return response;
}
}
private String read(InputStream in) {
BufferedReader reader;
StringBuilder response = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
return response.toString();
}
}
}
}

how to verify login input with database php MySQL

please help
i'm doing a loging activity for my android application, i checked the email and password with my database using this code
<?php
try
{
// On se connecte à MySQL
$bdd = new PDO('mysql:host=localhost;dbname=application;charset=utf8', 'root', '');
}
catch(Exception $e)
{
// En cas d'erreur, on affiche un message et on arrête tout
die('Erreur : '.$e->getMessage());
echo 'base de donnee n est pas connecte';
}
//Getting values
$username = $_POST['editusername'];
$password = $_POST['editpassword'];
//contact surgat
// On affiche chaque entrée une à une
$reponse = $bdd->query("SELECT * FROM personne WHERE Email='$username' AND Motpass='$password'");
while ($donnees = $reponse->fetch())
{
//if we got some result
if(isset($donnees)){
//displaying success
echo "success";
}else{
//displaying failure
echo "failure";
}
$reponse->closeCursor();
}
?>
and i'm working with android studio this is the loginactivity.java that i used in it AsyncTask to get the result
package com.example.yh.log;
import android.app.Activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
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.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MainActivity extends Activity {
private EditText TextUserName;
private EditText TextPassword;
public static final String USER_NAME = "USERNAME";
String username;
String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onLoginClick(View view){
TextUserName = (EditText) findViewById(R.id.editusername);
TextPassword = (EditText) findViewById(R.id.editpassword);
username=TextUserName.getText().toString();
password=TextPassword.getText().toString();
if(username.isEmpty())
Toast.makeText(getBaseContext(),"Entrez votre username",Toast.LENGTH_SHORT).show();
else if(password.isEmpty())
Toast.makeText(getBaseContext(),"Entrez votre mot de passe",Toast.LENGTH_SHORT).show();
else {
String urlString = "http://192.168.173.1/Search/login.php";
LoginTask loginTask = new LoginTask();
loginTask.execute(urlString);
}
}
private class LoginTask extends AsyncTask<String,Void,String>
{
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(MainActivity.this, "Please wait", "Loading...");
}
#Override
protected String doInBackground(String... params) {
HttpURLConnection c=null;
try {
String urlString=params[0];
URL url=new URL(urlString);
c=(HttpURLConnection)url.openConnection();
c.setRequestMethod("POST");
c.setConnectTimeout(15000 /* milliseconds */);
c.setDoInput(true);
c.setDoOutput(true);
c.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
String s = "username="+username+"&password=" + password;
c.setFixedLengthStreamingMode(s.getBytes().length);
PrintWriter out = new PrintWriter(c.getOutputStream());
out.print(s);
out.close();
c.connect();
int mStatusCode = c.getResponseCode();
String result="";
switch (mStatusCode) {
case 200:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
br.close();
result = sb.toString();
}
return result;
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
return "Error connecting to server";
} finally {
if (c != null) {
try {
c.disconnect();
} catch (Exception ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex);
}
}
}
}
#Override
protected void onPostExecute(String s) {
//super.onPostExecute(s);
String ss = s;
loadingDialog.dismiss();
if(ss=="success") {
Intent intent = new Intent(MainActivity.this, UserProfile.class);
intent.putExtra(USER_NAME, username);
finish();
startActivity(intent);
}else{
Toast.makeText(getApplicationContext(), "invalide username or password", Toast.LENGTH_LONG).show();
}}
}
}
i keep geting this error in php code "indefined index editusername" when i run the activity and hit the button althought i declared the edit text with same ID in loginactivity.xml i have changed it many times but still not working
  <EditText android:id="#+id/editusername"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
thank you.
The problem is that this in the Java:
String s = "username="+username+"&password=" + password;
Doesn't match up with this in the PHP:
//Getting values
$username = $_POST['editusername'];
$password = $_POST['editpassword'];
Also note that you should use URLEncoder.encode() for values that come from user input:
String charset = "UTF-8";
String s = "editusername=" +
URLEncoder.encode(username, charset) +
"&editpassword=" +
URLEncoder.encode(password, charset);
Also, you can't use == with Strings in Java, you need to use the equals() method:
#Override
protected void onPostExecute(String s) {
//super.onPostExecute(s);
String ss = s;
loadingDialog.dismiss();
//use equals() instead:
if(ss.equals("success")) {
Intent intent = new Intent(MainActivity.this, UserProfile.class);
intent.putExtra(USER_NAME, username);
finish();
startActivity(intent);
}else{
Toast.makeText(getApplicationContext(), "invalide username or password", Toast.LENGTH_LONG).show();
}}
}

Categories