How do I fix this duplication of onCreate.
I tried changing onCreate to onCreate1
but #Override gets an error saying
"Method does not override method from its superclass"
how do i fix this pls help thank you so much
#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;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
/**
* 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();
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
}
You don't need two onCreate methods. You need to do all what you need into one of these two methods.
Delete the other one
It's not possible to have two methods with the same signature in Java.
Furthermore onCreate is called automatically by Android, so creating a onCreate1 method should resolve in non executed code.
Remove
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
add below line in your First and only onCreate
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
eg:
#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);
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
session = new UserSession(this);
userInfo = new UserInfo(this);
if (session.isUserLoggedin()) {
startActivity(new Intent(this, MainActivity.class));
finish();
}
login.setOnClickListener(this);
signup.setOnClickListener(this);
}
Method does not override method from its superclass
means your override method can't find the superclassmethod, because there is no superclass method by that name
For me quoting this answer
Why are we forced to call super.method()?
The classes that make up the Android SDK can be incredibly complex. For instance, both activities and fragments must perform a number of operations in order to function properly (i.e. managing life cycle, optimizing memory usage, drawing the layout to the screen, etc.). Requiring the client to make a call to the base class (often at the beginning of the method) ensures that these operations are still performed, while still providing a reasonable level of abstraction for the developer.
How do we know that a function method requires super to be called?
The documentation should tell you whether or not this is required. If it doesn't I'd Google-search for some sample code (or check the API demos... or better yet, look at the source code!). It shouldn't be too difficult to figure out.
Related
I'm trying to login with four different users using php and mysql database in android, and after if any user login with email and password i'm trying to fetch their information like (Name, Address, ID, etc.) from mysql database.
And i want that whenever if any of user from those four users login they can able to see their own information from database like(Name, Address, ID, etc.)
I have already tried to separate those users with the user type and with if-else condition that is in code that i provided.
public class LoginActivity extends AppCompatActivity {
private static final String TAG="LoginActivity";
private TextView createaccount;
private EditText Ausername,Apassword;
private Button LoginButton;
private Context mContext;
//URLS class
//ALL URLs
URLs urLs;
RelativeLayout relativeLayout1,relativeLayout2;
Handler handler=new Handler();
Runnable runnable=new Runnable() {
#Override
public void run() {
relativeLayout1.setVisibility(View.VISIBLE);
relativeLayout2.setVisibility(View.VISIBLE);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
urLs = new URLs();
if (SharedPrefManager.getInstance(getApplicationContext()).isLoggedIn()){
finish();
Intent intentD = new Intent(LoginActivity.this, DashboardActivity.class);
startActivity(intentD);
}
relativeLayout1 = findViewById(R.id.rel3);
relativeLayout2 = findViewById(R.id.rel2);
Ausername = findViewById(R.id.etuname);
Apassword = findViewById(R.id.etpass);
LoginButton = findViewById(R.id.loginbutton);
handler.postDelayed(runnable, 2000);
createaccount = findViewById(R.id.tvregistration);
createaccount.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(LoginActivity.this, Rigistration_Option.class);
startActivity(intent);
}
});
LoginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
userLogin();
}
});
}
private void userLogin(){
//first getting the values
final String email = Ausername.getText().toString();
final String password = Apassword.getText().toString();
//validating inputs
if (TextUtils.isEmpty(email)) {
Ausername.setError("Please enter your username");
Ausername.requestFocus();
return;
}
if (TextUtils.isEmpty(password)) {
Apassword.setError("Please enter your password");
Apassword.requestFocus();
return;
}
//if everything is fine
class UserLogin extends AsyncTask<Void, Void, String> {
ProgressBar progressBar;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar = findViewById(R.id.progressbar);
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressBar.setVisibility(View.GONE);
try {
//converting response to json object
JSONObject obj = new JSONObject(s);
//if no error in response
if (!obj.getBoolean("error")) {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
//getting the user from the response
JSONObject userJson = obj.getJSONObject("user");
//creating a new user object
CA_SIGNUP_GTST user = new CA_SIGNUP_GTST(
userJson.getInt("id"),
userJson.getString("name"),
userJson.getString("email"),
userJson.getString("mobile"),
userJson.getString("address")
);
//storing the user in shared preferences
SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);
//starting the profile activity
finish();
Intent intentD = new Intent(LoginActivity.this, DashboardActivity.class);
startActivity(intentD);
} else {
Toast.makeText(getApplicationContext(), "Invalid username or password", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... voids) {
//creating request handler object
RequestHandler requestHandler = new RequestHandler();
HashMap<String, String> params = new HashMap<>();
URLs urLs = new URLs();
if (urLs.equals("cma_login")) {
params.put("email", email);
params.put("password", password);
return requestHandler.sendPostRequest(URLs.CMA_LOGIN, params);
}
else if (urLs.equals("ca_login")){
params.put("email", email);
params.put("password", password);
return requestHandler.sendPostRequest(URLs.CA_LOGIN, params);
}
else if (urLs.equals("cs_login")){
params.put("email", email);
params.put("password", password);
return requestHandler.sendPostRequest(URLs.CS_LOGIN, params);
}
else if (urLs.equals("adv_login")){
params.put("email", email);
params.put("password", password);
return requestHandler.sendPostRequest(URLs.ADV_LOGIN, params);
}
return null;
}
}
UserLogin ul = new UserLogin();
ul.execute();
}
}
i expect that after user login they can see their own information but when i try to login with second and the third user then they are unable to login.
I want the data of textview in the second activity to pass in the third but i dont want to display it in the third activity. I want to directly send the data from the second activity to Pass in my sql db after clicking the button in the final activity. Is is achievable?
This is my first activity.
public class MainActivity extends AppCompatActivity {
private EditText email, password;
private Button btn_login;
private ProgressBar loading;
private static String URL_LOGIN ="http://192.168.1.83/Attendance/login.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loading= findViewById(R.id.loading);
email = findViewById(R.id.editTextUserEmail);
password = findViewById(R.id.editTextPassword);
btn_login = findViewById(R.id.buttonRegister);
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mEmail = email.getText().toString().trim();
String mPassword = password.getText().toString().trim();
if (!mEmail.isEmpty() || !mPassword.isEmpty()) {
Login(mEmail, mPassword);
}else{
email.setError("Please Enter Email");
password.setError("Please Enter Password");
}
}
});
}
private void Login(final String email, final String password) {
loading.setVisibility(View.VISIBLE);
btn_login.setVisibility(View.GONE);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
Log.d("JSON", jsonObject.toString());
String success = jsonObject.getString("success");
JSONArray jsonArray =
jsonObject.getJSONArray("login");
if (success.equals("1"))
{
for (int i = 0; i<jsonArray.length(); i++){
JSONObject object =
jsonArray.getJSONObject(i);
String name =
object.getString("name").trim();
String email =
object.getString("email").trim();
// Toast.makeText(MainActivity.this,
"Success Login \nYour name: "+name+"\nYour Email: "+email,
// Toast.LENGTH_LONG).show();
Intent intent = new
Intent(MainActivity.this, HomeActivity.class);
intent.putExtra("name",name);
intent.putExtra("email", email);
startActivity(intent);
loading.setVisibility(View.GONE);
}
}
} catch (JSONException e) {
e.printStackTrace();
loading.setVisibility(View.GONE);
btn_login.setVisibility(View.VISIBLE);
Toast.makeText(MainActivity.this, "Error"
+e.toString(),
Toast.LENGTH_LONG).show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error"
+error.toString(),
Toast.LENGTH_LONG).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("email", email);
params.put("password", password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
This is my second activity
public class HomeActivity extends AppCompatActivity {
private TextView name,email;
private TextView welcome;
private Button Send;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
name = findViewById(R.id.name);
email = findViewById(R.id.email);
Send = findViewById(R.id.btn_send);
welcome = findViewById(R.id.welcome);
final Intent intent = getIntent();
String extraName = intent.getStringExtra("name");
String extraEmail = intent.getStringExtra("email");
name.setText(extraName);
email.setText(extraEmail);
Send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(HomeActivity.this,StatusActivity.class);
intent1.putExtra("wel", welcome.getText().toString());
intent1.putExtra("name1", name.getText().toString());
intent1.putExtra("email1", email.getText().toString());
startActivity(intent1);
}
});
}
And this is my final activity but Here i dont want to show the text view i just want to post it from here.
public class StatusActivity extends AppCompatActivity {
private TextView welcome, name, email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_status);
welcome = findViewById(R.id.abcd);
name = findViewById(R.id.name1);
email = findViewById(R.id.email1);
final Intent intent = getIntent();
String extraName1 = intent.getStringExtra("name1");
String extraEmail1 = intent.getStringExtra("email1");
String extraWelcome = intent.getStringExtra("wel");
name.setText(extraName1);
email.setText(extraEmail1);
welcome.setText(extraWelcome);
}
Your question is pretty clear until you put MySql to the topic. Why you want to pass the data from one activity to another through the database. Why involve database operations which take time and resources.
You may pass data from one activity to another through Intents (primitive values, Strings and Parcelables)!
All you have to do is:
Get the data (int your case from TextView).
Create the Intent to navigate to the next Activity.
Put the data to the Intent.
Start the Activity.
Retrieve the data from the Intent.
For example if will navigate to the next Activity via button click then in that button's onClick():
// 1.
String data = myTextView.getText();
// 2.
Intent intent = new Intent(yourContext,YourNextActivity.class);
// 3.
intent.putStringExtra("MY DATA KEY",data);
// 4.
yourContext.startActivity(intent);
// 5. Now in YourNextActivity's onCreate();
String retrievedData = YourNextActivity.this.getIntent().getStringExtra("MY DATA KEY");
// Done!
I am trying to make a login page where if user enters a correct mobile and pwd it should go in ProfileActivity.java
my code
public class LoginActivity extends AppCompatActivity {
EditText editTextUsername, editTextPassword;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
if (SharedPrefManager.getInstance(this).isLoggedIn()) {
finish();
startActivity(new Intent(this, ProfileActivity.class));
}
progressBar = (ProgressBar) findViewById(R.id.progressBar);
editTextUsername = (EditText) findViewById(R.id.editTextUsername);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
//if user presses on login
//calling the method login
Button login = (Button)findViewById(R.id.buttonLogin);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
userLogin();
}
});
//if user presses on not registered
findViewById(R.id.textViewRegister).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//open register screen
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
}
});
}
private void userLogin() {
//first getting the values
final String mobile = editTextUsername.getText().toString();
final String password = editTextPassword.getText().toString();
//validating inputs
if (TextUtils.isEmpty(mobile)) {
editTextUsername.setError("Please enter your username");
editTextUsername.requestFocus();
return;
}
if (TextUtils.isEmpty(password)) {
editTextPassword.setError("Please enter your password");
editTextPassword.requestFocus();
return;
}
//if everything is fine
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
progressBar.setVisibility(View.GONE);
try {
//converting response to json object
JSONObject obj = new JSONObject(response);
//if no error in response
if (!obj.getBoolean("error")) {
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show();
//getting the user from the response
JSONObject userJson = obj.getJSONObject("user");
//creating a new user object
User user = new User(
userJson.getInt("id"),
userJson.getString("mobile"),
userJson.getString("password")
);
//storing the user in shared preferences
SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);
//starting the profile activity
Intent intent = new Intent(LoginActivity.this, ProfileActivity.class);
startActivity(intent);
finish();
} else {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("TAG", response);
}
},
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("mobile", mobile);
params.put("password", password);
return params;
}
};
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
}
In this code neither a toast, progressbar, nor the intent to redirect to next activity is working. I have also extended ProfileActivity with Activity. I have registerd profileactivity.java in manifest file.
What am i doing wrong here? thank you for your suggestions
finish() method should be put a end, because it will ignore all next lines.
Intent intent = new Intent(LoginActivity.this, ProfileActivity.class);
startActivity(intent);
finish();
You are using "id" field as an integer and it's an String ,Secondly from where you are getting
User user = new User(
userJson.getString("id"),
"", // please add mobile and password in JSON
""
);
I solved it. In the line ,
JSONObject userJson = obj.getJSONObject("user");
I named the object as user. But in PHP I named it as result As soon as I changed it, it started working.
Although, Thanks for your support community :).
all of you great developers, which I'm not, since I'm posting this question ;-)
I have a site with a to-do list where you can log in to Google. Now I want to make an Android app to access my DB on my site. I have the login with Google part correct and from that login activity, I switch to the activity (via intent, that's how I know I'm logged in correctly, cause the intent is only started when logged in) to display my to-do list. This is where I'm stuck. I can't seem to fetch the data from the DB, even though I'm logged in. I searched a bit online (watched a few hours of youtube video on the topic, and also searched StackOverflow, the internet in general and the Google developer pages), but no result. I'm guessing I have to pass on the token from the login activity to the other, but other than that, I just don't know and I'm hoping someone of you can point me in the right direction. Extra info: site is written in PHP with PDO for DB functions and MySQL DB. I also managed to get the JSON output on the site. In the android app, I also use Volley and it's written in Java (not Kotlin). I would really appreciate the help and if you need more info (or maybe a part of the code), be sure to ask.
Regards
Christophe
Edit: hereby the requested code:
LoginActivity:
package package_name;
some imports...
public class LoginActivity extends AppCompatActivity {
private static final String TAG = "Scorpio To Do Login: ";
GoogleSignInOptions gso;
GoogleSignInClient mGoogleSignInClient;
SignInButton signInButton;
private int RC_SIGN_IN = 6;
private static final String URL_DATA = "https://some.url.be";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Configure sign-in to request the user's ID, email address, and basic
// profile. ID and basic profile are included in DEFAULT_SIGN_IN.
gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.server_client_id))
.requestEmail()
.build();
// Build a GoogleSignInClient with the options specified by gso.
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}
#Override
protected void onStart() {
super.onStart();
// Check for existing Google Sign In account, if the user is already signed in
// the GoogleSignInAccount will be non-null.
GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
updateUI(account);
}
private void updateUI(GoogleSignInAccount account) {
Log.w(TAG, "account = " + account);
if(account == null){
// Set the dimensions of the sign-in button.
signInButton = findViewById(R.id.sign_in_button);
signInButton.setSize(SignInButton.SIZE_WIDE);
signInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
signIn();
}
});
signInButton.setVisibility(View.VISIBLE);
} else {
Context context = LoginActivity.this;
/* This is the class that we want to start (and open) when the button is clicked. */
Class destinationActivity = TaskActivity.class;
/*
* Here, we create the Intent that will start the Activity we specified above in
* the destinationActivity variable. The constructor for an Intent also requires a
* context, which we stored in the variable named "context".
*/
Intent startChildActivityIntent = new Intent(context, destinationActivity);
/*
* Once the Intent has been created, we can use Activity's method, "startActivity"
* to start the ChildActivity.
*/
startActivity(startChildActivityIntent);
}
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInClient.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
// The Task returned from this call is always completed, no need to attach
// a listener.
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
handleSignInResult(task);
}
}
private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
try {
GoogleSignInAccount account = completedTask.getResult(ApiException.class);
String idToken = account.getIdToken();
Log.d("Token: ", idToken);
// Signed in successfully, show authenticated UI.
updateUI(account);
} catch (ApiException e) {
// The ApiException status code indicates the detailed failure reason.
// Please refer to the GoogleSignInStatusCodes class reference for more information.
Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
updateUI(null);
}
}
}
TaskActivity:
package package_name;
some imports...
public class TaskActivity extends AppCompatActivity {
private static final String URL_DATA = "https://some.url.be";
private RecyclerView recyclerView;
private RecyclerView.Adapter scorpioAdapter;
private List<ListItem> listItems;
String JSON_STRING;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task);
recyclerView = findViewById(R.id.rv);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems = new ArrayList<>();
}
/*REAL DATA*/
/*try instead of loadRecyclerViewData*/
public void getJSON(View view){
new BackgroundTask().execute();
}
/*end try*/
private void loadRecyclerViewData() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Loading data...");
progressDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.GET,
URL_DATA,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
progressDialog.dismiss();
try {
JSONArray jsonArray = new JSONArray(s);
for(int i=0;i<jsonArray.length();i++){
JSONObject o = jsonArray.getJSONObject(i);
int id = o.getInt("id");
String name = o.getString("name");
int done = o.getInt("done");
String reminderDate = o.getString("reminderdate");
String reminderTime = o.getString("remindertime");
ListItem item = new ListItem(id, name, done, reminderDate, reminderTime);
listItems.add(item);
}
scorpioAdapter = new ScorpioAdapter(listItems, getApplicationContext());
recyclerView.setAdapter(scorpioAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(getApplicationContext(), volleyError.getMessage(), Toast.LENGTH_LONG).show();
}
}
);
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
/*END REAL DATA*/
/* things I tried*/
class BackgroundTask extends AsyncTask<Void, Void, String> {
String json_url;
#Override
protected void onPreExecute() {
json_url = "https://some.url.be";
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
Log.i("Scorpio To Do: ", result);
TextView name = (TextView) findViewById(R.id.name);
name.setText(result);
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(json_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((JSON_STRING = bufferedReader.readLine()) != null){
stringBuilder.append(JSON_STRING + "\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
/*end try*/
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I'm trying to use this good tutorial in Dialog like this for Login action:
public class MainActivity extends AppCompatActivity {
private SQLiteHandler db;
public ProgressDialog pDialog;
public SessionManager session;
private DrawerLayout drawerLayout;
private static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Displaying the user details on the screen
TextView txtName = (TextView) findViewById(R.id.usernamehd);
TextView txtEmail = (TextView) findViewById(R.id.emailuserr);
db = new SQLiteHandler(getApplicationContext());
HashMap<String, String> user = db.getUserDetails();
String name = user.get("name");
String email = user.get("email");
txtName.setText(name);
txtEmail.setText(email);
TextView sgnin = (TextView) findViewById(R.id.signinbtn);
sgnin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Dialog d = new Dialog(MainActivity.this);
d.setContentView(R.layout.dialog);
String title = getResources().getString(R.string.dialog_title);
d.setTitle(title);
d.show();
// first dialog for showing that dialog Login-register
final EditText inusremail = (EditText) d.findViewById(R.id.emailuserr);
final EditText inpass = (EditText) d.findViewById(R.id.passworduser);
final Button btnLogin = (Button) d.findViewById(R.id.Login);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setCancelable(false);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = inusremail.getText().toString();
String password = inpass.getText().toString();
if (email.trim().length() > 0 && password.trim().length() > 0) {
checkLogin(email, password);
} else {
Toast.makeText(getApplicationContext(), "Please enter the credentials!", Toast.LENGTH_LONG).show();
}
}
});
//end the Login button
}
});
And here is the function for CheckLogin:
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Request.Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
// Check for error node in json
if (!error) {
// user successfully logged in
// Create login session
session.setLogin(true);
// Launch main activity
Intent intent = new Intent(MainActivity.this,
MainActivity.class);
startActivity(intent);
finish();
} else {
// Error in login. Get the error message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// JSON error
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "login");
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();
}
But, there is a problem and i dont know what is it:
java.lang.NullPointerException: Attempt to invoke virtual method 'void client.package.helper.SessionManager.setLogin(boolean)' on a null object reference
at client.package.MainActivity$6.onResponse(MainActivity.java:257)
at client.package.MainActivity$6.onResponse(MainActivity.java:242)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
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:5254)
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)
i just change the package name
and of course, Register is working and i can save the user credentials in the server side but, there is a similar problem in this and i dont know how can i fix that in one Acttivity.
Any help would be great.
session.setLogin(true);
You must make sure that session is initialized..
To be extra careful:
if(session!=null)
session.setLogin(true);
The error says Object of SessionManager is null. You have not initialized the object after declaration.
SessionManager session; //declared
session = New SessionManager(Arguments); //Intialized