i'm having some trouble working with there checkbox. So in my app the user as 2 check boxes, and then a button, that button opens a new intent, and i need to pass the information through the intent to know if the checkbox is checked or not. I'm passing that information with the .putExtra() but then in the new intent when i do a if statement my app always crashes here because it gives me always a null pointer exception.
Here's the code for the button and pass the information:
final CheckBox sabado = (CheckBox) findViewById(R.id.checkBoxSabado);
final CheckBox domingo = (CheckBox) findViewById(R.id.checkBoxDomingo);
//Clique no botao "PROCURAR"
buttonProcurar.setOnClickListener(
new Button.OnClickListener(){
#Override
public void onClick(View v) {
if(deTextPartida.getText().toString().equals(paraTextDestino.getText().toString())){
Toast.makeText(getBaseContext(), "Partida e destino nao podem ser iguais, escolha de novo!", Toast.LENGTH_LONG).show();
}
else{
Intent i = new Intent(horariosMenu.this, mostraHorario.class);
i.putExtra("Partida", deTextPartida.getText().toString());
i.putExtra("Destino", paraTextDestino.getText().toString());
i.putExtra("Sabado", sabado.isChecked());
i.putExtra("Domingo", domingo.isChecked());
startActivity(i);
}
}
}
);
And here's the code to get it:
Bundle data = getIntent().getExtras();
if(data == null){
return;
}
String Partida = data.getString("Partida");
String Destino = data.getString("Destino");
String Sabado = data.getString("Sabado");
String Domingo = data.getString("Domingo");
if(Sabado.equals("true")){
Toast.makeText(getBaseContext(), Sabado, Toast.LENGTH_LONG).show();
}
What am i doing wrong guys ? :X
In "sabado" y "domingo" you are sending boolean values through putExtra method. Then in the Activity that receive the data, you assign a String value. You can write some like:
i.putExtra("Sabado", sabado.isChecked()+"");
i.putExtra("Domingo", domingo.isChecked()+"");
And then:
String Sabado = data.getString("Sabado");
String Domingo = data.getString("Domingo");
So ended up solving my problem. I'll post here so if in the future there are some with the same problem they can check right here.
I just changed my bundle, i found a way to get the Extras information another way :
Intent intent = getIntent();
String Partida = intent.getStringExtra("Partida");
String Destino = intent.getStringExtra("Destino");
boolean Sabado = intent.getBooleanExtra("Sabado", true);
boolean Domingo = intent.getBooleanExtra("Domingo", true);
And in the if statement (the one causing problem) i just had to do:
if(Sabado){
Toast.makeText(getBaseContext(), Sabado, Toast.LENGTH_LONG).show();
}
Because now "Sabado" is a boolean, and so in if(Sabado) i check if he is true or false, wich is the value of if the checkbox is checked or not.
So that's it guys, hope it helps
Related
I made another post to explain better, ok? :)
This video shows exactly what I mean:
The video is: https://www.youtube.com/watch?v=DCg00fe-_xs
Firebase normally stores data. After the 6th second of the video, trying to enter new data, the data stays about a second in Firebase, but automatically then it disappears.
I try to input the data into Firebase two more times in this video, but the data always automatically disappears afterwards.
You can see that the other datas that are stored in Firebase does NOT disappear. But the data of this code is automatically disappearing for some reason as shown in the video. Please what can I do to fix it?
Code:
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String raça = spinner_raca.getSelectedItem().toString();
final String regiaoDoEstado = spinner_regiaoDoEstado.getSelectedItem().toString();
final String estado = spinner_estado.getSelectedItem().toString();
Intent receiverIntent = getIntent();
Bundle bundleRecebedor = receiverIntent.getExtras();
String nomecompleto = bundleRecebedor.getString("nomecompleto");
String email = bundleRecebedor.getString("email");
String doencasPreExistentes = bundleRecebedor.getString("doencasPreExistentes");
String dataDeNascimento = bundleRecebedor.getString("dataDeNascimento");
String genero = bundleRecebedor.getString("genero");
String identificadorEmHash = bundleRecebedor.getString("identificadorEmHash");
String telefone = receiverIntent.getStringExtra("telefone");
reference = FirebaseDatabase.getInstance().getReference().child("Usuarios").child(identificadorEmHash);
Toast.makeText(getApplicationContext(), identificadorEmHash, Toast.LENGTH_LONG).show();
if(identificadorEmHash.equals(null)) {
Toast.makeText(getApplicationContext(), "The identifier does not exist", Toast.LENGTH_LONG).show();
} else {
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
reference = FirebaseDatabase.getInstance().getReference().child("Usuarios").child(identificadorEmHash);
if (!dataSnapshot.exists()) {
Toast.makeText(getApplicationContext(), "The identifier does not exist", Toast.LENGTH_LONG).show();
} else {
HashMap<String, String> sendDataToDataBase = new HashMap<>();
sendDataToDataBase.put("Nome Completo", nomecompleto);
sendDataToDataBase.put("E-mail", email);
sendDataToDataBase.put("Identificador em Hash", identificadorEmHash);
sendDataToDataBase.put("Telefone", telefone);
sendDataToDataBase.put("Doenças Pré Existentes", doencasPreExistentes);
sendDataToDataBase.put("Data de Nascimento", dataDeNascimento);
sendDataToDataBase.put("Gênero", genero);
// When I am going to send the following data to Firebase, the problem of the video happens.
sendDataToDataBase.put("Região do Estado em que mora", regiaoDoEstado);
sendDataToDataBase.put("Raça", raça);
sendDataToDataBase.put("Estado do Brasil em que mora", estado);
try {
raiz.child(identificadorEmHash).setValue(sendDataToDataBase);
} catch (Exception e) {
e.getMessage();
}
}
}
});
}
}
});
Please, can someone help me to fix this bug?
Firebase doesn't automatically delete data, so if you see the data show up in the console it was written there by a client/API call, and allowed by your security rules. If the data subsequently gets updates or removed again, there is another client/API call that does so.
I recommend checking for realtime listeners in your code, that may be responding to your first write by updating (and accidentally reverting) that operation. It is also quite common to have a server-side script that is doing this.
Update: one thing you can try is to use updateChildren instead of setValue in all places such as this one:
raiz.child(identificadorEmHash).updateChildren(sendDataToDataBase)
This is my Activity 1
final Intent ridesameIntent = new Intent(this, Activity2.class);
TextView userText = (TextView) findViewById(R.id.username);
ImageView userImage = (ImageView) findViewById(R.id.profile_pic);
String userNameMessage = userText.getText().toString();
String userPicMessage = userImage.toString();
ridesameIntent.putExtra(EXTRA_MESSAGE_USERNAME,userNameMessage);
ridesameIntent.putExtra(EXTRA_MESSAGE_USERPIC,userPicMessage);
startActivity(ridesameIntent);
This is Activity 2
Intent userDetail = getIntent();
String userPicMessage = userDetail.getStringExtra(Activity1.EXTRA_MESSAGE_USERPIC);
String userNameMessage = userDetail.getStringExtra(Activity1.EXTRA_MESSAGE_USERNAME);
TextView userdetail1 = (TextView) findViewById(R.id.username_scroll);
ImageView userdetail2 = (ImageView) findViewById(R.id.profile_pic_scroll);
userdetail1.setText(userNameMessage);
userdetail2.setImageURI(Uri.parse(userPicMessage));
I have tried passing the uri but getting no results in passing the user pic
also for help here is the code which fetches user profile from Facebook and sets it into the navbar of Activity 1
public void setUserProfile(String jsondata) {
try {
response = new JSONObject(jsondata);
user_email.setText(response.get("email").toString());
user_name.setText(response.get("name").toString());
profile_pic_data = new JSONObject(response.get("picture").toString());
profile_pic_url = new JSONObject(profile_pic_data.getString("data"));
Picasso.with(this).load(profile_pic_url.getString("url"))
.into(user_picture);
} catch (Exception e) {
e.printStackTrace();
}
}
So please suggest me how can i get the image to activity 2.
Hello this is my code by which i get rid of this problem
In first Activity
Profile profile = Profile.getCurrentProfile();
Bundle mBundle = new Bundle();
mBundle.putParcelable("pic", profile);
Intent loginint = new Intent(MainActivity.this,DashBoard.class);
loginint.putExtra("email",email);
loginint.putExtras(mBundle);
startActivity(loginint);
finish();
And in Second Activity where u want to show that Image
Intent intent = getIntent();
Bundle mBundle =intent.getExtras();
Profile profile;
if (mBundle != null) {
profile = (Profile) mBundle.getParcelable("pic");
} else {
profile = Profile.getCurrentProfile();
}
Picasso.with(DashBoard.this)
.load(profile.getProfilePictureUri(400, 400).toString())
.into(mfbimage);
here mfbimage is object of ImageView where u want to show that Profile Picture.
profile_pic_url.getString("url") extract this value into a variable and pass it as your intent extra and then load it with a Picasso in your second activity like in your setUserProfile method.
EDIT.
So in your setUserProfile(String jsondata) method on this line Picasso.with(this).load(profile_pic_url.getString("url")).into(user_picture); in your load() method you're extracting an url string from a JSONObject by calling profile_pic_url.getString("url"). You can create a field from that statement via Right click -> Refactor -> Extract -> Field... And then call put it as extra to your intent by calling ridesameIntent.putExtra(EXTRA_MESSAGE_USERPIC, fieldNameThatYouExtracted);
Then in your second activity call
Picasso.with(this).load(userPicMessage).into(userPicMessage); instead of userdetail2.setImageURI(Uri.parse(userPicMessage));
After that you can learn how to simplify json deserialization using GSON library Leveraging the Gson Library
You can pass the image Bitmap through the intent to the second activity as it implements the Parcelable interface.
Bitmap profileBitmap = ((BitmapDrawable)user_picture.getDrawable()).getBitmap();
ridesameIntent.putExtra("profilePic", profileBitmap);
And on the other end :
Intent intent = getIntent();
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("profilePic");
I'm trying to write my first program, and am now learning and writing the part where I save general information and user information via SharedPreferences.
Used the documentation and wrote the first part for saving general information and everything worked great. I could write and read values perfectly.
I expanded to store user information in a second file, and it seems to write, but i always get the default value. If I switch to using the general information file instead of user file, it works.
I think I'm doing something wrong in how I am using GetSharedPreferences() where it is limiting me to using just 1 file like it says for GetPreferences().
The general settings I am storing in a file named "Data", and user settings I am saving in file User1, User2, etc for each user
Below is my code.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// If first time running app, create Guest user
int intNumOfUsers=Integer.valueOf(funcReadData("Data","INT","NumOfUsers"));
if (intNumOfUsers==0)
{
String strTest=funcReadData("User1","STR","User");
subWriteData("Data","INT","NumOfUsers","1");
subWriteData("User1","STR","Name","Guest");
subWriteData("User1","STR","Pass","Guest");
}
// Determine if user needs to login before continuing
if (Boolean.valueOf(funcReadData("Data", "BLN", "StayLoggedIn")))
{
subLoadMain();
finish();
}
}
In above onStart, when the app is run the first time, it reads from "Data" file to get value of intNumOfUsers and if 0, it creates a default one by changing intNUmOfUsers to 1, and then creating a guest User/Pass in "User1" file.
The value to "Data" file saves and can be read perfectly, but the value to "User1" doesn't seem to save since I only get default value when I read it.
I use below common procedure to read and write data so no mistake with differences in code for each case exists.
public void subWriteData(String strFile, String strType, String strKey, String strValue)
{
SharedPreferences prefs = getSharedPreferences(strFile, MODE_PRIVATE);
SharedPreferences.Editor editor=prefs.edit();
Log.d("WD","WRITE-"+strFile+"-"+strType+"-"+strKey+"-"+strValue);
switch (strType)
{
case "STR":
editor.putString(strKey, strValue);
break;
case "INT":
editor.putInt(strKey,Integer.valueOf(strValue));
break;
case "BLN":
editor.putBoolean(strKey,Boolean.valueOf(strValue));
break;
case "LNG":
editor.putLong(strKey,Long.valueOf(strValue));
break;
case "FLT":
editor.putFloat(strKey, Float.valueOf(strValue));
break;
}
editor.commit();
}
public String funcReadData(String strFile, String strType, String strKey) {
String strValue = "";
SharedPreferences prefs = getSharedPreferences("Data", MODE_PRIVATE);
switch (strType)
{
case "STR":
strValue = prefs.getString(strKey, "");
break;
case "INT":
strValue = String.valueOf(prefs.getInt(strKey, 0));
break;
case "BLN":
strValue = String.valueOf(prefs.getBoolean(strKey, false));
break;
case "LNG":
strValue = String.valueOf(prefs.getLong(strKey, 0));
break;
case "FLT":
strValue = String.valueOf(prefs.getFloat(strKey, 0));
break;
}
Log.d("WD","READ"+"-"+strFile+"-"+strType+"-"+strKey+"-"+strValue);
return strValue;
}
And below is just more code where I see if i can find user details and match against given information or create new user etc
public void subCreateLogin(View view)
{
Boolean boolUserFound=false;
Boolean boolUserLoggedIn=false;
int intNumOfUsers;
CheckBox chkStayLoggedIn = (CheckBox) findViewById(R.id.chkStayLoggedIn);
EditText txtUser = (EditText)findViewById(R.id.txtUser);
if (txtUser.getText().length()==0 )
{
Toast.makeText(Login.this, "Please enter a valid username", Toast.LENGTH_SHORT).show();
}
else
{
EditText txtPass = (EditText)findViewById(R.id.txtPass);
if (txtPass.getText().length()==0 )
{
Toast.makeText(Login.this, "Password field cannot be empty", Toast.LENGTH_SHORT).show();
}
else
{
intNumOfUsers=Integer.valueOf(funcReadData("Data","INT","NumOfUsers"));
if (intNumOfUsers>1)
{
int Lvar;
String txtData;
for (Lvar = 1; Lvar <= intNumOfUsers; Lvar++)
{
txtData = funcReadData(("User"+Lvar).toString(), "STR","Name");
if (txtData.toUpperCase().equals(txtUser.getText().toString().toUpperCase()))
{
boolUserFound=true;
txtData = funcReadData(("User"+Lvar).toString(), "STR", "Pass");
if (txtData.equals(txtPass.getText().toString()))
{
boolUserLoggedIn=true;
subWriteData("Data","STR","LastUser", txtUser.getText().toString());
if (chkStayLoggedIn.isChecked())
{
subWriteData("Data","BLN","StayLoggedIn","true");
}
}
else
{
Toast.makeText(Login.this, "Incorrect password. Please try again.", Toast.LENGTH_SHORT).show();
}
}
}
}
if (!boolUserFound)
{
// First new user, create his details
intNumOfUsers++;
subWriteData("Data","INT","NumOfUsers",String.valueOf(intNumOfUsers));
subWriteData(("User"+intNumOfUsers).toString(), "STR", "Name", txtUser.getText().toString());
subWriteData(("User"+intNumOfUsers).toString(),"STR","Pass",txtPass.getText().toString());
subWriteData("Data","STR","LastUser", txtUser.getText().toString());
//boolUserFound=true;
boolUserLoggedIn=true;
if (chkStayLoggedIn.isChecked())
{
subWriteData("Data","BLN","StayLoggedIn","true");
}
}
}
}
if (boolUserLoggedIn)
{
subLoadMain();
finish();
}
}
So anything that reads/write to "Data" is fine, but to "User1", "User2" etc never seems to work. How do I enable the ability to save multiple preferences files?
Thanks!
in your read data function while getting the shared prefs you have specified the file name as Data instead of passing in the file name while in writing you use the passed in filename.
I want to implement a search in my Android application.
In this page, first I am displaying a user list and then performing a search on the user list. Both are in the same activity. In the following manner, I am getting intent and some values from the previous page. When I display the user list, all the values are coming. But while performing search, spaceId gets lost and becomes null. I need this value.
Intent intent = this.getIntent();
Bundle receiveBundle = intent.getExtras();
spaceId = receiveBundle.getString("spaceId");
What should I do to get this value?
Edit:
String spaceId;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = this.getIntent();
Bundle receiveBundle = intent.getExtras();
spaceId = receiveBundle.getString("spaceId");
String URLTicketList = String.format(getString(R.string.URLTicketList, spaceId));
RestClient client = new RestClient(URLTicketList,
this.getApplicationContext());
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
TabSettings ts = new TabSettings();
ts.setSelTab(0);
String response = client.getResponse();
tickets = parseTicketList(response);
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
searchResult=getMatchingStrings(tickets,query);
this.ticket_adapter = new TicketAdapter(this,
R.layout.ticket_details_row,searchResult);
setListAdapter(this.ticket_adapter);
}
else {
this.ticket_adapter = new TicketAdapter(this,
R.layout.ticket_details_row, tickets);
setListAdapter(this.ticket_adapter);
}
}
getMatchingstrings()
ArrayList<Ticket> getMatchingStrings(ArrayList<Ticket> list, String regex1) {
ArrayList <Ticket> listClone = new ArrayList<Ticket>();
for (Ticket string : list) {
if(string.getAssignedTo().equals(regex1)){
listClone.add(string);
}
}
return listClone;
}
Try it
getIntent().getExtras().getString("spaceId");
You said your activity is recreating. So you are not getting the value of spaceID after recreation. Then do this thing as below.
public String PREFS_NAME = "Shared_Pref";
Bundle receiveBundle = this.getIntent().getExtras();
String spaceId_value = receiveBundle.getString("spaceId");
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
if(spaceId_value == null) {
spaceId_value = settings.getString("spaceId", "");
}
else {
SharedPreferences.Editor editor = settings.edit();
editor.putString("spaceId", spaceId_value);
}
I hope this will help you out.
edit :
I am editing your code.
Which part i have edited, i have mentioned that part as edited. Carefully see what i have changed and do that thing in your code. Then let me know.
String spaceId;
public String PREFS_NAME = "Shared_Pref"; //edited part
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//editing start
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
Bundle receiveBundle = this.getIntent().getExtras();
if(receiveBundle != null) {
spaceId = receiveBundle.getString("spaceId");
if(spaceId == null) {
spaceId = settings.getString("spaceId", "");
}
else {
SharedPreferences.Editor editor = settings.edit();
editor.putString("spaceId", spaceId);
}
}
//editing end
String URLTicketList = String.format(getString(R.string.URLTicketList, spaceId));
RestClient client = new RestClient(URLTicketList,
this.getApplicationContext());
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
TabSettings ts = new TabSettings();
ts.setSelTab(0);
String response = client.getResponse();
tickets = parseTicketList(response);
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
searchResult=getMatchingStrings(tickets,query);
this.ticket_adapter = new TicketAdapter(this,
R.layout.ticket_details_row,searchResult);
setListAdapter(this.ticket_adapter);
}
else {
this.ticket_adapter = new TicketAdapter(this,
R.layout.ticket_details_row, tickets);
setListAdapter(this.ticket_adapter);
}
}
When you are firstly loading your list in activity,you have to save that spaceId in some SharedPreference variable for further use.And while reloading activity with search result,you can find that Id from SharedPreference variable previously saved.
Be sure,you overwrite that variable as and when you firstly load list in your activity to meet your needs cleanly.
Also you have to get spaceId from intent like:
int spaceId=0;
if(getIntent().hasExtra())
spaceId=getIntent().getStringExtra("spaceId");
Doing this wont give you excpetion when you reload the same activity with no extras to your intent.
Or,you will have to pass this spaceId along with intent you are using to reload the same activity for showing search result.
Hope,you get the point!
If u relaunching the same activity while performing search,u will lost that value. If u r doing so,while relaunching also pass that spaceId to the relaunching activity also using intent.putextra() method
as in your question and comments i guess you are getting problem if your activity is recreated
add following code in manifest file under your activity tag
android:configChanges="keyboardHidden|orientation"
your activity will not be created again
and then use the value of spaceID where you need
in my app i have two editbox in which the user types the email and password. The values are send to an URL and if the return values is success i am moving to a new activity, else if the return value is Email And Password Not Match! i want to show an alert box that emailand pwd mismatches.
For this, after getting the xml file from the network using sax parser i am doing parsing the and if the return value is "Email And Password Not Match!", i am storing this in a constant names as ERROR_VALUE.
i have already stored the value in a String constant as follows
public static String ERROR_CONST = "Email And Password Not Match!";
now i am comparing those values and showing an alert box,
if (ERROR_CONST.contentEquals(ERROR_VALUE))
{
alertbox();
}
after this i am using the else part to move to a new activity, my app gets crashed at this part only
else if(ERROR_VALUE == null)
{
Intent myIntent = new Intent(getBaseContext(), Add.class);
startActivityForResult(myIntent, 0);
finish();
}
}
how to use else condition successfully in my app, please help me friends
Well when comparing 2 strings its always a good idea to use
s1.compareToIgnoreCase(s2);
reading your post I would suggest you use enum or constants
public static final ERROR_CODE_INVALIDE_LOGGIN = 1;
to compare rather that strings.
Comparing strings is tedious (have to be careful that your comparing the characters and not references etc.). As comparing 2 int is easy and takes less time
I checked quickly in the javaDoc
contentEquals compares your String to a StringBuffer
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#contentEquals(java.lang.StringBuffer)
as
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#compareTo(java.lang.String)
Compares the actual string letters
other edit (sorry about that)
if your code is
if (ERROR_CONST.contentEquals(ERROR_VALUE))
{
alertbox();
}
else if(ERROR_VALUE == null)
{
Intent myIntent = new Intent(getBaseContext(), Add.class);
startActivityForResult(myIntent, 0);
finish();
}
then you have a problem when ERROR_VALUE is == null.
you pass null in contentequals and I'm guessing Java tries to convert null to StringBuffer and crashes.
what you want to do it
if(ERROR_VALUE == null)
{
Intent myIntent = new Intent(getBaseContext(), Add.class);
startActivityForResult(myIntent, 0);
finish();
}else if (ERROR_CONST. equalsIgnoreCase(ERROR_VALUE))
{
alertbox();
}
this way you avoid any null pointer exceptions and your compare will work just fine