I am trying to create a simple login and if it is successful, I am trying to save the response userid (uid) into the shared preferences. Below is the part of my loginActivity.java and the error messages are:
Error 1
error: incompatible types: int cannot be converted to String
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST, Config.LOGIN_URL, null, new Response.Listener<JSONObject>() {
Error 2
error: cannot find symbol
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,Config.LOGIN_URL, null, new Response.Listener<JSONObject>() {
^
symbol: constructor (int,String,,>)
LoginActivity.java
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.AppCompatButton;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONObject;
import com.android.volley.Request.Method;
import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.Map;
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
//Defining views
private EditText editTextTCNO;
private EditText editTextMobile;
private AppCompatButton buttonLogin;
//boolean variable to check user is logged in or not
//initially it is false
private boolean loggedIn = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
//Initializing views
editTextTCNO = (EditText) findViewById(R.id.editTextTCNO);
editTextMobile = (EditText) findViewById(R.id.editTextMobile);
buttonLogin = (AppCompatButton) findViewById(R.id.loginButton);
//Adding click listener
buttonLogin.setOnClickListener(this);
}
#Override
protected void onResume() {
super.onResume();
//In onresume fetching value from sharedpreference
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Fetching the boolean value form sharedpreferences
loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false);
//If we will get true
if(loggedIn){
//We will start the Profile Activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
}
}
private void login() {
//Getting values from edit texts
final String tcno = editTextTCNO.getText().toString().trim();
final String mobile = editTextMobile.getText().toString().trim();
final String operation = "login";
//Creating a string request
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST, Config.LOGIN_URL, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
String smsg = response.getString("msg");
String pid = response.getString("uid");
//If we are getting success from server
if(smsg == Config.LOGIN_SUCCESS){
//Creating a shared preference
SharedPreferences sharedPreferences = LoginActivity.this.getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
//Creating editor to store values to shared preferences
SharedPreferences.Editor editor = sharedPreferences.edit();
//Adding values to editor
editor.putBoolean(Config.LOGGEDIN_SHARED_PREF, true);
editor.putString(Config.UID_SHARED_PREF, pid);
//Saving values to editor
editor.commit();
//Starting profile activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
}else{
//If the server response is not success
//Displaying an error message on toast
Toast.makeText(LoginActivity.this, "Invalid username or password", Toast.LENGTH_LONG).show();
}
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
//Adding parameters to request
params.put(Config.KEY_TCNO, tcno);
params.put(Config.KEY_MOBILE, mobile);
params.put(Config.KEY_OPERATION, operation);
//returning parameter
return params;
}
};
//Adding the string request to the queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonObjReq);
}
#Override
public void onClick(View v) {
//Calling the login function
login();
}
}
this is my fully functional way to make a volley request, hope it helps
private JSONObject LoginJson()
{
JSONObject jsonBody = new JSONObject();
try {
jsonBody.put("Username", "testUser");
jsonBody.put("Password", "123456");
} catch (JSONException e) {
e.printStackTrace();
}
return jsonBody;
}
public boolean identificarce ()
{
RequestFuture<JSONObject> future = RequestFuture.newFuture();
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, URL.ServicioLogging, this.LoginJson(), future, future);
QueuHolder.getInstance(Login.contexto).getRequestQueue().add(request);
try {
JSONObject response = future.get();
try
{
String NombreCompleto = response.getString("NombreCompleto");
int id = response.getInt("id");
//save results in shared preferences
}
catch (JSONException e)
{
e.printStackTrace();
}
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
return true;
}
Related
i'm very beginner in this problem.
i following the tutorials from youtube make a database for user register, i use localhost and put the php file into htdocs and it's succes but when i tried to put the php file into 000webhost file manager. the result is 'something went wrong' it should be 'Succesfully Registered'. i dont know what should i do because there's no error in logcat. i'm sure there's no error in php file because i've matched it with the real source code.
Example Error Image
Thank you in advance.
here is my code
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.AuthFailureError;
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 java.util.HashMap;
import java.util.Map;
public class Register extends AppCompatActivity {
private EditText etName, etEmail, etPassword, etReenterPassword;
private TextView tvStatus;
private String URL = "https://db4image.000webhostapp.com/login/register.php";
private String name, email, password, reenterPassword;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
etName = findViewById(R.id.name);
etEmail = findViewById(R.id.email);
etPassword = findViewById(R.id.password);
etReenterPassword = findViewById(R.id.repass);
tvStatus = findViewById(R.id.tvStatus);
name = email = password = reenterPassword = "";
}
public void daftarCok (View view) {
name = etName.getText().toString().trim();
email = etEmail.getText().toString().trim();
password = etPassword.getText().toString().trim();
reenterPassword = etReenterPassword.getText().toString().trim();
if(!password.equals(reenterPassword)){
Toast.makeText(this, "Password Mismatch", Toast.LENGTH_SHORT).show();
}
else if(!name.equals("") && !email.equals("") && !password.equals("")){
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.equals("success")) {
tvStatus.setText("Successfully registered.");
Intent inten = new Intent(Register.this, MainActivity.class);
startActivity(inten);
}
else if (response.equals("failure")) {
tvStatus.setText("Something went wrong!");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.toString().trim(), Toast.LENGTH_SHORT).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> data = new HashMap<>();
data.put("name", name);
data.put("email", email);
data.put("password", password);
return data;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
}
public void login(View view) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
}
This is my register.php
<?php
if(isset($_POST['name']) && isset($_POST['email']) && isset($_POST['password'])){
require_once "conn.php";
require_once "validate.php";
$name = validate($_POST['name']);
$email = validate($_POST['email']);
$password = validate($_POST['password']);
$sql = "INSERT INTO users VALUES ('', '$name', '$email', '" . md5($password) . "')";
if(!$conn->query($sql)){
echo "failure";
}else{
echo "success";
}
}
?>
Here this is the layout in which I have to set the image of the user who successfully logged in
and I have saved the url of the image in the table where all the details of the users are there....
So what I was trying is I am fetching the url of the image from the database and then tried to set it into imageview.. I have checked that the url is comming to the variable...
so as you can see in the above image it is not setting the image in imageview but when I assign the url first to the imgurl variable at the time of defining the variable then it works fine...
I don't know why this is happening... am I doing anything wrong or is there any other way to achieve this?
This is the code of the file...
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
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 java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class Dashboard extends AppCompatActivity {
TextView usrname;
ImageView profileimg;
public static String imgurl = "";//here
/**
* Shared Preferences
**/
SharedPreferences sharedPreferences;
public static final String mypreference = "mypref";
public static final String Name = "nameKey";
public static final String Email = "emailKey";
/**
* Shared Preferences
**/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
profileimg = findViewById(R.id.iv_display_image);
usrname = findViewById(R.id.tv_username);
/**Shared Preferences**/
sharedPreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
/**Shared Preferences**/
//fetching session data
String name = sharedPreferences.getString(Name, "0");
usrname.setText(name);
fetchimg(name);
LoadImage loadImage = new LoadImage(profileimg);
Log.d("Oncreate img url", imgurl);
loadImage.execute(imgurl);
}
private void fetchimg(String name) {
StringRequest request = new StringRequest(Request.Method.POST, "https://**url**//fetchimg.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.startsWith("Here")) {
String urlstr = getUrl(response, "Here ");
seturl(urlstr);
Log.d("urlstr value:", urlstr);
} else {
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
Log.d("vOLLEY ERROR", response.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
Log.d("vOLLEY ERROR", error.getMessage().toString());
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("login_name", "xxxxx");
params.put("login_pass", "xxxxx");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(Dashboard.this);
requestQueue.add(request);
}
private void seturl(String urlstr) {
this.imgurl = urlstr;
Log.d("Image url set inside seturl", imgurl);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.dashboardmenu, menu);
return true;
}
public void openeditprofile(View view) {
startActivity(new Intent(this, EditProfileActivity.class));
}
private class LoadImage extends AsyncTask<String, Void, Bitmap> {
ImageView imageView;
public LoadImage(ImageView profileimg) {
this.imageView = profileimg;
}
#Override
protected Bitmap doInBackground(String... strings) {
String urlLink = strings[0];
Bitmap bitmap = null;
try {
InputStream inputStream = new java.net.URL(urlLink).openStream();
bitmap = BitmapFactory.decodeStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
profileimg.setImageBitmap(bitmap);
}
}
public static String getUrl(String string, String word) {
// Check if the word is present in string
// If found, remove it using removeAll()
if (string.contains(word)) {
// To cover the case
// if the word is at the
// beginning of the string
// or anywhere in the middle
String tempWord = word + " ";
string = string.replaceAll(tempWord, "");
// To cover the edge case
// if the word is at the
// end of the string
tempWord = " " + word;
string = string.replaceAll(tempWord, "");
}
// Return the resultant string
return string;
}
}
You are fetching image asynchronously, your Asynctask execute will be called with empty imgUrl as it not already fetched, move AsyncTask execution code in onResponse of fetching
private void fetchimg(String name) {
StringRequest request = new StringRequest(Request.Method.POST, "https://**url**//fetchimg.php", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.startsWith("Here")) {
String urlstr = getUrl(response, "Here ");
seturl(urlstr);
//here the url is ready to consume
Log.d("urlstr value:", urlstr);
//load the image now
LoadImage loadImage = new LoadImage(profileimg);
Log.d("Oncreate img url", imgurl);
loadImage.execute(imgurl);
} else {
Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show();
Log.d("vOLLEY ERROR", response.toString());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
Log.d("vOLLEY ERROR", error.getMessage().toString());
}
}
) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("login_name", "xxxxx");
params.put("login_pass", "xxxxx");
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(Dashboard.this);
requestQueue.add(request);
}
use **Glide** to display Image from Url into image view.
You have to add glide lib in app-level build.gradle file.
implementation 'com.github.bumptech.glide:glide:4.12.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0'
Glide.with(this).load(url)
.transform(CenterCrop(), RoundedCorners(radius))
.placeholder(R.drawable.drawable_image_placeholder)
.error(R.drawable.drawable_image_placeholder)
.into(ivProfile)
drawable_image_placeholder is the default imageview that displays
when getting the error to load the image. ivProfile is imageview .
Ia trying to get user locations whenever its login the application.I made a class and its working perfect seperately but when I embed it in my main project it didnt submit the location values in database.I want that whenever user login that class run for only once and submits its coordinates in database.
Here Is the code of my location class :
I want that when user login this class class run for once only all I want is to get user location when its loged in.
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
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 java.util.HashMap;
import java.util.Map;
public class getposition extends AppCompatActivity {
String URL_LOGIN = "api"
Button btn;
TextView tv1,tv2;
LocationManager locationManager;
static final int REQUEST_LOCATION = 1;
String lg, lt , chk;
String lat_long;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_getposition);
btn = findViewById(R.id.send);
tv1 = findViewById(R.id.lang);
tv2 = findViewById(R.id.lat);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
chk = getLocation();
loadlocation();
if(chk != "false"){
String foo = chk;
String[] split = foo.split("_");
lt = split[0];
lg = split[1];
Toast.makeText(getApplicationContext(),chk,Toast.LENGTH_LONG).show();
}
}
private void loadlocation() {
final RequestQueue requestQueue = Volley.newRequestQueue(getposition.this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_LOGIN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
tv1.setText(response);
tv2.setText(response);
requestQueue.stop();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
tv1.setText("Something went wrong///");
error.printStackTrace();
requestQueue.stop();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("user_id","12" );
params.put("user_lat", lt);
params.put("user_lng", lg);
return params;
}
};
VolleySingleton.getInstance(getposition.this).addToRequestQueue(stringRequest);
}
public String getLocation() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
else {
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
double latt = location.getLatitude();
double lng = location.getLongitude();
lat_long = latt + "_" + lng;
tv1.setText("Latitude: " + latt);
tv2.setText("Longitude: " + lng);
} else {
lat_long = "false";
tv1.setText("Unable to find correct location.");
tv2.setText("Unable to find correct location. ");
}
}
return lat_long;
}
}
This is my login class:
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;
import com.vshine.neuron.riseshine.VolleySingleton;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.vshine.neuron.riseshine.MainActivity;
import com.vshine.neuron.riseshine.R;
import com.vshine.neuron.riseshine.getregistered;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class login extends AppCompatActivity {
Button login_button;
ImageButton GetRegistered;
EditText userName_edt, password_edt;
String user_name, password;
Context mctx;
String json_response;
String URL_LOGIN = "api"
public static final String PREFS_NAME = "MyPreferenceFiles";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mctx = this;
initBasic();
initLogin();
}
private void initBasic() {
login_button = (Button) findViewById(R.id.login_button);
GetRegistered = (ImageButton) findViewById(R.id.register);
userName_edt = (EditText) findViewById(R.id.user_name);
password_edt = (EditText) findViewById(R.id.password);
}
private void initLogin() {
GetRegistered.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent= new Intent(login.this,getregistered.class);
startActivity(intent);
}
});
login_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
user_name = userName_edt.getText().toString();
password = password_edt.getText().toString();
if (user_name.trim().equals("") || password.trim().equals("")) {
ShowToastMessage("Please enter the credentials properly");
}
else {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting response to json object
JSONObject obj = new JSONObject(response);
//if no error in response
// json_response = j_obj.getString("message");
if (response!= null) {
// Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
json_response = obj.getString("message");
// ShowToastMessage(json_response);
//getting the user from the response
JSONObject userJson = obj.getJSONObject("response");
//creating a new user object
String u_id = String.valueOf(userJson.getInt("id"));
// ShowToastMessage(u_id);
//storing the user in shared preferences
SharedPreferences.Editor editor = getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("User_id", u_id);
editor.commit();
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
} else {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("user_name", user_name);
params.put("password", password);
return params;
}
};
VolleySingleton.getInstance(login.this).addToRequestQueue(stringRequest);
}
}
});
}
private void ShowToastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
}
I am using android studio ,mysql database and notepad++ for php files.
The database has a table named login and has 3 attributes:
id
firstname
lastname
all are of the type varchar.
When I try to execute this code of android and php I don't get any error and the code is executed successfully but the data from the database does not get displayed on the emulator.
*******************Android code************************
package com.example.digi.college;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
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 com.android.volley.AuthFailureError;
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.JsonObjectRequest;
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.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
EditText firstname, lastname, id;
Button insert, show;
TextView result;
RequestQueue requestQueue;
String inserturl = "http://192.168.1.104/android/register.php";
String displayurl = "http://192.168.1.104/android/display.php";
String hello="hello how are you";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
id = (EditText) findViewById(R.id.editText);
firstname = (EditText) findViewById(R.id.editText2);
lastname = (EditText) findViewById(R.id.editText3);
insert = (Button) findViewById(R.id.button);
show = (Button) findViewById(R.id.button2);
result = (TextView) findViewById(R.id.textView);
requestQueue = Volley.newRequestQueue(getApplicationContext());
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
displayurl, new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
try {
JSONArray students = response.getJSONArray("students");
for (int i = 0; i < students.length(); i++) {
JSONObject login = students.getJSONObject(i);
String id = login.getString("id");
String firstname = login.getString("firstname");
String lastname = login.getString("lastname");
result.append(id+" "+firstname+" "+lastname+"\n");
}
result.append("===\n");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
}
});
insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringRequest request = new StringRequest(Request.Method.POST, inserturl, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> parameters = new HashMap<String, String>();
parameters.put("id",id.getText().toString());
parameters.put("firstname",firstname.getText().toString());
parameters.put("lastname",lastname.getText().toString());
return parameters;
}
};
requestQueue.add(request);
}
});
}
}
*****************Php Code for insert.php******************
<?php
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$id=$_POST['id'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$db = mysql_connect("localhost", "root", "");
mysql_select_db("ntu", $db);
$sql = mysql_query("INSERT INTO login (id,firstname,lastname) VALUES ('$id','$firstname', '$lastname')");
mysql_close($db);
}
?>
*************Php code for display.php*************
<?php
$db = mysql_connect("localhost", "root", "");
mysql_select_db("ntu", $db);
$sql = mysql_query("SELECT * FROM login");
$a = array();
$index = 0;
while($row = mysql_fetch_assoc($sql))
{
$a[$index] = $row;
$index++;
}
echo json_encode(array("students"=>$a));
mysql_close($db);
?>
I think you have missed the put the internet permission in androidmanifeast.xml file give internet permission and check.
So I'm trying to adapt this tutorial: http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/
to my own project. It is a basic register & login in Android/Java using SQLite & Volley to a SQL server via PHP.
I can get the tutorial as written working no problem. However, upon transferring it to my project I encounter a crash;
05-12 01:18:05.763 1965-1965/com.disclosure_scots.disclosure_scots E/AndroidRuntime? FATAL EXCEPTION: main
Process: com.disclosure_scots.disclosure_scots, PID: 1965
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.disclosure_scots.disclosure_scots.AppController.addToRequestQueue(com.android.volley.Request, java.lang.String)' on a null object reference
at com.disclosure_scots.disclosure_scots.RegisterActivity.registerUser(RegisterActivity.java:194)
at com.disclosure_scots.disclosure_scots.RegisterActivity.access$300(RegisterActivity.java:34)
at com.disclosure_scots.disclosure_scots.RegisterActivity$1.onClick(RegisterActivity.java:90)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
The line within RegisterActivity to which it refers too is;
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
The Activities involved are;
RegisterActivity
package com.disclosure_scots.disclosure_scots;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.disclosure_scots.disclosure_scots.AppConfig;
import com.disclosure_scots.disclosure_scots.AppController;
import com.disclosure_scots.disclosure_scots.SQLiteHandler;
import com.disclosure_scots.disclosure_scots.SessionManager;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
public class RegisterActivity extends ActionBarActivity {
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnRegister;
private EditText inputFullName;
private EditText inputEmail;
private EditText inputPassword;
private EditText inputTel_No;
private EditText inputHome_Add;
private EditText inputPostcode;
private CheckBox inputPostal;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
inputFullName = (EditText) findViewById(R.id.editTextName);
inputEmail = (EditText) findViewById(R.id.editTextEmail);
inputPassword = (EditText) findViewById(R.id.editTextPass);
inputTel_No = (EditText) findViewById(R.id.editTextPhone);
inputHome_Add = (EditText) findViewById(R.id.editTextPost);
inputPostcode = (EditText) findViewById(R.id.editTextPostcode);
inputPostal = (CheckBox) findViewById(R.id.PostalcheckBox);
btnRegister = (Button) findViewById(R.id.btnRegister);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// Session manager
session = new SessionManager(getApplicationContext());
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to Legal disclaimer activity
Intent intent = new Intent(RegisterActivity.this,
LegalDiscActivity.class);
startActivity(intent);
finish();
}
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {
registerUser(name, email, password);
} else {
Toast.makeText(getApplicationContext(),
"Please enter your details!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Login Screen
/*btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(i);
finish();
}
});*/
}
/**
* Function to store user in MySQL database will post params(tag, name,
* email, password) to register url
* */
private void registerUser(final String name, final String email,
final String password) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
// User successfully stored in MySQL
// Now store the user in sqlite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
// Launch login activity
Intent intent = new Intent(
RegisterActivity.this,
LoginActivity.class);
startActivity(intent);
finish();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "register");
params.put("name", name);
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
#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_register, 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);
}
}
AppController class
package com.disclosure_scots.disclosure_scots;
/**
* Created by Administrator on 09/05/2015.
*/
import android.app.Application;
import android.text.TextUtils;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
I've been over it a number of times but cannot tell why I am getting the null object in my copied version while the original works fine.
Any help appreciated.
This is very likely because you didn't register your AppController in the manifest so getInstance returns null.
you need to add this line in your manifest (may be you missed this line so it returns null value)
<application
android:name="(your app package).app.AppController" // <--this line
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
...../>