how do I pass an u_id value to another activity? - java

Here is my main file where i get u_id and other data but i pass u_id text to other activity
Mainactivity.java
package com.desktop.app;
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.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.desktop.app.Stitle.EXTRA_TITLE;
public class MainActivity extends AppCompatActivity {
Button signup,login,learnmore ;
EditText ed1,ed2,u_id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signup = (Button) findViewById(R.id.signupbutton);
learnmore = (Button) findViewById(R.id.learnmore);
login = (Button) findViewById(R.id.loginbutton);
ed1 = (EditText) findViewById(R.id.emailedittext);
u_id = (EditText) findViewById(R.id.uid);
ed2 = (EditText) findViewById(R.id.passwordedittext);
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent in = new Intent(MainActivity.this,Activity2.class);
startActivity(in);
}
});
learnmore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent in = new Intent(MainActivity.this,Activity1.class);
startActivity(in);
}
});
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = ed1.getText().toString().trim();
String password = ed2.getText().toString().trim();
final String log_id = u_id.getText().toString();
if(email.isEmpty()){
ed1.setError("Fill this field");
ed1.requestFocus();
return;
}
if(password.isEmpty()){
ed2.setError("Fill this field");
ed2.requestFocus();
return;
}
if(log_id.isEmpty()){
u_id.setError("Fill this field");
u_id.requestFocus();
return;
}
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
login();
Intent i = new Intent (MainActivity.this,fullview.class);
Bundle b =new Bundle();
b.putString("text", String.valueOf(u_id));
i.putExtras(b);
startActivity(i);
}
});
}
private void login(){
String url= "http://192.168.0.136/fyp/andr_log.php";
final RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.trim().equals("Login Successfull")){
Toast.makeText(getApplicationContext(), "Login Successfull",Toast.LENGTH_LONG).show();
Intent in = new Intent(MainActivity.this,Search.class);
startActivity(in);
}
else {
Toast.makeText(getApplicationContext(), "Login Unsuccessfull",Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "error:" +error.toString() ,Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Email", ed1.getText().toString().trim() );
params.put("uid", u_id.getText().toString().trim() );
params.put("Password", ed2.getText().toString().trim() );
return params;
}
};
requestQueue.add(stringRequest);
}});
}
}
fullview.java
package com.desktop.app;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static android.support.v7.app.AlertDialog.*;
import static com.desktop.app.Stitle.EXTRA_AUTHOR;
import static com.desktop.app.Stitle.EXTRA_HR;
import static com.desktop.app.Stitle.EXTRA_PUBLISHER;
import static com.desktop.app.Stitle.EXTRA_PUBY;
import static com.desktop.app.Stitle.EXTRA_ACC;
import static com.desktop.app.Stitle.EXTRA_RAK;
import static com.desktop.app.Stitle.EXTRA_STATUS;
import static com.desktop.app.Stitle.EXTRA_TITLE;
import static com.desktop.app.Stitle.EXTRA_VR;
public class fullview extends AppCompatActivity {
Button location, avail, request;
TextView textviewtitle, textviewauthors, textviewpublisher, textviewpubyear,textviewacc,u_id;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fullview);
Intent intent = getIntent();
Bundle b = getIntent().getExtras();
String id= b.getString("text");
u_id= findViewById(R.id.uid);
String title = intent.getStringExtra(EXTRA_TITLE);
String author = intent.getStringExtra(EXTRA_AUTHOR);
String publisher = intent.getStringExtra(EXTRA_PUBLISHER);
int puby = intent.getIntExtra(EXTRA_PUBY,0);
int accc = intent.getIntExtra(EXTRA_ACC,0);
final int rak = intent.getIntExtra(EXTRA_RAK,0);
final int hr = intent.getIntExtra(EXTRA_HR,0);
final int vr = intent.getIntExtra(EXTRA_VR,0);
final String status = intent.getStringExtra(EXTRA_STATUS);
textviewtitle = findViewById(R.id.textviewtitle);
textviewauthors = findViewById(R.id.textviewauthors);
textviewpublisher = findViewById(R.id.textviewpublisher);
textviewpubyear = findViewById(R.id.textviewpubyear);
textviewacc = findViewById(R.id.textviewacc);
textviewtitle.setText(title);
textviewauthors.setText(author);
textviewpublisher.setText(publisher);
textviewpubyear.setText(String.valueOf(puby));
textviewacc.setText(String.valueOf(accc));
location = findViewById(R.id.loc);
location.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
{
AlertDialog.Builder builder=new AlertDialog.Builder(fullview.this);
builder.setTitle("Location");
builder.setMessage("Rak-No :: " + rak + "\nColumn :: " + hr +"\nRow :: " + vr);
AlertDialog alertDialog=null;
builder.setPositiveButton("Close", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(fullview.this,"Closed",Toast.LENGTH_SHORT).show();
}
});
alertDialog=builder.create();
alertDialog.show();
}
}
});
avail = findViewById(R.id.avail);
avail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
AlertDialog.Builder builder=new AlertDialog.Builder(fullview.this);
{
if (status.equals("yes")) {
builder.setTitle("Availablity");
builder.setMessage("Available");
} else {
builder.setTitle("Availablity");
builder.setMessage("Not Available");
}
}
AlertDialog alertDialog=null;
builder.setPositiveButton("Close", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(fullview.this,"Closed",Toast.LENGTH_SHORT).show();
}
});
alertDialog=builder.create();
alertDialog.show();
}
});
request= findViewById(R.id.request);
request.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
request();
}
});
}
private void request(){
String url= "http://192.168.0.136/fyp/bookreq.php";
final RequestQueue requestQueue = Volley.newRequestQueue(fullview.this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.trim().equals("successfull")){
Toast.makeText(getApplicationContext(), "Go to Admin For Approval",Toast.LENGTH_LONG).show();
Intent in = new Intent(fullview.this,Search.class);
startActivity(in);
}
else {
Toast.makeText(getApplicationContext(), "Already Requested",Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "error:" +error.toString() ,Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Title", textviewtitle.getText().toString().trim());
params.put("Author", textviewauthors.getText().toString().trim());
params.put("Publisher", textviewpublisher.getText().toString().trim());
params.put("Acc", textviewacc.getText().toString().trim());
params.put("Puby", textviewpubyear.getText().toString().trim());
Log.i("Info",textviewtitle.getText().toString().trim());
return params;
}
};
requestQueue.add(stringRequest);
}
}
Here is my second file above where i want to shoe u_id text but i done with this to pass u_id text to other activity
Intent i = new Intent (MainActivity.this,fullview.class);
Bundle b =new Bundle();
b.putString("text", String.valueOf(u_id));
i.putExtras(b);
startActivity(i);
this code i use to pass u_id text and next activity code i use below code
Bundle b = getIntent().getExtras();
String id= b.getString("text");
u_id= findViewById(R.id.uid);

This is what your problem is.
Intent i = new Intent (MainActivity.this,fullview.class);
Bundle b =new Bundle();
b.putString("text", String.valueOf(u_id));
i.putExtras(b);
startActivity(i);
Change this line
b.putString("text", String.valueOf(u_id));
to
b.putString("text", u_id.getText().toString().trim());
EDIT:
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email = ed1.getText().toString().trim();
String password = ed2.getText().toString().trim();
final String log_id = u_id.getText().toString();
if(email.isEmpty()){
ed1.setError("Fill this field");
ed1.requestFocus();
}else if(password.isEmpty()){
ed2.setError("Fill this field");
ed2.requestFocus();
} else if(log_id.isEmpty()){
u_id.setError("Fill this field");
u_id.requestFocus();
} else {
login();
Intent i = new Intent(MainActivity.this,fullview.class);
Bundle b =new Bundle();
b.putString("text", u_id.getText().toString().trim());
i.putExtras(b);
startActivity(i);
}
}

Related

android studio com.android.volley.clienterror

its giving me a error that is called com.android.volley.clienterror
whenever i press the register or login button. I imagine that the
error could be that my android app isnt connected to my database but
idk.................................................................................................................................................................................................................
import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.Map;
public class register extends AppCompatActivity {
private EditText etName, etEmail, etPassword, etReenterPassword;
private TextView tvStatus;
private Button btnRegister;
private String URL = "http://10.0.2.2/login.register.php";
private String name, email, password, reenterPassword;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
etName = findViewById(R.id.etName);
etEmail = findViewById(R.id.etEmail);
etPassword = findViewById(R.id.etPassword);
etReenterPassword = findViewById(R.id.etReenterPassword);
tvStatus = findViewById(R.id.tvStatus);
btnRegister = findViewById(R.id.btnRegister);
name = email = password = reenterPassword = "";
}
public void save(View view){
name = etName.getText().toString().trim();
email = etEmail.getText().toString().trim();
password = etPassword.getText().toString().trim();
reenterPassword = etReenterPassword.getText().toString().trim();
if(!password.equals(reenterPassword)){
Toast.makeText(this , "Password mismatch", Toast.LENGTH_SHORT).show();
}
else if(!name.equals("")&& !email.equals("") && !password.equals("")){
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if (response.equals("success")) {
tvStatus.setText("Successfully registered");
btnRegister.setClickable(false);
} else if (response.equals("failure")) {
tvStatus.setText("something went wrong!");
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.toString().trim(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> data = new HashMap<>();
data.put("name", name);
data.put("email", email);
data.put("password", password);
return data;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
}
public void login(View view){
Intent intent = new Intent (this, MainActivity.class);
startActivity(intent);
finish();
}
}

Activity opening itself [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am creating a chat app. users can change their info. after making a new account, they have to create their profile. the profile activity restarts itself again and again. can I fix it or It is an Android problem
I have tried everything at here!
settingsActivity.java:
package com.satyamedh.chitchatmessenger;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Objects;
import de.hdodenhof.circleimageview.CircleImageView;
public class SettingsActivity extends AppCompatActivity {
private Button Updatebutton;
private EditText Username, Status;
private CircleImageView profileImage;
private String currentUID;
private DatabaseReference rootref;
private StorageReference ProfileImagesRef;
private String downloadUrl;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{
final CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK)
{
Uri resultUri = result.getUri();
final StorageReference ref = ProfileImagesRef.child(currentUID + ".jpg");
ref.putFile(resultUri)
.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri)
{
Toast.makeText(SettingsActivity.this, uri.toString(), Toast.LENGTH_SHORT).show();
downloadUrl = uri.toString();
rootref.child("Users").child(currentUID).child("image")
.setValue(downloadUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if(task.isSuccessful())
{
Toast.makeText(SettingsActivity.this, "Profile Image Uploaded Successfully...", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(SettingsActivity.this, "Some error has occurred, please try again later...", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
});
}
}
}
private void getUserInfo()
{
rootref.child("Users").child(currentUID)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String oldImage;
if(dataSnapshot.hasChild("name") && (dataSnapshot.hasChild("status"))) {
String oldUsername = dataSnapshot.child("name").getValue().toString();
String oldStatus = dataSnapshot.child("status").getValue().toString();
Username.setText(oldUsername);
Status.setText(oldStatus);
}
if (dataSnapshot.hasChild("image"))
{
oldImage = dataSnapshot.child("image").getValue().toString();
Picasso.get().load(oldImage).placeholder(R.drawable.profile_image).into(profileImage);
}
Toast.makeText(SettingsActivity.this, "Please update your profile", Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void updateSettings()
{
String setUserName = Username.getText().toString();
String setStatus = Status.getText().toString();
if (TextUtils.isEmpty(setUserName))
{
Toast.makeText(this, "Please enter Username to continue", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(setStatus))
{
Toast.makeText(this, "Please enter Status to continue", Toast.LENGTH_SHORT).show();
}
else
{
HashMap<String, String> profileMap = new HashMap<>();
profileMap.put("uid", currentUID);
profileMap.put("name", setUserName);
profileMap.put("status", setStatus);
rootref.child("Users").child(currentUID).setValue(profileMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful())
{
Toast.makeText(SettingsActivity.this, "Profile updated successfully", Toast.LENGTH_SHORT).show();
askUserToUseApp();
}
else
{
String messegess = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error : " + messegess, Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
protected void onStart() {
super.onStart();
FirebaseAuth mAuth = FirebaseAuth.getInstance();
currentUID = Objects.requireNonNull(mAuth.getCurrentUser()).getUid();
rootref = FirebaseDatabase.getInstance().getReference();
ProfileImagesRef = FirebaseStorage.getInstance().getReference().child("Profile images");
initializeFields();
Updatebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
updateSettings();
}
});
getUserInfo();
profileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.start(SettingsActivity.this);
}
});
updateUserStatus("online");
}
private void initializeFields()
{
Updatebutton = findViewById(R.id.update_settings);
Username = findViewById(R.id.set_user_name);
Status = findViewById(R.id.set_status);
profileImage = findViewById(R.id.set_profile_image);
}
private void askUserToUseApp() {
Intent loginIntent = new Intent(SettingsActivity.this, MainActivity.class);
loginIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
#Override
protected void onStop()
{
super.onStop();
updateUserStatus("offline");
}
#Override
protected void onDestroy()
{
super.onDestroy();
updateUserStatus("offline");
}
private void updateUserStatus(String state)
{
Calendar calForDate = Calendar.getInstance();
#SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMM, yyyy");
String currentDate = simpleDateFormat.format(calForDate.getTime());
Calendar calForTime = Calendar.getInstance();
#SuppressLint("SimpleDateFormat") SimpleDateFormat simpleTimeFormat = new SimpleDateFormat("hh:mm:ss a");
String currentTime = simpleTimeFormat.format(calForTime.getTime());
HashMap<String, Object> onlineState = new HashMap<>();
onlineState.put("time", currentTime);
onlineState.put("date", currentDate);
onlineState.put("state", state);
rootref.child("Users").child(currentUID).child("userState")
.updateChildren(onlineState);
}
}
there are no errors. but I can stop it by uninstalling it using ADB
Edit: it works fine after I edit it manually edit in firebase and then open that activity from the main activity.
Edit2:
registerActivity.java
package com.satyamedh.chitchatmessenger;
import android.app.ProgressDialog;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;
public class ResigsterActivity extends AppCompatActivity {
private Button registerButton;
private EditText userEmail, userPassword;
private TextView loginactivityLink;
private FirebaseAuth mAuth;
private DatabaseReference rootref;
private ProgressDialog loading_bar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_resigster);
FirebaseApp.initializeApp(this);
mAuth = FirebaseAuth.getInstance();
rootref = FirebaseDatabase.getInstance().getReference();
MobileAds.initialize(this, "ca-app-pub-3127817354023186~6842500243");
final AdView mAdView;
mAdView = findViewById(R.id.register_banner_ad);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
mAdView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
// Code to be executed when an ad finishes loading.
}
#Override
public void onAdFailedToLoad(int errorCode) {
// Code to be executed when an ad request fails.
}
#Override
public void onAdOpened() {
// Code to be executed when an ad opens an overlay that
// covers the screen.
}
#Override
public void onAdClicked() {
// Code to be executed when the user clicks on an ad.
}
#Override
public void onAdLeftApplication() {
// Code to be executed when the user has left the app.
}
#Override
public void onAdClosed() {
// Code to be executed when the user is about to return
// to the app after tapping on an ad.
}
});
initializeFields();
loginactivityLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
askUserToLogin();
}
});
registerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
createAccount();
}
});
}
private void createAccount()
{
final String email = userEmail.getText().toString();
final String password = userPassword.getText().toString();
if (TextUtils.isEmpty(email))
{
Toast.makeText(this, "Please enter Email...", Toast.LENGTH_SHORT).show();
}
if (TextUtils.isEmpty(password))
{
Toast.makeText(this, "Please enter Password...", Toast.LENGTH_SHORT).show();
}
else
{
loading_bar.setTitle("Creating new account");
loading_bar.setMessage("Please wait...");
loading_bar.setCanceledOnTouchOutside(true);
loading_bar.show();
mAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful())
{
final String currentUserID = mAuth.getCurrentUser().getUid();
rootref.child("Users").child(currentUserID).setValue("");
final String[] deviceToken = new String[1];
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() {
#Override
public void onSuccess(InstanceIdResult instanceIdResult) {
deviceToken[0] = instanceIdResult.getToken();
// Do whatever you want with your token now
// i.e. store it on SharedPreferences or DB
// or directly send it to server
rootref.child("Users").child(currentUserID).child("device_token").setValue(deviceToken[0]).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if (task.isSuccessful())
{
Toast.makeText(ResigsterActivity.this, "Account created successfully...", Toast.LENGTH_SHORT).show();
loading_bar.dismiss();
mAuth.signInWithEmailAndPassword(email, password);
askUserToMain();
}
}
});
rootref.child("Users").child(currentUserID).child("image").setValue("https://firebasestorage.googleapis.com/v0/b/chit-chat-web-chat.appspot.com/o/profile_image.png?alt=media&token=12bc53c2-c27d-420f-9d5f-f84c22a6449c");
rootref.child("Users").child(currentUserID).child("name").setValue("Enter your name here");
rootref.child("Users").child(currentUserID).child("status").setValue("Enter your status here");
}
});
}
else
{
String messegess = task.getException().toString();
Toast.makeText(ResigsterActivity.this, "Error : " + messegess, Toast.LENGTH_SHORT).show();
loading_bar.dismiss();
}
}
});
}
}
private void initializeFields()
{
registerButton = (Button) findViewById(R.id.register_button);
userEmail = (EditText) findViewById(R.id.register_email);
userPassword = (EditText) findViewById(R.id.register_password);
loginactivityLink = (TextView) findViewById(R.id.register_sign_in);
loading_bar = new ProgressDialog(this);
}
private void askUserToLogin() {
Intent loginIntent = new Intent(ResigsterActivity.this, LoginActivity.class);
loginIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
private void askUserToMain() {
Intent mainIntent = new Intent(ResigsterActivity.this, ProfileActivity.class);
mainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(mainIntent);
finish();
}
private void askUserToUseApp() {
Intent loginIntent = new Intent(ResigsterActivity.this, LoginActivity.class);
loginIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
}
Might be not related answer but whenever you are using any firebase or firestore
event try to pass "this("activity context")" as the first parameter it will manage the
activity life cycle and will remove you listener when your app will be in background.

How to pass data from one activity to another activity

I'm creating an event app which contains a list of events in recyclerview.
The events recyclerview consists of the event name, image, date and time, heart image (example: heart shape like button on Instagram) which will change its color when the user clicks on the 'interested' button.
After clicking on any event its description appears and there are two buttons: 'interested' and 'going'. If the user clicks on 'interested' that heart color in the recyclerview will become yellow. The event will also get saved in another list where it will remain until that event is removed from the saved list.
So far I've completed saving that event in the saved list on clicking the 'interested' button. But I don't know how to change the heart color simultaneously and how to make it remain until the event is deleted from saved list.
First Activity calling recyclerview adapter
import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class EventActivity extends AppCompatActivity {
//this is the JSON Data URL
//make sure you are using the correct ip else it will not work
private static final String URL_PRODUCTS = "https://www.test.magicalballoons.co.in/priyanka/event.php?";
//a list to store all the products
List<Product> productList;
//the recyclerview
RecyclerView recyclerView;
ImageView homemenu;
//SwipeRefreshLayout swiper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event);
getSupportActionBar().hide();
homemenu = findViewById(R.id.homemenu);
// swiper = findViewById(R.id.swiper);
//getting the recyclerview from xml
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//initializing the productlist
productList = new ArrayList<>();
homemenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(EventActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
});
//this method will fetch and parse json
//to display it in recyclerview
loadProducts();
}
private void loadProducts() {
/*
* Creating a String Request
* The request type is GET defined by first parameter
* The URL is defined in the second parameter
* Then we have a Response Listener and a Error Listener
* In response listener we will get the JSON response as a String
* */
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_PRODUCTS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONArray array = new JSONArray(response);
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting product object from json array
JSONObject product = array.getJSONObject(i);
//adding the product to product list
productList.add(new Product(
product.getString("id"),
product.getString("name"),
product.getString("date"),
product.getString("location"),
product.getString("image"),
product.getString("details")
));
}
//creating adapter object and setting it to recyclerview
RecyclerViewAdapter adapter = new RecyclerViewAdapter(EventActivity.this, productList);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(EventActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
}
public void onBackPressed() {
Intent intent = new Intent(EventActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
}
Recyclerview Adapter
import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.BreakIterator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import static com.example.priyankaregistration.URLs.URL_EVENT;
/**
* Created by Aws on 11/03/2018.
*/
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
private RequestQueue requestQueue;
private JsonArrayRequest request;
private Context mContext;
private List<Product> mData;
RequestOptions option;
TextView total;
ImageView colorheart,heart;
// Dialog myDailog;
private Dialog myDialog;
public RecyclerViewAdapter(Context mContext, List<Product> mData) {
this.mContext = mContext;
this.mData = mData;
//this.swiper = swiper;
option=new RequestOptions().fitCenter().placeholder(R.drawable.background).error(R.drawable.background);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
LayoutInflater inflater = LayoutInflater.from(mContext);
view = inflater.inflate(R.layout.fragment_conferences, parent, false);
final MyViewHolder viewHolder = new MyViewHolder(view);
myDialog = new Dialog(mContext);
colorheart = (ImageView) view.findViewById(R.id.colorheart);
heart = (ImageView) view.findViewById(R.id.heart);
total = (TextView) view.findViewById(R.id.count);
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_COUNT,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
total.setText(jsonObject.getString("countid"));
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("eventid", mData.get(viewHolder.getAdapterPosition()).getId());
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(mContext);
requestQueue.add(stringRequest);
viewHolder.view_container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, Description.class);
intent.putExtra("eventname",mData.get(viewHolder.getAdapterPosition()).getName());
intent.putExtra("eventid",mData.get(viewHolder.getAdapterPosition()).getId());
intent.putExtra("eventdate",mData.get(viewHolder.getAdapterPosition()).getDate());
intent.putExtra("eventloc",mData.get(viewHolder.getAdapterPosition()).getLocation());
intent.putExtra("eventimg",mData.get(viewHolder.getAdapterPosition()).getImage());
intent.putExtra("details",mData.get(viewHolder.getAdapterPosition()).getDetails());
mContext.startActivity(intent);
}
});
return viewHolder;
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
holder.textViewName.setText(mData.get(position).getName());
holder.textViewDate.setText("Date : " + mData.get(position).getDate());
holder.textViewLocation.setText("Time : " + mData.get(position).getLocation());
Glide.with(mContext).load(mData.get(position).getImage()).apply(option).into(holder.img_thumbnail);
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView textViewName,textViewDate, textViewLocation,total;
ImageView img_thumbnail;
//LinearLayout view_container;
CardView view_container;
public MyViewHolder(View itemView) {
super(itemView);
view_container = itemView.findViewById(R.id.container);
textViewName = itemView.findViewById(R.id.textViewName);
textViewDate = itemView.findViewById(R.id.textViewDate);
textViewLocation = itemView.findViewById(R.id.textViewLocation);
total = itemView.findViewById(R.id.count);
img_thumbnail=itemView.findViewById(R.id.imageView);
}
}
}
This is second activity
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.support.design.widget.Snackbar;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class Description extends AppCompatActivity {
TextView textViewName,textViewDate, textViewLocation, details;
ImageView evimg,going,interest;
RequestOptions option;
ImageView homemenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details);
getSupportActionBar().hide();
option=new RequestOptions().fitCenter().placeholder(R.drawable.background).error(R.drawable.background);
textViewName = findViewById(R.id.textViewName);
evimg = findViewById(R.id.evimg);
details = findViewById(R.id.details);
going = findViewById(R.id.going);
interest = findViewById(R.id.interest);
homemenu = findViewById(R.id.homemenu);
textViewName.setText(getIntent().getStringExtra("eventname"));
//textViewDate.setText(getIntent().getStringExtra("eventdate"));
//textViewLocation.setText(getIntent().getStringExtra("eventloc"));
details.setText(getIntent().getStringExtra("details"));
details.setMovementMethod(new ScrollingMovementMethod());
Glide.with(this).load(getIntent().getStringExtra("eventimg")).apply(option).into(evimg);
going.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringRequest stringRequest = new StringRequest(Request.Method.GET, URLs.URL_EVENT+"?userid=" + SharedPrefManager.getInstance(getApplicationContext()).getUserId() + "&eventid="+ getIntent().getStringExtra("eventid"),
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String message = jsonObject.getString("name");
Intent intent = new Intent(Description.this,Ticket.class);
intent.putExtra("code",message);
intent.putExtra("eventimg",getIntent().getStringExtra("eventimg"));
intent.putExtra("activity","NO");
// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
jsonrequest();
startActivity(intent);
finish();
//Toast.makeText(mContext,message,Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
//params.put("userid",SharedPrefManager.getInstance(getApplicationContext()).getUserId());
//params.put("eventid",getIntent().getStringExtra("eventid"));
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
});
interest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_EVENTSAVED ,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
//String message = jsonObject.getString("name")
Toast.makeText(getApplicationContext(),jsonObject.getString("message"),Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("userid",SharedPrefManager.getInstance(getApplicationContext()).getUserId());
params.put("eventid",getIntent().getStringExtra("eventid"));
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
});
homemenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Description.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
});
}
private void jsonrequest() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_EVENTDELETED,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//progressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(response);
Toast.makeText(getApplicationContext(),jsonObject.getString("Event removed from saved list"),Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
//progressDialog.dismiss();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("userid",SharedPrefManager.getInstance(getApplicationContext()).getUserId());
params.put("eventid",getIntent().getStringExtra("eventid"));
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
requestQueue.add(stringRequest);
}
}
I'm having heart image in my recyclerview . And when i click on interest buttton in Description activity the heart image in recyclerview get change.
Assuming you are saving the events in some model class, what you can do is when calling the onBindViewHolder method of your adapter, check if the event is marked as save. If it is, then you either need to change the heart image to another heart image which is yellow, or you can apply a tint on the heart image to make it yellow.
You can change drawable by using this code
heartImageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.yellow_heart));
You can apply tint by using this code
heartImageView.setColorFilter(Color.argb(255, 255, 255, 0))
EDIT (Based on comment)
If the heart is in the first activity and the interested button is in the second activity what you need to do is to save the state of the event when you click on the interested button. Once you go back to the the first activity, you can check the state of the event and then update the image by using any of the above two methods.
EDIT 2 (Based on new code shared)
After you get the response from your Volley call, you should save the event id somewhere to keep track of which events you are interested in (this can be in either a model class or some global list). When you go back to your first activity (which contains the recyclerview), you need to check each event id with the stored event id list that you have and change the heart for each event that matches.
You can do this with the help for startActivityforresult
In Activity1, start Activity2 as:
Intent i = new Intent(this, Activity2.class);
startActivityForResult(i, 1);
In Activity2, use setResult for sending data back:
Intent intent = new Intent();
intent.putExtra("updatedArraylist", "arraylist")
setResult(RESULT_OK, intent);
finish();
And in Activity1, receive data with onActivityResult:
public void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK) {
String strArrayList =
data.getStringExtra("updatedArraylist");
Gson gson = new Gson();
Type youListType = new TypeToken<List<Model>>() {
}.getType();
List<Model> yourTypeList = gson.fromJson(strArrayList,
yourListType);
ArrayList finalArraylist = new ArrayList<>(yourTypeList);
yourArraylist.addAll(finalArraylist);
youtAdapter.notifyDataSetChanged();
}
}
}
You can apply color onclick event to heart button like following code :
your_image_id.setBackgroundColor(getResources().getColor(R.color.yellow));
In first activity
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivityForResult(intent, 100);
From second activity, you have to execute the below code before the activity getting destroyed by finish() or back press (For this you can override onBackPressed of second activity and remove the super class call and call the below method).
private void exitWithResult(){
Intent returnIntent = new Intent();
returnIntent.putExtra("result", "Id of selected item");
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
Again in first activity you have to handle the result inside onActivityResult method.
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == 100) {
if(resultCode == Activity.RESULT_OK){
String result=data.getStringExtra("result");
Log.e("DATA", "" + result);
}
if (resultCode == Activity.RESULT_CANCELED) {
//Write your code if there's no result
Log.e("DATA", "No result");
}
}
}
Update
You can use an interface as callback from adapter to activity. startActivityForResult canbe called inside the callback method of interface. You have to pass callback interface to adapter through adapter constructor along with data set.
declare this interface inside adapter
public interface AdapterCallback{
void onAdapterSelected(int pos);
}
And in first activity implement the interface like this.
MyAdapter.AdapterCallback callback = new MyAdapter.AdapterCallback() {
#Override
public void onAdapterSelected(int pos) {
Intent intent = new Intent(getApplicationContext(),
SecondActivity.class);
startActivityForResult(intent, 100);
}
};
Then set adapter like this.
RecyclerView rv = findViewById(R.id.rv_list);
rv.setHasFixedSize(true);
rv.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
MyAdapter adapter = new MyAdapter(callback); //This is the only change
rv.setAdapter(adapter);
Changes in adapter below. (You should pass list data along with call back as you already does)
private AdapterCallback callback;
public MyAdapter(AdapterCallback callback) {
this.callback = callback;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, final int i) {
viewHolder.mBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callback.onAdapterSelected(i);
}
});
}
Interface also come inside adapter. I am not repeating it here as i already mentioned at first

Firebase not uploading files to Storage Bucket

I am creating a chat app in which Users can create groups. when a users creates a group, he/she can choose a group profile image. but if i choose the image, it wont upload. what to do?
I have inspected the code, there is no error anywhere
CreateGroupActivity.java:
package com.satyamedh.chitchatmessenger;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.theartofdev.edmodo.cropper.CropImage;
import com.theartofdev.edmodo.cropper.CropImageView;
import de.hdodenhof.circleimageview.CircleImageView;
public class CreateGroupActivity extends AppCompatActivity
{
private CircleImageView circleImageView;
private EditText editText;
private Button buttonconf, buttoncanc;
private Uri resultUri;
private final static int chosenProfileImage = 1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_group);
initializeFields();
buttoncanc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent profileIntent = new Intent(CreateGroupActivity.this, MainActivity.class);
startActivity(profileIntent);
}
});
buttonconf.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(editText.getText())){
Toast.makeText(CreateGroupActivity.this, "Please enter text..", Toast.LENGTH_SHORT).show();
}
else
{
DatabaseReference rootref = FirebaseDatabase.getInstance().getReference();
Intent settingsIntent = new Intent(CreateGroupActivity.this, chooseUserActivity.class);
String key = rootref.push().getKey();
settingsIntent.putExtra("groupKey", key);
settingsIntent.putExtra("groupImage", resultUri);
settingsIntent.putExtra("groupName", editText.getText().toString());
startActivity(settingsIntent);
}
}
});
circleImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, chosenProfileImage);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == chosenProfileImage && resultCode == RESULT_OK && data != null)
{
Uri imageUri = data.getData();
CropImage
.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{
final CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(resultCode == RESULT_OK) {
resultUri = result.getUri();
circleImageView.setImageURI(resultUri);
}
}
}
private void initializeFields()
{
MobileAds.initialize(this, "ca-app-pub-3127817354023186~6842500243");
final AdView mAdView;
mAdView = findViewById(R.id.my_adView_createGroup);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
mAdView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
// Code to be executed when an ad finishes loading.
}
#Override
public void onAdFailedToLoad(int errorCode) {
// Code to be executed when an ad request fails.
}
#Override
public void onAdOpened() {
// Code to be executed when an ad opens an overlay that
// covers the screen.
}
#Override
public void onAdClicked() {
// Code to be executed when the user clicks on an ad.
}
#Override
public void onAdLeftApplication() {
// Code to be executed when the user has left the app.
}
#Override
public void onAdClosed() {
// Code to be executed when the user is about to return
// to the app after tapping on an ad.
}
});
circleImageView = findViewById(R.id.create_group_image);
editText = findViewById(R.id.create_group_name);
buttonconf = findViewById(R.id.confirm_button);
buttoncanc = findViewById(R.id.cancel_button);
}
}
chooseUserActivity.java:
package com.satyamedh.chitchatmessenger;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import com.squareup.picasso.Picasso;
import java.util.HashMap;
import java.util.Objects;
import de.hdodenhof.circleimageview.CircleImageView;
/**
* A simple {#link Fragment} subclass.
*/
public class chooseUserActivity extends AppCompatActivity {
private RecyclerView myRecyclerList;
private DatabaseReference ContactsRef, UsersRef;
private String currentUID;
private DatabaseReference groupsRef;
private Button confirmButton;
private String downloadUrl ;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_choose_user);
super.onCreate(savedInstanceState);
initializeFields();
}
private void initializeFields()
{
myRecyclerList = findViewById(R.id.users_choser_group);
myRecyclerList.setLayoutManager(new LinearLayoutManager(chooseUserActivity.this));
FirebaseAuth mAuth = FirebaseAuth.getInstance();
currentUID = mAuth.getCurrentUser().getUid();
ContactsRef = FirebaseDatabase.getInstance().getReference().child("Contacts").child(currentUID);
UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
confirmButton = findViewById(R.id.confirm_group);
MobileAds.initialize(this, "ca-app-pub-3127817354023186~6842500243");
final AdView mAdView;
mAdView = findViewById(R.id.choose_user_adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
mAdView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
// Code to be executed when an ad finishes loading.
}
#Override
public void onAdFailedToLoad(int errorCode) {
// Code to be executed when an ad request fails.
}
#Override
public void onAdOpened() {
// Code to be executed when an ad opens an overlay that
// covers the screen.
}
#Override
public void onAdClicked() {
// Code to be executed when the user clicks on an ad.
}
#Override
public void onAdLeftApplication() {
// Code to be executed when the user has left the app.
}
#Override
public void onAdClosed() {
// Code to be executed when the user is about to return
// to the app after tapping on an ad.
}
});
Toolbar toolbar = findViewById(R.id.users_chosers_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle("Choose users to be in " + getIntent().getExtras().get("groupName").toString());
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerOptions<Contacts> options =
new FirebaseRecyclerOptions.Builder<Contacts>()
.setQuery(ContactsRef, Contacts.class)
.build()
;
FirebaseRecyclerAdapter<Contacts, ChatsViewHolder>
adapter = new
FirebaseRecyclerAdapter <Contacts, ChatsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final ChatsViewHolder holder, final int position, #NonNull Contacts model)
{
final String string = getRef(position).getKey();
final String[] image = {"default_image"};
UsersRef
.child(string)
.addValueEventListener(new ValueEventListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(#NonNull final DataSnapshot dataSnapshot)
{
if (dataSnapshot.exists())
{
if (dataSnapshot.hasChild("image"))
{
image[0] = dataSnapshot.child("image").getValue().toString();
Picasso.get().load(image[0]).placeholder(R.drawable.profile_image).into(holder.profileImageView);
}
final String name = dataSnapshot.child("name").getValue().toString();
holder.Username.setText(name);
holder.Userstatus.setText("Last seen: \n");
if(dataSnapshot.child("userState").hasChild("state"))
{
String date = dataSnapshot.child("userState").child("date").getValue().toString();
String state = dataSnapshot.child("userState").child("state").getValue().toString();
String time = dataSnapshot.child("userState").child("time").getValue().toString();
if(Objects.equals(state, "online"))
{
holder.Userstatus.setText(getString(R.string.Online));
}
else
{
holder.Userstatus.setText(getString(R.string.last_seen) + time + " " + date);
}
}
else
{
holder.Userstatus.setText("Offline");
}
final HashMap<String, Object> hashMap = new HashMap<>();
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if (!hashMap.containsKey(getRef(position).getKey())) {
holder.itemView.setPadding(15, 15, 15, 15);
holder.IsUserInGroup.setVisibility(View.VISIBLE);
if (hashMap.isEmpty()) {
hashMap.put(currentUID, "admin");
}
hashMap.put(getRef(position).getKey(), "non-admin");
}
else {
holder.itemView.setPadding(0, 0, 0, 0);
if (hashMap.size() == 1)
{
hashMap.remove(currentUID, "admin");
}
holder.IsUserInGroup.setVisibility(View.INVISIBLE);
hashMap.remove(getRef(position).getKey(), "non-admin");
}
groupsRef = FirebaseDatabase.getInstance().getReference().child("Groups").child(getIntent().getExtras().get("groupKey").toString());
}
});
confirmButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
final StorageReference ProfileImagesRef;
ProfileImagesRef = FirebaseStorage.getInstance().getReference().child("Groups profile images");
final StorageReference ref = ProfileImagesRef.child(getIntent().getExtras().get("groupKey").toString() + ".jpg");
ref.putFile((Uri) getIntent().getExtras().get("groupImage"))
.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri)
{
Toast.makeText(chooseUserActivity.this, uri.toString(), Toast.LENGTH_SHORT).show();
downloadUrl = uri.toString();
}
});
}
});
groupsRef = FirebaseDatabase.getInstance().getReference().child("Groups").child(getIntent().getExtras().get("groupKey").toString());
groupsRef.child("Users").updateChildren(hashMap);
groupsRef.child("Messages").setValue("");
groupsRef.child("Group info").child("group name").setValue(getIntent().getExtras().get("groupName").toString());
groupsRef.child("Group info").child("group image").setValue(downloadUrl);
Toast.makeText(chooseUserActivity.this, "Group created successfully", Toast.LENGTH_SHORT).show();
Intent settingsIntent = new Intent(chooseUserActivity.this, MainActivity.class);
settingsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(settingsIntent);
finish();
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#NonNull
#Override
public ChatsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i)
{
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.users_display_layout, viewGroup, false);
return new ChatsViewHolder(view);
}
};
myRecyclerList.setAdapter(adapter);
adapter.startListening();
}
public static class ChatsViewHolder extends RecyclerView.ViewHolder
{
CircleImageView profileImageView;
TextView Username, Userstatus;
CheckBox IsUserInGroup;
ChatsViewHolder(#NonNull View itemView)
{
super(itemView);
profileImageView = itemView.findViewById(R.id.users_profile_image);
Username = itemView.findViewById(R.id.users_name);
Userstatus = itemView.findViewById(R.id.users_status);
IsUserInGroup = itemView.findViewById(R.id.IsUserInGroup);
}
}
}
Can anyone help me please?
I fixed it by moving the code in the on success listener itself

I got an error about override method and class jsonresponse

I can't solve this problem in my new app. I am a beginner in Android Studio. My register.java class file is added here:
package com.agte.agtevivo;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class Register extends AppCompatActivity {
Button button;
EditText editText3,editText4,editText5,editText6,editText7;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
editText3 =(EditText)findViewById(R.id.editText3);
editText4=(EditText)findViewById(R.id.editText4);
editText5 =(EditText)findViewById(R.id.editText5);
editText6=(EditText)findViewById(R.id.editText6);
editText7=(EditText)findViewById(R.id.editText7);
button=(Button)findViewById(R.id.button);
//button.setOnClickListener(this);
button.setOnClickListener(new View.OnClickListener(){
// #Override
public void onClik(View v){
final String name=editText3.getText().toString();
final String username=editText4.getText().toString();
final int number=Integer.parseInt(editText7.getText().toString());
final String shop=editText5.getText().toString();
final String password=editText6.getText().toString();
Response.Listener<String> responceListener =new Response.Listener<String>(){
// #Override
public void onResponce (String responce){
try {
JSONObject jsonResponce =new JSONObject(responce);
boolean success=new jsonResponce("Registerd Successfully");
if(success)
{
Intent intent =new Intent(Register.this,Login.class);
Register.this.startActivity(intent);
}else{
AlertDialog.Builder builder =new AlertDialog.Builder(Register.this);
builder.setMessage("Register Failed");
//.setNegativeButton("Retry",null);
//.create()
//.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
};
};
RegisterRequest registerRequest =new RegisterRequest
(name,username,number,shop,password,responceListener);
RequestQueue queue = Volley.newRequestQueue(Register.this);
queue.add(registerRequest);
}
});
}
/* #Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.button:
break;
}
}
*/
}
I got an error I have listed on below:
Error:(38, 62) error: is not
abstract and does not override abstract method onClick(View) in
OnClickListener
Error:(48, 93) error: is
not abstract and does not override abstract method
onResponse(String) in Listener
Error:(53, 50) error: cannot find symbol class jsonResponce
Error:Execution failed for task
':app:compileFlavorDebugJavaWithJavac'. Compilation failed; see the
compiler error output for details.
Currently I got an error:
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = new jsonResponse.getBoolean("Success");
if (success) {
Intent intent = new Intent(Register.this, Login.class);
Register.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(Register.this);
builder.setMessage("Register Failed");
//.setNegativeButton("Retry",null);
//.create()
//.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Error is:
Error:Execution failed for task ':app:compileFlavorDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
Error:(62, 47) error: incompatible types
required: boolean
found: getBoolean
package com.agte.agtevivo;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class Register extends AppCompatActivity {
Button button;
EditText editText3,editText4,editText5,editText6,editText7;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
editText3 =(EditText)findViewById(R.id.editText3);
editText4=(EditText)findViewById(R.id.editText4);
editText5 =(EditText)findViewById(R.id.editText5);
editText6=(EditText)findViewById(R.id.editText6);
editText7=(EditText)findViewById(R.id.editText7);
button=(Button)findViewById(R.id.button);
//button.setOnClickListener(this);
button.setOnClickListener(new View.OnClickListener(){
// #Override
public void onClick(View v){
final String name=editText3.getText().toString();
final String username=editText4.getText().toString();
final int number=Integer.parseInt(editText7.getText().toString());
final String shop=editText5.getText().toString();
final String password=editText6.getText().toString();
Response.Listener<String> responceListener =new Response.Listener<String>(){
#Override
public void onResponse (String responce){
try {
JSONObject jsonResponce =new JSONObject(responce);
// What is this ?
boolean success=new jsonResponce("Registerd Successfully");
if(success)
{
Intent intent =new Intent(Register.this,Login.class);
Register.this.startActivity(intent);
}else{
AlertDialog.Builder builder =new AlertDialog.Builder(Register.this);
builder.setMessage("Register Failed");
//.setNegativeButton("Retry",null);
//.create()
//.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
};
};
RegisterRequest registerRequest =new RegisterRequest
(name,username,number,shop,password,responceListener);
RequestQueue queue = Volley.newRequestQueue(Register.this);
queue.add(registerRequest);
}
});
}
/* #Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.button:
break;
}
}
*/
}
Theres a load of grammar failures in your code, which I corrected in the snipped above (just make a diff) for further debugging look here: https://developer.android.com/studio/debug/index.html

Categories