I'm developing a program that generates random passwords, but I'm bad at databases. I can generate password, but I want to send the generated password to realtime database with Firebase, but I can't. What should I do?
My code in mainactivity is like this :
import androidx.appcompat.app.AppCompatActivity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
Button button;
TextView textView;
CheckBox num;
CheckBox upper;
CheckBox lower;
CheckBox sym;
EditText max_lenght;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button5);
button = (Button)findViewById(R.id.button5);
textView = (TextView)findViewById(R.id.textView) ;
textView=(TextView)findViewById(R.id.textView2);
num= (CheckBox)findViewById(R.id.num);
upper=(CheckBox)findViewById(R.id.upper) ;
lower=(CheckBox)findViewById(R.id.lower) ;
sym=(CheckBox)findViewById(R.id.sym) ;
max_lenght=(EditText) findViewById(R.id.editTextNumberSigned);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View pas) {
String pass = randompassword(Integer.parseInt(max_lenght.getText().toString()),upper.isChecked(),lower.isChecked(),num.isChecked(),sym.isChecked());
if (pass.isEmpty()){
Toast.makeText(getApplicationContext(),"Lütfen Veri Giriniz !!",Toast.LENGTH_SHORT).show();
}
else {
ClipboardManager clipboardManager = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clipData = ClipData.newPlainText("Veri",pass);
clipboardManager.setPrimaryClip(clipData);
Toast.makeText(getApplicationContext(),"Sifreniz Olusturuldu... ",Toast.LENGTH_LONG).show();
}
textView.setText(pass);
}
});
}
private static String randompassword(int max_lenght, boolean upperCase, boolean lowerCase, boolean numbers, boolean specialCharacters)
{
String upperCaseChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String lowerCaseChars = "abcdefghijklmnopqrstuvwxyz";
String numberChars = "0123456789";
String specialChars = "!##$%^&*()_-+=<>?/{}~|";
String allowedChars = "";
Random rn = new Random();
StringBuilder sb = new StringBuilder(max_lenght);
if (upperCase){
allowedChars+=upperCaseChars;
sb.append(upperCaseChars.charAt(rn.nextInt(upperCaseChars.length()-1)));
}
if(lowerCase){
allowedChars+=lowerCaseChars;
sb.append(lowerCaseChars.charAt(rn.nextInt(lowerCaseChars.length()-1)));
}
if (numbers){
allowedChars+=numberChars;
sb.append(numberChars.charAt(rn.nextInt(numberChars.length()-1)));
}
if (specialCharacters){
allowedChars+=specialChars;
sb.append(specialChars.charAt(rn.nextInt(specialChars.length()-1)));
}
sb.append(allowedChars.charAt(rn.nextInt(allowedChars.length()-1)));
for(int i=sb.length();i < max_lenght; ++i){
sb.append(allowedChars.charAt(rn.nextInt(allowedChars.length())));
}
return sb.toString();
}
}
I have defined the things required for firebase, but I don't know where to write in the main part.
After generating the random password, you can send to the database in the following way:
private DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child("passwords").child(/*how so ever you want to nest data*/).setValue(password);
This is just a snippet to get you started, you can read more Read and write data.
Related
I have a feature in my program where I have to enter the user's details such as the user's age, height, and weight. This data will be stored in Firestore.
this is how the user will input their details
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.button.MaterialButton;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
public class account_information extends AppCompatActivity {
public static final String TAG = "TAG";
EditText et_age, et_height, et_weight;
Button btn_create;
FirebaseFirestore db;
FirebaseAuth mAuth;
String userID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account_information);
mAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
et_age = findViewById(R.id.et_age);
et_height = findViewById(R.id.et_height);
et_weight = findViewById(R.id.et_weight);
btn_create = findViewById(R.id.btn_create);
btn_create.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String age = et_age.getText().toString().trim();
String height = et_height.getText().toString().trim();
String weight = et_weight.getText().toString().trim();
if(age.isEmpty()){
et_age.setError("Age is mandatory");
et_age.requestFocus();
return;
}
if(height.isEmpty()){
et_height.setError("Height is mandatory");
et_height.requestFocus();
return;
}
if(weight.isEmpty()){
et_weight.setError("Weight is mandatory");
et_weight.requestFocus();
return;
}
userID = mAuth.getCurrentUser().getUid();
DocumentReference documentReference = db.collection("userDetail").document(userID);
Map<String,Object> user = new HashMap<>();
user.put("Age",age);
user.put("Height",height);
user.put("Weight",weight);
user.put("UserId", userID);
documentReference.set(user)
.addOnSuccessListener((OnSuccessListener) (aVoid) -> {
Log.d(TAG, "onSuccess: user Detail is created for "+ userID);
startActivity(new Intent(account_information.this, MainActivity.class));
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull #NotNull Exception e) {
Log.d(TAG, "onFailure"+ e.toString());
}
});
}
});
}
}
And this is how it will store in firebase
https://imgur.com/a/wtCJt8X
However, when the user decides to update their profile (for example his weight) the rest of the input will pass an empty string at the firebase
like this:
https://imgur.com/oskucbl
And this is how the user can update their details
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import org.jetbrains.annotations.NotNull;
public class UpdateProfile extends AppCompatActivity {
public static final String TAG = "TAG";
EditText et_age, et_height, et_weight;
Button btn_update;
FirebaseAuth mAuth;
FirebaseFirestore mStore;
String userID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_profile);
et_age = findViewById(R.id.et_age);
et_height = findViewById(R.id.et_height);
et_weight = findViewById(R.id.et_weight);
btn_update = findViewById(R.id.btn_update);
mAuth = FirebaseAuth.getInstance();
mStore = FirebaseFirestore.getInstance();
userID = mAuth.getCurrentUser().getUid();
btn_update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String age = et_age.getText().toString().trim();
String height = et_height.getText().toString().trim();
String weight = et_weight.getText().toString().trim();
userID = mAuth.getCurrentUser().getUid();
DocumentReference documentReference = mStore.collection("userDetail").document(userID);
documentReference
.update("Age",age, "Height",height, "Weight",weight)
.addOnSuccessListener((OnSuccessListener) (aVoid) -> {
Log.d(TAG, "onSuccess: user Detail is created for "+ userID);
startActivity(new Intent(UpdateProfile.this, MainActivity.class));
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull #NotNull Exception e) {
Log.d(TAG, "onFailure"+ e.toString());
}
});
}
});
}}
Update: I've tried the method of #zen_of_kermit but I got the same problem, maybe there's something in the code that I've missed
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import org.jetbrains.annotations.NotNull;
import java.util.HashMap;
import java.util.Map;
public class UpdateProfile extends AppCompatActivity {
public static final String TAG = "TAG";
EditText et_age, et_height, et_weight;
Button btn_update;
FirebaseAuth mAuth;
FirebaseFirestore mStore;
String userID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_profile);
et_age = findViewById(R.id.et_age);
et_height = findViewById(R.id.et_height);
et_weight = findViewById(R.id.et_weight);
btn_update = findViewById(R.id.btn_update);
mAuth = FirebaseAuth.getInstance();
mStore = FirebaseFirestore.getInstance();
userID = mAuth.getCurrentUser().getUid();
btn_update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String age = et_age.getText().toString().trim();
String height = et_height.getText().toString().trim();
String weight = et_weight.getText().toString().trim();
userID = mAuth.getCurrentUser().getUid();
DocumentReference documentReference = mStore.collection("userDetail").document(userID);
Map<String, Object> dataToUpdateMap = new HashMap<>();
if (isValidAndChanged(documentReference, "Age", age)) {
dataToUpdateMap.put("Age", age);
}
if (isValidAndChanged(documentReference, "Height", height)) {
dataToUpdateMap.put("Height", height);
}
if (isValidAndChanged(documentReference, "Weight", weight)) {
dataToUpdateMap.put("Weight", weight);
}
documentReference.update(dataToUpdateMap).addOnSuccessListener((OnSuccessListener) (aVoid) -> {
Log.d(TAG, "onSuccess: user Detail is created for "+ userID);
startActivity(new Intent(UpdateProfile.this, readProfileData.class));
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull #NotNull Exception e) {
Log.d(TAG, "onFailure"+ e.toString());
}
});
}
});
}
boolean isValidAndChanged(DocumentReference docRef, String key, Object value) {
return true;
}
}
You are passing all three fields (age, height, weight) without checking if they are valid or contain changes to the existing data. You should make those checks before calling update, similar to how you did in the create function.
For example, create a function to check if new data is valid and different than old data:
boolean isValidAndChanged(DocumentReference docRef, String key, String value) {
// TODO get snapshot of data and compare to new value
}
And then use that to update (passing a Map to update instead of var-args):
String age = et_age.getText().toString().trim();
String height = et_height.getText().toString().trim();
String weight = et_weight.getText().toString().trim();
userID = mAuth.getCurrentUser().getUid();
DocumentReference documentReference = mStore.collection("userDetail").document(userID);
Map<String, String> dataToUpdateMap = new HashMap<>();
if (isValidAndChanged(documentReference, "Age", age)) {
dataToUpdateMap.put("Age", age);
}
if (isValidAndChanged(documentReference, "Height", height)) {
dataToUpdateMap.put("Height", height);
}
if (isValidAndChanged(documentReference, "Weight", weight)) {
dataToUpdateMap.put("Weight", weight);
}
documentReference.update(dataToUpdateMap)
// ...
Also, best practice is to use constants instead of passing magic strings around all over your code (e.g. "Age" becomes AGE.)
You're getting all the data overwritten because you're passing empty strings to the update() method. Firestore can indeed hold null values, but the values of Age and Height after the update are not null, but empty strings.
If you want to update a single field and leave the other ones untouched, then you should simply pass to the update() method only values for the fields you need to update. In code, it should look like this:
documentReference.update("Weight", weight).addOnSuccessListener(/* ... /*);
I've tried using both SharedPrefrences and also saving to internal storage but I cannot get the results I want. The only results I have achieved are crashes.
I have an app that generates a custom password based on user options, it then enters those password into an Arraylist if the user clicks a button to save the password. However, when the app closes all data is lost.
How do I save the populated ArrayList or ListView so when the user clicks views passwords they can see their previously saved passwords?
* MAIN ACTIVITY JAVA *
package com.jrfapplications.passgen;
import android.content.Context;
import android.content.Intent;
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.TextView;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import static com.jrfapplications.passgen.SettingsPage.CustPass;
import static com.jrfapplications.passgen.SettingsPage.FBPass;
import static com.jrfapplications.passgen.SettingsPage.custword;
import static com.jrfapplications.passgen.SettingsPage.custwordend;
import static com.jrfapplications.passgen.SettingsPage.isEndWordChecked;
import static com.jrfapplications.passgen.SettingsPage.isHighCaseChecked;
import static com.jrfapplications.passgen.SettingsPage.isNumbChecked;
import static com.jrfapplications.passgen.SettingsPage.isSpecChecked;
import static com.jrfapplications.passgen.SettingsPage.isStartCustWordChecked;
import static com.jrfapplications.passgen.SettingsPage.passLength;
public class MainActivity extends AppCompatActivity implements Serializable {
//Buttons
Button btnGoToSet;
Button btnGenPass;
Button btnViewPass;
Button btnSavePass;
//TextView
TextView passView;
//Saved Pass Array
static ArrayList<String> SavedCustomPasswords = new ArrayList<>();
static ArrayList<String> SavedFacebookPasswords = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Find Buttons
btnGoToSet = (Button) findViewById(R.id.settingsbtn);
btnGenPass = (Button) findViewById(R.id.genpass);
btnViewPass = (Button) findViewById(R.id.viewpassbtn);
btnSavePass = (Button) findViewById(R.id.SavePassBtn);
//Find TextView
passView = (TextView) findViewById(R.id.pwEditTxt);
//Button Functions
btnGoToSet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, SettingsPage.class));
}
});
btnGenPass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
generatePassword(generateCharSet());
}
});
btnSavePass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (CustPass == 1){
if (SavedCustomPasswords.contains(passView.getText().toString())){
Toast.makeText(getApplicationContext(), "Password Already Saved", Toast.LENGTH_SHORT).show();
}else{
SavedCustomPasswords.add(passView.getText().toString());
Toast.makeText(getApplicationContext(), "Password Saved", Toast.LENGTH_SHORT).show();
}
}
if (FBPass == 1){
if (SavedFacebookPasswords.contains(passView.getText().toString())){
Toast.makeText(getApplicationContext(), "Password Already Saved", Toast.LENGTH_SHORT).show();
}else{
SavedFacebookPasswords.add(passView.getText().toString());
Toast.makeText(getApplicationContext(), "Password Saved", Toast.LENGTH_SHORT).show();
}
}
}
});
btnViewPass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, view_pass.class));
}
});
}
public char[] generateCharSet() {
String numbers = "0123456789";
String special = "!£$%^&*()";
String alphabetsLower = "abcdefghijklmnopqrstuvwxyz";
String alphabetsUpper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// Add lower alphabets by default
StringBuilder finalCharset = new StringBuilder(alphabetsLower);
// Add special chars if option is selected
if (isSpecChecked == 1) {
finalCharset.append(special);
}
// Add upper case chars if option is selected
if (isHighCaseChecked == 1) {
finalCharset.append(alphabetsUpper);
}
// Add numbers if option is selected
if (isNumbChecked == 1) {
finalCharset.append(numbers);
}
// build the final character set
return finalCharset.toString().toCharArray();
}
public void generatePassword(char[] charset) {
final StringBuilder sb = new StringBuilder();
Random random = new Random();
for (int i = 0; i < passLength; i++) {
char c = charset[random.nextInt(charset.length)];
sb.append(c);
}
if (isStartCustWordChecked == 1 && isEndWordChecked == 1){
final String output = custword + sb.toString() + custwordend;
passView.setText(output);
}else if (isStartCustWordChecked == 1){
final String output = custword + sb.toString();
passView.setText(output);
}else if (isEndWordChecked == 1){
final String output = sb.toString() + custwordend;
passView.setText(output);
}else
{
final String output = sb.toString();
passView.setText(output);
}
}
}
* VIEW PASS JAVA *
package com.jrfapplications.passgen;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class view_pass extends AppCompatActivity {
private ListView mListView1, mListView2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_pass);
mListView1 = (ListView)findViewById(R.id.listView1);
mListView2 = (ListView)findViewById(R.id.listView2);
mListView1.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, MainActivity.SavedCustomPasswords));
mListView2.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, MainActivity.SavedFacebookPasswords));
ListUtils.setDynamicHeight(mListView1);
ListUtils.setDynamicHeight(mListView2);
}
public static class ListUtils {
public static void setDynamicHeight(ListView mListView) {
ListAdapter mListAdapter = mListView.getAdapter();
if (mListAdapter == null) {
// when adapter is null
return;
}
int height = 0;
int desiredWidth = View.MeasureSpec.makeMeasureSpec(mListView.getWidth(), View.MeasureSpec.UNSPECIFIED);
for (int i = 0; i < mListAdapter.getCount(); i++) {
View listItem = mListAdapter.getView(i, null, mListView);
listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
height += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = mListView.getLayoutParams();
params.height = height + (mListView.getDividerHeight() * (mListAdapter.getCount() - 1));
mListView.setLayoutParams(params);
mListView.requestLayout();
}
}
}
This can be done by simply storing the generated password into sqlite database. https://developer.android.com/training/basics/data-storage/databases.html
You can also use cursor loaders for a better performance.
https://developer.android.com/guide/components/loaders.html
Try using a DBMS, if you want it stored locally, I would recommend SQL, or cloud-based system like Firebase
Shared preferences and Gson, much simple.
I used shared preferences to to save my ArrayLists on close thanks for the direction guys!
Using this for my answer:
Android: keep values in list after app shutdown
static ArrayList<String> SavedCustomPasswords = new ArrayList<>();
SavedCustomPasswords = getArray();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, SavedCustomPasswords);
adapter.notifyDataSetChanged();
public boolean saveArray() {
SharedPreferences sp = this.getSharedPreferences(SHARED_PREFS_NAME, Activity.MODE_PRIVATE);
SharedPreferences.Editor mEdit1 = sp.edit();
Set<String> set = new HashSet<String>();
set.addAll(SavedCustomPasswords);
mEdit1.putStringSet("list", set);
return mEdit1.commit();
}
public void onStop() {
saveArray();
super.onStop();
}
public ArrayList<String> getArray() {
SharedPreferences sp = this.getSharedPreferences(SHARED_PREFS_NAME, Activity.MODE_PRIVATE);
//NOTE: if shared preference is null, the method return empty Hashset and not null
Set<String> set = sp.getStringSet("list", new HashSet<String>());
return new ArrayList<String>(set);
}
I want to send the username and password to the server and it returns a response whether the username and password matches. I do not want to ask for login each time my app starts, instead I want to remain in the home_screen until I logout from my android app. How can I do this? any example will be thankfull..
package com.example.test5;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity implements OnClickListener{
private EditText username;
private EditText password;
private Button login;
static String u;
static String p;
Context context = MainActivity.this;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText)findViewById(R.id.editText1);//Visibility
password = (EditText)findViewById(R.id.editText2);//Visibility
login = (Button)findViewById(R.id.button1);//Visibility
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
u = username.getText().toString();
p = password.getText().toString();
Toast.makeText(MainActivity.this, "Checking User Login",Toast.LENGTH_SHORT).show();
new MyAsyncTask_Login(context).execute(u,p);
}
});
}
#Override
public void onClick(DialogInterface dialog, int which) {
}
}
my asynctask class
package com.example.test5;
import java.io.StringReader;
import java.util.LinkedList;
import java.util.List;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.XmlResourceParser;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.widget.Toast;
public class MyAsyncTask_Login extends AsyncTask<String, Void, String>{
public static final String MyPREFERENCES = "MyPrefs" ; //editor: never used
public static final String userName = "name";
public static final String Password = "password";
SharedPreferences sharedpreferences; //editor: never used
private Context context;
public MyAsyncTask_Login(Context context) {
this.context = context;
}
#Override
protected String doInBackground(String... params) {
String response = new Login_WebService().checkLogin(params[0], params[1]);
return response;
}
#Override
protected void onPostExecute(String result) {
String strResponse = result;
try {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser parser = factory.newPullParser();
parser.setInput(new StringReader(strResponse));
List<String> tags = new LinkedList<String>();
tags.add("valid");
for (int type = parser.next(); type != XmlResourceParser.END_DOCUMENT; type = parser.next()) {
if (type == XmlResourceParser.START_TAG) {
String name = parser.getName();
if (tags.contains(name)) {
type = parser.next();
if (parser.getText().trim().equals("1")) {
Toast.makeText(context, "logged in succesfully.",Toast.LENGTH_SHORT).show();
try {
String user = MainActivity.u;
String pass = MainActivity.p;
Intent i = new Intent(context,Home_page.class);
context.startActivity(i);
}
catch (Exception e) {
Toast.makeText(context, e.toString(),Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(context, "Invalid User",Toast.LENGTH_SHORT).show();
}
}
}
}
}
catch (Exception e) {
}
}
}
You can do like this:
Save your login data in shared Preferences.
When the user login:
protected void doInBackground(Activity... params) {
Activity activity = (Activity) params[0];
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);//Pass activity in params o
Editor editor = prefs.edit();
editor.putString("username",u);
editor.putString("password",p);
editor.commit();
}
in on create when the user restart the app read the shared preferences:
u = prefs.getString("username", "");
p = prefs.getString("password", "");
if(u.equals("") || p.equals(""))
//user needs new login
else
//user already login
To make logout put "" in sharedpreferences.
I populate an alerttdialog from a database. I store these values in an arrayList, convert them to an charsequence list then set them to my alertdialog builder. As shown:
This is a screenshot of my populated 'text template' options from my database:
At the moment when I click one of my options for example Call me. it displays as it should within a specified edittext. If I click on one of the other options such as 'Email me' this is ignored, only my first 'if' option Call me. will work as shown:
This leads me to believe for some reason only Call me has been added to my charsequence array but I'm not sure why. Here is my complete class. I am getting this issue at the longOnClick method. I have marked this issue area on the code below:
package com.example.flybase2;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class ContactsEmail extends Activity implements OnClickListener, OnLongClickListener{
String emailPassed;
String emailAdd;
String emailSub;
String emailMess;
EditText setEmailAddress;
EditText setEmailSubject;
EditText setEmailMessage;
Button btnSendEmail;
int i;
CharSequence[] items;
DBHandlerTempComms addTemp = new DBHandlerTempComms(this, null, null);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.emaillayout);
Bundle extras = getIntent().getExtras();
if (extras != null) {
emailPassed = extras.getString("passedEmailAdd");
}
setEmailAddress = (EditText) findViewById (R.id.inputEmailAddress);
setEmailAddress.setText(emailPassed);
setEmailSubject = (EditText) findViewById (R.id.inputEmailSubject);
setEmailMessage = (EditText) findViewById (R.id.inputEmailMessage);
btnSendEmail = (Button)findViewById(R.id.btnSendEmail);
btnSendEmail.setOnClickListener(this);
setEmailMessage.setOnLongClickListener(this);
}
#Override
public void onClick(View sendEmailClick) {
emailAdd = setEmailAddress.getText().toString();
emailSub = setEmailSubject.getText().toString();
emailMess = setEmailMessage.getText().toString();
Intent sendEmailIntent = new Intent(Intent.ACTION_SEND);
sendEmailIntent.setType("message/rfc822");
sendEmailIntent.putExtra(Intent.EXTRA_EMAIL,new String[] {emailAdd});
sendEmailIntent.putExtra(Intent.EXTRA_SUBJECT, emailSub);
sendEmailIntent.putExtra(Intent.EXTRA_TEXT, emailMess);
startActivity(Intent.createChooser(sendEmailIntent, "Send mail..."));
finish();
}
*********************ISSUE AREA********************
#Override
public boolean onLongClick(View v) {
addTemp.open();
Cursor getTemps = addTemp.setList();
addTemp.close();
if (getTemps != null) {
String[] from = new String[getTemps.getCount()];
startManagingCursor(getTemps);
if (getTemps.moveToFirst()) {
int count = 0;
do {
String userName = getTemps.getString(1);
from[count] = userName;
count++;
} while (getTemps.moveToNext());
}
ArrayList<String> content = new ArrayList<String>();
for (int a = 0; a < from.length; a ++)
{
content.add(from[a]);
}
items = content.toArray(new CharSequence[content.size()]);
}
Builder alertDialogBuilder = new AlertDialog.Builder(ContactsEmail.this);
alertDialogBuilder.setTitle("Message Templates:");
alertDialogBuilder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Call me.")) {
setEmailMessage.setText(items[item]);
}
else if (items[item].equals("Text me.")) {
setEmailMessage.setText(items[item]);
}
else if (items[item].equals("Leaving the house now.")) {
setEmailMessage.setText(items[item]);
}
else if (items[item].equals("Leaving work now.")) {
setEmailMessage.setText(items[item]);
}
else if (items[item].equals("Create New Template +")) {
AlertDialog.Builder builder = new AlertDialog.Builder(ContactsEmail.this);
builder.setTitle("Type New Template:");
final EditText input = new EditText(ContactsEmail.this);
builder.setView(input);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Editable value = input.getText();
setEmailMessage.setText(value);
String templateValue = (String)value.toString();
addTemp.open();
addTemp.insertTemplate(templateValue);
addTemp.close();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
builder.show();
}
}
});
alertDialogBuilder.show();
return true;
}
}
Slightly embarrassing but I've just realized I have different strings comparing my IFs to the strings stored in the charsequence, so it is now working!
I'm new to Android development and I'm wondering why my code crashes the Android Emulator. What I'm doing is creating an array of strings, then picking an index from the array at random and displaying the value inside a TextView. But it always seems to crash my emu.
package com.test.randomTest;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class randomTestActivity extends Activity {
private Button button;
private TextView helloTextView;
private String[] hellos;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
helloTextView = (TextView)findViewById(R.id.helloText);
button = (Button)findViewById(R.id.button);
hellos = new String[7];
hellos[0] = "Hello";
hellos[1] = "G'days";
hellos[2] = "Yo!";
hellos[3] = "Hi";
hellos[4] = "Hay";
hellos[5] = "Bonjour";
hellos[6] = "Hay there!";
hellos[7] = "Hallo";
button.setOnClickListener(buttonListener);
}
private OnClickListener buttonListener = new OnClickListener() {
public void onClick(View v) {
int x = 0 + (int)(Math.random() * ((7 - 0) + 1));
String helloText = hellos[x];
helloTextView.setText(helloText);
}
};
}
Any help/advice would be great!
Thanks.
You created a String[] of size 7.
hellos = new String[7];
Therefore the indices range from 0 to 6. Trying to access hellos[7] will cause an IndexOutOfBoundsException.
I assume your getting a nullpointerexecption. Try generating your random number like this instead:
Random rando = new Random();
int x = rando.nextInt(hellos.lenght);
package com.test.randomTest;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class randomTestActivity extends Activity {
private Button button;
private TextView helloTextView;
private String[] hellos;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
helloTextView = (TextView)findViewById(R.id.helloText);
button = (Button)findViewById(R.id.button);
hellos = new String[8];
hellos[0] = "Hello";
hellos[1] = "G'days";
hellos[2] = "Yo!";
hellos[3] = "Hi";
hellos[4] = "Hay";
hellos[5] = "Bonjour";
hellos[6] = "Hay there!";
hellos[7] = "Hallo";
button.setOnClickListener(buttonListener);
}
private OnClickListener buttonListener = new OnClickListener() {
public void onClick(View v) {
int x = 0 + (int)(Math.random() * ((7 - 0) + 1));
String helloText = hellos[x];
helloTextView.setText(helloText);
}
};
}
Increase string array size you gave 7 as size, but you are passing 8 values to string.
so it throws indexoutofbounds exception.
Thats probably because of array IndexOutOfBoundException... since sometimes your x will have value 8 but array length is just 7..