Good day to all.
I'm creating a social android app for posting offers of services for the skilled & talented within our univerity. I'm using the conventional languages for android: Java and XML.
But whenever I invoke the createOffer method within the CreateOfferActivity the app crashes without producing any exceptions and simply restarts.
Here's the code for CreateOfferActivity:
package com.italent.italent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.DateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class CreateOfferActivity extends AppCompatActivity {
private EditText offerTitle;
private EditText offerDesc;
private EditText offerMinPrice;
private EditText offerMaxPrice;
private Spinner offerCategory;
private Button crtOffer;
String offCategory;
String imagePath;
public double minPrice;
public double maxPrice;
private static final String TAG = "CreateOfferActivity";
private static final String URL_FOR_CREATING_OFFER = "https://*****/create_offer.php";
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_offer);
offerTitle = (EditText) findViewById(R.id.etOfferTitle);
offerDesc = (EditText) findViewById(R.id.etOfferDesc);
offerMinPrice = (EditText) findViewById(R.id.etMinPrice);
offerMaxPrice = (EditText) findViewById(R.id.etMaxPrice);
offerCategory = (Spinner) findViewById(R.id.spCategories);
crtOffer = (Button) findViewById(R.id.bCreateOffer);
ArrayAdapter<CharSequence> arrAdapter = ArrayAdapter.createFromResource(this,
R.array.category_Array, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
arrAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
offerCategory.setAdapter(arrAdapter);
//Create Offer button onClick listener
crtOffer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
submitOfferForm();
Toast.makeText(CreateOfferActivity.this, "It works...", Toast.LENGTH_LONG).show();
}
});
}
private void submitOfferForm() {
String offTitle = offerTitle.getText().toString();
String offDesc = offerDesc.getText().toString();
//////////Replace image path later with a valid one
imagePath = "Some Image Path";
offCategory = offerCategory.getSelectedItem().toString();
//getting sharedPreferences file named userInfo to retrieve MemberName, Username and branch
SharedPreferences sharedPreferences = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
String ofMName = sharedPreferences.getString("MemberName:", "");
String ofUName = sharedPreferences.getString("UserName:", "");
String ofBranch = sharedPreferences.getString("Branch:", "");
String mnPri = " " + minPrice;
String mxPri = " " + maxPrice;
createOffer(ofMName, ofUName, offTitle, offDesc, ofBranch, mnPri, mxPri, imagePath, offCategory);
}
private void createOffer(final String oMName, final String oUName, final String oTitle, final String oText,
final String oBranch,final String oMinPri, final String oMaxPri, final String oImage, final String oCategory) {
// Tag used to cancel the request
String cancel_req_tag = "offer";
progressDialog.setMessage("Adding your offer...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_FOR_CREATING_OFFER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Offer Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) { // error is set to false, meaning no error
//String user = jObj.getJSONObject("offer").getString("name");
Toast.makeText(CreateOfferActivity.this, "Your Offer has been created!", Toast.LENGTH_SHORT).show();
// Launch Home activity
Intent HomeIntent = new Intent(CreateOfferActivity.this, HomeActivity.class);
startActivity(HomeIntent);
finish();
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(CreateOfferActivity.this, errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Error in creating offer: " + error.getMessage());
Toast.makeText(CreateOfferActivity.this,
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to create offer url
Map<String, String> params = new HashMap<String, String>();
params.put("offerMemberName", oMName);
params.put("offerUserName", oUName);
params.put("offerTitle", oTitle);
params.put("OfferText", oText);
params.put("OfferBranch", oBranch);
params.put("OfferDateTime", DateFormat.getDateTimeInstance().format(new Date()));
params.put("OfferMinPrice", "" + oMinPri);
params.put("OfferMaxPrice", "" + oMaxPri);
params.put("OfferCategory", oCategory);
params.put("OfferImage", oImage);
return params;
}
};
// Adding request to request queue
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq, cancel_req_tag);
}
private void showDialog() {
if (!progressDialog.isShowing())
progressDialog.show();
}
private void hideDialog() {
if (progressDialog.isShowing())
progressDialog.dismiss();
}
}
And the code for create_offer.php
<?php
require_once 'update_user_info.php';
$db = new update_user_info();
// json response array
$response = array("error" => FALSE);
if (isset($_POST['offerTitle']) && isset($_POST['offerMname']) && isset($_POST['offerBranch']) && isset($_POST['offerText']) && isset($_POST['offerImageURL']) &&
isset($_POST['offerDateTime']) && isset($_POST['offerMinPrice']) && isset($_POST['offerMaxPrice']) && isset($_POST['offerCategory']) && isset($_POST['offerUname'])) {
// receiving the post params
$ofTitle = $_POST['offerTitle'];
$ofMName = $_POST['offerMname'];
$ofBranch = $_POST['offerBranch'];
$ofText = $_POST['offerText'];
$ofImageURL = $_POST['offerImageURL'];
$ofDateTime = $_POST['offerDateTime'];
$ofMinPri = $_POST['offerMinPrice'];
$ofMaxPri = $_POST['offerMaxPrice'];
$ofCategory = $_POST['offerCategory'];
$ofUName = $_POST['offerUname'];
// check if user is already existed with the same email
if (!($db->checkExistingUserThruUname($ofUName))) {
// user doesn't exist
$response["error"] = TRUE;
$response["error_msg"] = "Visitors cannot post an offer. Please register first.";
echo json_encode($response);
} else {
// create a new offer
$user = $db->storeOfferInfo($ofTitle, $ofMName, $ofBranch, $ofText, $ofImageURL, $ofDateTime, $ofMinPri, $ofMaxPri, $ofCategory, $ofUName);
if ($offer) {
// offer stored successfully
$response["error"] = FALSE;
$response["offer"]["offTitle"] = $offer["offTitle"];
$response["offer"]["offMname"] = $offer["offMname"];
$response["offer"]["offBranch"] = $offer["offBranch"];
$response["offer"]["offText"] = $offer["offText"];
$response["offer"]["offImageURL"] = $offer["offImageURL"];
$response["offer"]["offDateTime"] = $offer["offDateTime"];
$response["offer"]["offMinPrice"] = $offer["offMinPrice"];
$response["offer"]["offMaxPrice"] = $offer["offMaxPrice"];
$response["offer"]["offCategory"] = $offer["offCategory"];
$response["offer"]["offUname"] = $offer["offUname"];
echo json_encode($response);
} else {
// offer failed to store
$response["error"] = TRUE;
$response["error_msg"] = "Unknown error occurred in offer creation!";
echo json_encode($response);
}
}
} else {
$response["error"] = TRUE;
$response["error_msg"] = "A required field is missing!";
echo json_encode($response);
}
?>
This is the Logcat:
04-22 03:24:38.950 27998-27998/com.italent.italent E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.italent.italent, PID: 27998
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ProgressDialog.setMessage(java.lang.CharSequence)' on a null object reference
at com.italent.italent.CreateOfferActivity.createOffer(CreateOfferActivity.java:122)
at com.italent.italent.CreateOfferActivity.submitOfferForm(CreateOfferActivity.java:113)
at com.italent.italent.CreateOfferActivity.access$000(CreateOfferActivity.java:30)
at com.italent.italent.CreateOfferActivity$1.onClick(CreateOfferActivity.java:86)
at android.view.View.performClick(View.java:5697)
at android.widget.TextView.performClick(TextView.java:10826)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7225)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
P.S. i used almost the exact same java code, php code and database for registration and it works fine but i can't find why it doesn't work with this class.
I appreciate any guidlines or help. Thank you!
progressDialog variable is not initialized. Add following code in your activity onCreate()
ProgressDialog progressDialog = new ProgressDialog(this);
Related
I am making an attendance app on android studio, but whenever I try to log in using correct credentials I need to click twice on the login button to move forward to the next activity. I tried Asynctasks because of its background thread, after the same result I just reverted back
So, at first click nothing happens but as soon as please wait dialog box disappears and if I click like in under a second or two then it moves to the next activity.
clicking on login fetches some data from the server after the server has validated that the login exists and is correct. when data is received then the new activity is supposed to start since that received data will be shown in the next activity. (i have a list that is checked if it has data then it moves forward)
Login Activity code:
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
//sign up and login button
private Button btnSignUp;
private Button btnLogin;
private ProgressDialog progressDialog;
private RequestQueue Queue;
//data URL
private String extractStudentDataURL = "https://asuiot12.000webhostapp.com/checkLoginCredentials.php";
private String extractEnrolmentsDataURL = "https://asuiot12.000webhostapp.com/retrieveEnrolledCoursesData.php";
//editText
private EditText editTextEmail, editTextPassword;
private ConstraintLayout login;
//string variables
public static String inputEmail;
private String inputPassword;
//array list to store enrolled courses data
public static LinkedList<Courses> enrolledCoursesData = new LinkedList();
//static variable
public static StudentData studentData;
//shared preferences to maintain the login status of the user...
public static SharedPreferences sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
login = findViewById(R.id.login_activity);
login.setBackgroundColor(Color.WHITE);
btnSignUp = findViewById(R.id.button_sign_up);
btnLogin = findViewById(R.id.button_login);
// sp = getSharedPreferences("login", MODE_PRIVATE);
editTextEmail = findViewById(R.id.editText_RA_emailAddress);
editTextPassword = findViewById(R.id.editText_RA_password);
//login button listener
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
inputEmail = editTextEmail.getText().toString();
inputPassword = editTextPassword.getText().toString();
if (inputEmail.isEmpty()) {
editTextEmail.setError("Email Required");
editTextEmail.requestFocus();
} else if (inputPassword.isEmpty()) {
editTextPassword.setError("Password Required");
editTextPassword.requestFocus();
} else {
enrolledCoursesData.clear();
ExtractData();
}
}
});
//signUp button listener
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, RegistrationActivity.class);
startActivityForResult(intent, 1);
}
});
}
//retrieving data from the server and checking the login credentials
private void ExtractData() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, extractStudentDataURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
JSONObject data = array.getJSONObject(i);
int success = data.getInt("success");
if (success == 1) {
Long CNIC = data.getLong("CNIC");
String name = data.getString("Full_Name");
String fss = data.getString("FSS");
String regNo = data.getString("Reg_No");
String batch = data.getString("Batch");
String department = data.getString("Department");
int semester = data.getInt("Semester");
Long mobileNo = data.getLong("Mobile_No");
String nationality = data.getString("Nationality");
String MACAddress = data.getString("MAC_Address");
String homeAddress = data.getString("Home_Address");
String email = data.getString("Email");
String loginPassword = data.getString("Login_Password");
String photo = data.getString("Photo");
studentData = new StudentData(new BigInteger(String.valueOf(CNIC)), new BigInteger(String.valueOf(mobileNo))
, semester, name, fss, regNo, batch, department, nationality,
MACAddress, homeAddress, email, loginPassword, photo);
Toast.makeText(MainActivity.this, "Plz wait....", Toast.LENGTH_LONG).show();
// to get data of courses in which student is enrolled
extractDataOfEnrolments(email);
if (!enrolledCoursesData.isEmpty()) {
Intent intent = new Intent(MainActivity.this, CoursesActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("list", enrolledCoursesData);
intent.putExtras(bundle);
startActivity(intent);
}
} else if (success == 0) {
Toast.makeText(MainActivity.this, "Incorrect username or password",
Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error " + error, Toast.LENGTH_SHORT).show();
}
}) {
public Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("email", editTextEmail.getText().toString().trim());
params.put("password", editTextPassword.getText().toString().trim());
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
//retrieving data of enrolments from server
private void extractDataOfEnrolments(final String email) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, extractEnrolmentsDataURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
JSONObject data = array.getJSONObject(i);
String courseCode = data.getString("Course_Code");
String courseName = data.getString("Course_Name");
Courses courses = new Courses(courseCode, courseName);
enrolledCoursesData.add(courses);
}
} catch (Exception e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error " + error, Toast.LENGTH_SHORT).show();
}
}) {
public Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
If layout code or server-side PHP code is required to better understand the question, then please do ask.
You have a misunderstanding as to how threading works.
In your ExtractData method and its onResponse handler, you call extractDataOfEnrolments(), which is itself asynchronous:
// to get data of courses in which student is enrolled
extractDataOfEnrolments(email);
// the list hasn't been filled yet, will be empty!!!
if (!enrolledCoursesData.isEmpty()) {
}
You then immediately inspect the enrolledCoursesData list and start the CoursesActivity if not empty. The extractDataOfEnrolments() has an asynchronous callback (onResponse()) that hasn't completed yet, so the list would be empty.
You might consider moving the startActivity code into extractDataOfEnrolments(), e.g.:
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
JSONObject data = array.getJSONObject(i);
String courseCode = data.getString("Course_Code");
String courseName = data.getString("Course_Name");
Courses courses = new Courses(courseCode, courseName);
enrolledCoursesData.add(courses);
}
// now your list is populated, so now Ok to startActivity
if (!enrolledCoursesData.isEmpty()) {
Intent intent = new Intent(MainActivity.this, CoursesActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("list", enrolledCoursesData);
intent.putExtras(bundle);
startActivity(intent);
}
} catch (Exception e) {
}
I have a problem here ..My app is supposed to send 3 values to the database, from text box etName,etEmailand etPassword
but instead, it is not send anything ...I'm new in android and I don't know some of the things I wrote in my code as I am following some tutorials
this in my code for register
package com.xulucreatives.taxisiyaya;
import androidx.appcompat.app.AppCompatActivity;
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 okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class RegisterActivity extends AppCompatActivity {
EditText etName,etEmail,etPassword;
Button btnReg;
final String url_Register ="http://taxinote.000webhostapp.com/register_user.php";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
etName = findViewById(R.id.RM);
etEmail = findViewById(R.id.et_email);
etPassword = findViewById(R.id.et_password);
btnReg = findViewById(R.id.btn_reg);
btnReg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String Name = etName.getText().toString();
String Email = etEmail.getText().toString();
String Password = etPassword.getText().toString();
new RegisterUser().execute(Name,Email,Password);
// Toast.makeText(RegisterActivity.this,"Im working you bitch",Toast.LENGTH_LONG).show();
}
});
}
public class RegisterUser extends AsyncTask<String,Void,String>{
#Override
protected String doInBackground(String... strings) {
String Name = strings[0];
String Email = strings[1];
String Password = strings[2];
String finalURL = url_Register + "?user_name" + Name +
"&user_id"+ Email +
"&user_password"+ Password;
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(finalURL)
.build();
Response response = null;
try{
response = okHttpClient.newCall(request).execute();
if(response.isSuccessful())
{
String result = response.body().string();
if(result.equalsIgnoreCase("uaser registered successfully"))
{
Toast.makeText(RegisterActivity.this,"Registered Successfully",Toast.LENGTH_LONG).show();
Intent i = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(i);
finish();
}
else if(result.equalsIgnoreCase("user already exists")){
Toast.makeText(RegisterActivity.this,"User Already Exists",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(RegisterActivity.this,"Ooops ! Ran into a problem , try again",Toast.LENGTH_LONG).show();
}
}
else{
Toast.makeText(RegisterActivity.this,"response not successful!! :/",Toast.LENGTH_LONG).show();
}
}
catch(Exception e){
e.printStackTrace();
}
return null;
}
}
public void showToast(final String Text){
this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(RegisterActivity.this,Text,Toast.LENGTH_LONG).show();
}
});
}
}
user_name, user_id and user_password are from my php file in the server
<?php
require_once('connect.php');
$userName = $_GET['user_name'];
$userID = $_GET['user_id'];
$userPassword = $_GET['user_password'];
$query = "select * from users where email = '$userID'";
$recordExists = mysqli_fetch_array(mysqli_query($conn, $query));
if(isset($recordExists)){
echo 'User already exists';
}else{
$query = "INSERT INTO users (name, email, password) VALUES ('$userName', '$userID', '$userPassword')";
if(mysqli_query($conn, $query)){
echo 'User registered successfully';
}else{
echo 'oops! please try again!';
}
}
?>
but its not working i dont know why
You are creating an invalid url
which is
String finalURL = url_Register + "?user_name" + Name +
"&user_id"+ Email +
"&user_password"+ Password;
and should be like this
String finalURL = url_Register + "?user_name=" + Name +
"&user_id="+ Email +
"&user_password="+ Password;
Using a volley library I am sending a post request to a file register.php which should perform user registration and return JSONResponse after success. The code I have written is working fine in the local server(MAMP) but is not working in the live server. Logcat shows {success = 0} in the live server.
package com.example.androidregisterandlogin;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private EditText name, email, password, c_password;
private Button btn_regist;
private ProgressBar loading;
RequestQueue requestQueue;
private static String URL_REGIST = "https://domainname.com.np/mentordai/register.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loading = findViewById(R.id.loading);
name = findViewById(R.id.name);
email = findViewById(R.id.email);
password = findViewById(R.id.password);
c_password = findViewById(R.id.c_password);
btn_regist = findViewById(R.id.btn_regist);
btn_regist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Regist();
}
});
}
private void Regist(){
loading.setVisibility(View.VISIBLE);
btn_regist.setVisibility(View.GONE);
final String name = this.name.getText().toString().trim();
final String email = this.email.getText().toString().trim();
final String password = this.password.getText().toString().trim();
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_REGIST,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
Log.d("TAG",response);
JSONObject jsonObject = new JSONObject(response);
String success = jsonObject.getString("success");
if (success.equals("1")) {
Toast.makeText(MainActivity.this, "Register Success!", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Register Error! " + e.toString(), Toast.LENGTH_SHORT).show();
loading.setVisibility(View.GONE);
btn_regist.setVisibility(View.VISIBLE);
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Register Error! " + error.toString(), Toast.LENGTH_SHORT).show();
loading.setVisibility(View.GONE);
btn_regist.setVisibility(View.VISIBLE);
}
})
{
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("name", name);
params.put("email", email);
params.put("password", password);
return params;
}
};
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
Server code
<?php
if ($_SERVER['REQUEST_METHOD'] =='POST'){
$name = $_POST['name'];
$email = $_POST['email'];
$password = $_POST['password'];
$password = password_hash($password, PASSWORD_DEFAULT);
require_once 'connect.php';
$sql = "INSERT INTO student_users_table (name, email, password) VALUES ('$name', '$email', '$password')";
if ( mysqli_query($connection, $sql) ) {
$result["success"] = "1";
$result["message"] = "success";
echo json_encode($result);
mysqli_close($connection);
} else {
$result["success"] = "0";
$result["message"] = "error";
echo json_encode($result);
mysqli_close($connection);
}
}
?>
```
I'm not an php expert but it looks like your server is the one who return the 'success=0'
And it looks like you have some problem with the if ( mysqli_query($connection, $sql) ) statement, your code going to the else who return the success = 0.
Try to debug the server to see what happens when you send register request.
I think you should put validation at both end (Client as well as server end) on all of your form field . If any one of the field is kept empty your query will not be able to run.
For Validation in server use this at the start of your code
if( isset($_POST['name']) && isset($_POST['email']) && isset($_POST['password']))
{
}
To Validate data in Client side use
if(this.name.getText().toString().trim().equals(""))
{
Toast.makeText(MainActivity.this, "Please Enter Name " + e.toString(), Toast.LENGTH_SHORT).show();
}
also for password and email
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
While creating the android app in user profile when user click on password edit text the pop should be displayed I have implemented it but when i click on edit text It is giving me the below error. I have googled it but not found any useful solution. Please can you tell I am attaching the code :
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference
at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:222)
at android.app.AlertDialog$Builder.(AlertDialog.java:452)
at com.example.admin.avisar.UserProfile$2.onClick(UserProfile.java:71)
at android.view.View.performClick(View.java:5612)
at android.view.View$PerformClick.run(View.java:22285)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6123)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
06-01 12:35:00.558 1563-5452/? E/ActivityManager: Sending non-protected broadcast com.motorola.motocare.INTENT_TRIGGER from system 4237:com.motorola.process.system/1000 pkg com.motorola.motgeofencesvc
java.lang.Throwable
at com.android.server.am.ActivityManagerService.broadcastIntentLocked(ActivityManagerService.java:18226)
at com.android.server.am.ActivityManagerService.broadcastIntent(ActivityManagerService.java:18826)
at android.app.ActivityManagerNative.onTransact(ActivityManagerNative.java:512)
at com.android.server.am.ActivityManagerService.onTransact(ActivityManagerService.java:2906)
at android.os.Binder.execTransact(Binder.java:565)
code here
package com.example.admin.avisar;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.admin.avisar.network.CompletionListener;
import com.example.admin.avisar.network.NetworkTask;
import com.example.admin.avisar.network.Post_URL;
import com.example.admin.avisar.network.Responce;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class UserProfile extends AppCompatActivity implements CompletionListener{
EditText name,mobno,email,add,accid,pass,yeared;
Button svebtn;
ProgressDialog progressDialog;
private NetworkTask networkTask;
Context context;
String uid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle("My Profile");
actionBar.setDisplayHomeAsUpEnabled(true);
name = (EditText)findViewById(R.id.name);
mobno = (EditText)findViewById(R.id.mobno);
email = (EditText)findViewById(R.id.email);
add = (EditText)findViewById(R.id.add);
accid = (EditText)findViewById(R.id.id);
pass = (EditText)findViewById(R.id.pass);
yeared = (EditText)findViewById(R.id.year);
svebtn = (Button)findViewById(R.id.svebtn);
userProfileWebService();
svebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
userProfileUpdate();
}
});
pass.setOnClickListener(new View.OnClickListener() {
String newpass="";
String confirmpass="";
#Override
public void onClick(View view) {
AlertDialog.Builder alert = new AlertDialog.Builder(UserProfile.this);
alert.setTitle("change password"); //Set Alert dialog title here
final EditText newpassed = new EditText(context);
newpassed.setHint("New password");
alert.setView(newpassed);
final EditText confirmpassed = new EditText(context);
confirmpassed.setHint("Confirm password");
alert.setView(confirmpassed);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
if(newpassed.length()==0){
newpassed.requestFocus();
newpassed.setError("FIELD CANNOT BE EMPTY");
newpass = confirmpassed.getEditableText().toString();
}else if (confirmpassed.length()==0) {
confirmpassed.requestFocus();
confirmpassed.setError("FIELD CANNOT BE EMPTY");
confirmpass = confirmpassed.getEditableText().toString();
}else if(confirmpass==newpass){
passwordwebservice(newpassed);
}else{
confirmpassed.setError("confirm password doesnot match");
}
// Toast.makeText(context, srt, Toast.LENGTH_LONG).show();
} // End of onClick(DialogInterface dialog, int whichButton)
}); //End of alert.setPositiveButton
alert.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
dialog.cancel();
}
}); //End of alert.setNegativeButton
AlertDialog alertDialog = alert.create();
alertDialog.show();
}
});
}
private void passwordwebservice(EditText newpassed){
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setIndeterminate(true);
progressDialog.setProgress(0);
progressDialog.show();
progressDialog.setCanceledOnTouchOutside(false);
networkTask = new NetworkTask(this,this,false);
String newpass = newpassed.getEditableText().toString();
List<NameValuePair> params =new ArrayList<>();
params.add(new BasicNameValuePair("userid",uid));
params.add(new BasicNameValuePair("password",newpass));
params.add(new BasicNameValuePair("userid",uid));
networkTask.execute(params, Post_URL.URL_update_password, 3);
}
//userprofile view webservice
private void userProfileWebService(){
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setIndeterminate(true);
progressDialog.setProgress(0);
progressDialog.show();
progressDialog.setCanceledOnTouchOutside(false);
networkTask = new NetworkTask(this,this,false);
List<NameValuePair> params =getRequestParams();
networkTask.execute(params, Post_URL.URL_Profile, 1);
}
//parameter passing for userprofile webservice
private List<NameValuePair> getRequestParams() {
SharedPreferences sharedPreferences = getSharedPreferences("A", Context.MODE_PRIVATE);
uid = sharedPreferences.getString("user_id","abc");
Log.e("TAG",uid);
List<NameValuePair> param1 = new ArrayList<NameValuePair>();
param1.add(new BasicNameValuePair("userid", uid));
return param1;
}
private void userProfileUpdate(){
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setIndeterminate(true);
progressDialog.setProgress(0);
progressDialog.show();
progressDialog.setCanceledOnTouchOutside(false);
networkTask = new NetworkTask(this,this,false);
List<NameValuePair> params =getRequestParamsupdate();
networkTask.execute(params, Post_URL.URL_update_profile, 2);
}
private List<NameValuePair> getRequestParamsupdate(){
String username = name.getText().toString();
String mno = mobno.getText().toString();
String mail = email.getText().toString();
String address = add.getText().toString();
String accout_id = accid.getText().toString();
// String password= pass.getText().toString();
String yearString = yeared.getText().toString();
List<NameValuePair> pairs = new ArrayList<>();
pairs.add(new BasicNameValuePair("username",username));
pairs.add(new BasicNameValuePair("mobno",mno));
pairs.add(new BasicNameValuePair("email",mail));
pairs.add(new BasicNameValuePair("add",address));
pairs.add(new BasicNameValuePair("userid",accout_id));
// pairs.add(new BasicNameValuePair("password",password));
pairs.add(new BasicNameValuePair("year",yearString));
return pairs;
}
//user profile response handle
private void handleUserProfileResponse(JSONObject serverResponse){
int success=0;
try{
success = serverResponse.getInt(Responce.TAG_SUCCESS);
if(success==1){
progressDialog.dismiss();
//parsing the data
JSONArray user_profile = serverResponse.getJSONArray("user_details");
for(int i =0 ;i<user_profile.length();i++){
String name1 = user_profile.getJSONObject(i).getString("username");
String mno = user_profile.getJSONObject(i).getString("mobno");
//Log.e("TAG",name1);
String mail = user_profile.getJSONObject(i).getString("email");
String address = user_profile.getJSONObject(i).getString("add");
String accountid = user_profile.getJSONObject(i).getString("userid");
String password = user_profile.getJSONObject(i).getString("password");
String year = user_profile.getJSONObject(i).getString("year");
//set data to textview
name.setText(name1);
mobno.setText(mno);
email.setText(mail);
add.setText(address);
accid.setText(accountid);
pass.setText(password);
yeared.setText(year);
}
}
else{
progressDialog.dismiss();
Toast.makeText(UserProfile.this, serverResponse.getString(Responce.TAG_MESSAGE), Toast.LENGTH_LONG).show();
}
}catch (JSONException e){
}
}
private void handleUserProfileUpdateResponse(JSONObject serverResponse){
int success =0;
try{
success = serverResponse.getInt(Responce.TAG_SUCCESS);
if (success ==1){
progressDialog.dismiss();
Toast.makeText(UserProfile.this, serverResponse.getString(Responce.TAG_MESSAGE), Toast.LENGTH_LONG).show();
}
else{
progressDialog.dismiss();
Toast.makeText(UserProfile.this, serverResponse.getString(Responce.TAG_MESSAGE), Toast.LENGTH_LONG).show();
}
}catch(JSONException e)
{
}
}
private void handleUpdatePassResponse(JSONObject serverResponse){
int success =0;
try{
success = serverResponse.getInt(Responce.TAG_SUCCESS);
if (success ==1){
progressDialog.dismiss();
Toast.makeText(UserProfile.this, serverResponse.getString(Responce.TAG_MESSAGE), Toast.LENGTH_LONG).show();
}
else{
progressDialog.dismiss();
Toast.makeText(UserProfile.this, serverResponse.getString(Responce.TAG_MESSAGE), Toast.LENGTH_LONG).show();
}
}catch(JSONException e)
{
}
}
#Override
public void onComplete(JSONObject serverResponse, int RESPONSE_IDENTIFIER_FLAG) throws JSONException {
switch (RESPONSE_IDENTIFIER_FLAG){
case 1:handleUserProfileResponse(serverResponse);
break;
case 2: handleUserProfileUpdateResponse(serverResponse);
break;
case 3:handleUpdatePassResponse(serverResponse);
default:
break;
}
}
}
Pass activity instead of context in following line :
AlertDialog.Builder alert = new AlertDialog.Builder(context);
Im going to make a database in php my sql using android studio
but this error is in the way
//Adding request to request queue
AndroidLoginController.getInstance();
addToRequestQueue(strReq, tag_string_req);
}
I receive the error cannot resolve method 'addToRequestQueque(com.android.volley.toolbox.StringRequest,java.lang.String)'
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.example.pjsr.brnp.MainActivity;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import prefs.UserInfo;
import prefs.UserSession;
public class Login extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = Login.class.getSimpleName();
private EditText email, password;
private Button login;
private TextView signup;
private ProgressDialog progressDialog;
private UserSession session;
private UserInfo userInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
email = (EditText) findViewById(R.id.email);
password = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.login);
signup = (TextView) findViewById(R.id.open_signup);
progressDialog = new ProgressDialog(this);
session = new UserSession(this);
userInfo = new UserInfo(this);
if (session.isUserLoggedin()) {
startActivity(new Intent(this, MainActivity.class));
finish();
}
login.setOnClickListener(this);
signup.setOnClickListener(this);
}
private void login(final String email, final String password) {
//Tag used to cancel the request
String tag_string_req = "req_login";
progressDialog.setMessage("Logging in....");
progressDialog.show();
StringRequest strReq = new StringRequest(Request.Method.POST,
Utils.LOGIN_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
//check for error node in json
if (!error) {
//now store the user in SQLite
JSONObject user = jObj.getJSONObject("user");
String uName = user.getString("username");
String email = user.getString("email");
//Inserting row in users table
userInfo.setEmail(email);
userInfo.setUsername(uName);
session.setLoggedin(true);
startActivity(new Intent(Login.this, MainActivity.class));
finish();
} else {
//error in login, get the error message
String errorMsg = jObj.getString("error_msg");
toast(errorMsg);
}
} catch (JSONException e) {
//json error
e.printStackTrace();
toast("Json error: " + e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
toast("Unknown Error occured");
progressDialog.hide();
}
}) {
#Override
protected Map<String, String> getParams() {
//Posting parameters to login url
Map<String, String> params = new HashMap<>();
params.put("email", email);
params.put("password", password);
return params;
}
};
//Adding request to request queue
AndroidLoginController.getInstance();
addToRequestQueue(strReq, tag_string_req);
}
private void toast(String x) {
Toast.makeText(this, x, Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.login:
String uName = email.getText().toString().trim();
String pass = password.getText().toString().trim();
login(uName, pass);
break;
case R.id.open_signup:
startActivity(new Intent(this, SignUp.class));
break;
}
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Login Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
}
addToRequestQueue is a method defined for the volley application controller which seems to be AndroidLoginController in your case. Change the line to
AndroidLoginController.getInstance().addToRequestQueue(strReq,tag_string_req)
This is assuming you have created the singleton using standard volley tutorials or android developer documentation