Im having a problem with an app that I built that seems to be related to me using too many final variables in memory, when I test the app in android 2.3 and below it works fine but 4.0 and above it crashes after a while if the list gets too long, what im trying to figure out is a way that I can either bypass making the variables final or a way that can potentially make them null once they arent in view perhaps? below is my code, any help would go a long way thanks
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
final String url = (String) data.get(position).get(4);
final String aviUrl = (String) data.get(position).get(2);
final Date theTime = (Date) data.get(position).get(3);
final String theTweetText = (String) data.get(position).get(1);
final String theRealName = (String) data.get(position).get(0);
final String theScreenName = (String) data.get(position).get(5);
Boolean isRetweeted = (Boolean) data.get(position).get(6);
final Long iD = (Long) data.get(position).get(7);
final Integer totalTweets = (Integer) data.get(position).get(8);
final Integer totalFollowers = (Integer) data.get(position).get(9);
final Integer totalFollowing = (Integer) data.get(position).get(10);
final Long tweetId = (Long) data.get(position).get(11);
Date currentDate = new Date();
if (convertView == null)
vi = inflater.inflate(R.layout.item, null);
if (isRetweeted == true) {
final String theRetweetedTxt = (String) data.get(position).get(12);
final String theRetweetedUser = (String) data.get(position).get(13);
final String theRetweetedImgUrl = (String) data.get(position).get(14);
final String theRetweetedScreenName = (String) data.get(position).get(15);
final Long rTiD = (Long) data.get(position).get(16);
final Integer rTtotalTweets = (Integer) data.get(position).get(17);
final Integer rTtotalFollowers = (Integer) data.get(position).get(18);
final Integer rTtotalFollowing = (Integer) data.get(position).get(19);
final Long rtTweetId = (Long) data.get(position).get(20);
TextView theTweet = (TextView) vi.findViewById(R.id.tweet_text);
TextView username = (TextView) vi.findViewById(R.id.username);
TextView realname = (TextView) vi.findViewById(R.id.realname);
TextView theTimeTv = (TextView) vi.findViewById(R.id.theTime);
ImageView aviimage = (ImageView) vi.findViewById(R.id.user_avatar);
ImageView image = (ImageView) vi.findViewById(R.id.imageView1);
ImageView retweeterimage = (ImageView) vi
.findViewById(R.id.retweeter_avatar);
ImageView replyImage = (ImageView) vi.findViewById(R.id.mentionbutton);
ImageView retweetImage = (ImageView) vi.findViewById(R.id.retweetbutton);
RelativeLayout profileImageLayout = (RelativeLayout) vi.findViewById(R.id.profileimagelayout);
profileImageLayout.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Context context = v.getContext();
Intent intent=new Intent(context, FriendProfileActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("theuserid", rTiD);
intent.putExtra("totaltweets", rTtotalTweets);
intent.putExtra("totalfollowers", rTtotalFollowers);
intent.putExtra("totalfollowing", rTtotalFollowing);
intent.putExtra("useravatar", theRetweetedImgUrl);
intent.putExtra("username", theRetweetedUser);
intent.putExtra("screenname", theRetweetedScreenName);
intent.putExtra("tweetid", rtTweetId);
context.startActivity(intent);
}
});
image.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Context context = v.getContext();
Intent intent=new Intent(context, LightboxActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("thetweet", theRetweetedTxt);
intent.putExtra("theimage", url);
intent.putExtra("theuserid", rTiD);
intent.putExtra("screenname", theRetweetedScreenName);
intent.putExtra("tweetid", rtTweetId);
context.startActivity(intent);
}
});
replyImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Context context = v.getContext();
Intent intent=new Intent(context, TweetScreenActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("theuserid", rTiD);
intent.putExtra("screenname", theRetweetedScreenName);
intent.putExtra("tweetid", rtTweetId);
intent.putExtra("isretweet", false);
context.startActivity(intent);
}
});
retweetImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Context context = v.getContext();
Intent intent=new Intent(context, TweetScreenActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("theuserid", rTiD);
intent.putExtra("screenname", theRetweetedScreenName);
intent.putExtra("tweetid", rtTweetId);
intent.putExtra("isretweet", true);
intent.putExtra("thetweet", theRetweetedTxt);
context.startActivity(intent);
}
});
String str = (String) DateUtils.getRelativeTimeSpanString(theTime.getTime(), currentDate.getTime(),
0L, DateUtils.FORMAT_ABBREV_ALL);
theTimeTv.setText(str);
theTweet.setText(theRetweetedTxt);
username.setText("RT by #" + theScreenName);
realname.setText("#" + theRetweetedScreenName);
imageLoader.DisplayImage(theRetweetedImgUrl, aviimage);
imageLoader.DisplayImage(url, image);
imageLoader.DisplayImage(aviUrl, retweeterimage);
return vi;
} else {
TextView theTweet = (TextView) vi.findViewById(R.id.tweet_text);
TextView username = (TextView) vi.findViewById(R.id.username);
TextView realname = (TextView) vi.findViewById(R.id.realname);
TextView theTimeTv = (TextView) vi.findViewById(R.id.theTime);
ImageView aviimage = (ImageView) vi.findViewById(R.id.user_avatar);
ImageView image = (ImageView) vi.findViewById(R.id.imageView1);
ImageView replyImage = (ImageView) vi.findViewById(R.id.mentionbutton);
ImageView retweetImage = (ImageView) vi.findViewById(R.id.retweetbutton);
RelativeLayout profileImageLayout = (RelativeLayout) vi.findViewById(R.id.profileimagelayout);
profileImageLayout.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Context context = v.getContext();
Intent intent=new Intent(context, FriendProfileActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("theuserid", iD);
intent.putExtra("totaltweets", totalTweets);
intent.putExtra("totalfollowers", totalFollowers);
intent.putExtra("totalfollowing", totalFollowing);
intent.putExtra("useravatar", aviUrl);
intent.putExtra("username", theRealName);
intent.putExtra("screenname", theScreenName);
intent.putExtra("tweetid", tweetId);
context.startActivity(intent);
}
});
image.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Context context = v.getContext();
Intent intent=new Intent(context, LightboxActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("thetweet", theTweetText);
intent.putExtra("theimage", url);
intent.putExtra("theuserid", iD);
intent.putExtra("screenname", theScreenName);
intent.putExtra("tweetid", tweetId);
context.startActivity(intent);
}
});
replyImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Context context = v.getContext();
Intent intent=new Intent(context, TweetScreenActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("theuserid", iD);
intent.putExtra("screenname", theScreenName);
intent.putExtra("tweetid", tweetId);
intent.putExtra("isretweet", false);
context.startActivity(intent);
}
});
retweetImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Context context = v.getContext();
Intent intent=new Intent(context, TweetScreenActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("theuserid", iD);
intent.putExtra("screenname", theScreenName);
intent.putExtra("tweetid", tweetId);
intent.putExtra("isretweet", true);
intent.putExtra("thetweet", theTweetText);
context.startActivity(intent);
}
});
ImageView retweeterimage = (ImageView) vi
.findViewById(R.id.retweeter_avatar);
retweeterimage.setImageBitmap(null);
String str = (String) DateUtils.getRelativeTimeSpanString(theTime.getTime(), currentDate.getTime(),
0L, DateUtils.FORMAT_ABBREV_ALL);
theTimeTv.setText(str);
theTweet.setText(theTweetText);
username.setText(theRealName);
realname.setText("#" + theScreenName);
imageLoader.DisplayImage(aviUrl, aviimage);
imageLoader.DisplayImage(url, image);
return vi;
}
}
the 'final' keyword won't affect anything, it just basically tells the JVM that the value will not change, so your problem lies elsewhere.
Related
I'm new to Android Studio and i'm trying to do a simple register and login app, but I have one problem with the Picasso on my "Profile Picture" ImageView where the image is uploaded and stored to firebase, but the stored image won't show on ImageView.
Here's the Upload Photo code
public class UploadFoto extends AppCompatActivity {
private ProgressBar progressBar;
private ImageView imageViewUploadPic;
private Button upload_pic_btn, upload_pic_choose_btn;
private FirebaseAuth authProfile;
private StorageReference storageReference;
private FirebaseUser firebaseUser;
private static final int PICK_IMAGE_REQUEST = 1;
private Uri uriImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_upload_foto);
getSupportActionBar().setTitle("Alterar Foto de Perfil");
Button buttonUploadPicChoose = findViewById(R.id.upload_pic_choose_btn);
Button buttonUploadPic = findViewById(R.id.upload_pic_btn);
ProgressBar progressBar = findViewById(R.id.progressBar);
imageViewUploadPic = findViewById(R.id.imageView_profile_dp);
authProfile = FirebaseAuth.getInstance();
firebaseUser = authProfile.getCurrentUser();
storageReference = FirebaseStorage.getInstance().getReference("DisplayPics");
Uri uri = firebaseUser.getPhotoUrl();
//Setar foto atual do usuário (caso já tenha sido upada pro firebase) no image view
//Regular Uris.
Picasso.with(UploadFoto.this).load(uri).into(imageViewUploadPic);
//Escolhe imagem pra dar upload
buttonUploadPicChoose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFileChooser();
}
});
//realizar upload da imagem pro storage do Firebase
buttonUploadPic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressBar.setVisibility(View.VISIBLE);
UploadPic();
}
});
}
private void openFileChooser(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null){
uriImage = data.getData();
imageViewUploadPic.setImageURI(uriImage);
}
}
private void UploadPic(){
if (uriImage != null){
//Salvar imagem com o UID do usuário atual
StorageReference fileReference = storageReference.child(authProfile.getCurrentUser().getUid() + "."
+ getFileExtension(uriImage));
//Realizar Upload da imagem pro storage
fileReference.putFile(uriImage).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Uri downloadUri = uri;
firebaseUser = authProfile.getCurrentUser();
//Setar imagem do usuário após upload
UserProfileChangeRequest profireUpdates = new UserProfileChangeRequest.Builder()
.setPhotoUri(downloadUri).build();
firebaseUser.updateProfile(profireUpdates);
}
});
progressBar.setVisibility(View.GONE);
Toast.makeText(UploadFoto.this, "Imagem alterada com sucesso!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(UploadFoto.this, Perfil.class);
startActivity(intent);
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(UploadFoto.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
progressBar.setVisibility(View.GONE);
Toast.makeText(UploadFoto.this, "Nenhuma imagem foi selecionada!", Toast.LENGTH_SHORT).show();
}
}
//Obter extensão da imagem
private String getFileExtension(Uri uri){
ContentResolver cR = getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
//Criar actionbar menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//inflar menu
getMenuInflater().inflate(R.menu.common_menu, menu);
return super.onCreateOptionsMenu(menu);
}
//Quando for selecionado qualquer opção do menu
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.menu_atualizar){
//atualizar atividade/página
startActivity(getIntent());
finish();
overridePendingTransition(0, 0);
} /*else if (id == R.id.menu_alterarinfo){
Intent intent = new Intent(Perfil.this, AtualizarPerfil.class);
startActivity(intent);
} */else if (id == R.id.menu_sair){
authProfile.signOut();
Toast.makeText(UploadFoto.this, "Logout realizado com sucesso!", Toast.LENGTH_LONG).show();
Intent intent = new Intent(UploadFoto.this, Login.class);
//Limpar
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
} else {
Toast.makeText(UploadFoto.this, "Ocorreu um erro, tente novamente.", Toast.LENGTH_LONG).show();
}
return super.onOptionsItemSelected(item);
}
}
And here is the Profile code
public class Perfil extends AppCompatActivity {
private TextView textViewApelido, textViewNome, textViewCNH, textViewCategoria, textViewNatural,
textViewEndereco, textViewBairro, textViewCEP, textViewEmail, textViewTelefone, textViewCelular, textViewProfissional,
textViewTipo_Sanguíneo, textViewEstado_Civil, textViewNome_Garupa, textViewNatural_Garupa, textViewEndereco_Garupa,
textViewBairro_Garupa, textViewCEP_Garupa, textViewEmail_Garupa, textViewTelefone_Garupa, textViewCelular_Garupa,
textViewTipo_Sanguíneo_Garupa, textViewMoto, textViewAno_Modelo, textViewCC, textViewPlaca, textViewNome_Contato_1,
textViewParentesco_Contato_1, textViewCelular_Contato_1, textViewNome_Contato_2, textViewParentesco_Contato_2,
textViewCelular_Contato_2, textViewNascimento, textViewNascimento_Garupa;
private String Apelido, Nome, CNH, Categoria, Natural, Endereco, Bairro, CEP, Email, Telefone, Celular,
Profissional, Tipo_Sanguíneo, Estado_Civil, Nome_Garupa, Natural_Garupa, Endereco_Garupa, Bairro_Garupa, CEP_Garupa, Email_Garupa,
Telefone_Garupa, Celular_Garupa, Tipo_Sanguíneo_Garupa, Moto, Ano_Modelo, CC, Placa, Nome_Contato_1, Parentesco_Contato_1, Celular_Contato_1,
Nome_Contato_2, Parentesco_Contato_2, Celular_Contato_2, Nascimento, Nascimento_Garupa;
private ImageView imageView;
private FirebaseAuth authProfile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_perfil);
getSupportActionBar().setTitle("Perfil do Usuário");
textViewApelido = (TextView) findViewById(R.id.textView_show_apelido);
textViewNome = (TextView) findViewById(R.id.textView_show_nome);
textViewCNH = (TextView) findViewById(R.id.textView_show_CNH);
textViewCategoria = (TextView) findViewById(R.id.textView_show_categoria);
textViewNatural = (TextView) findViewById(R.id.textView_show_natural);
textViewEndereco = (TextView) findViewById(R.id.textView_show_endereco);
textViewBairro = (TextView) findViewById(R.id.textView_show_bairro);
textViewCEP = (TextView) findViewById(R.id.textView_show_CEP);
textViewEmail = (TextView) findViewById(R.id.textView_show_email);
textViewTelefone = (TextView) findViewById(R.id.textView_show_telefone);
textViewCelular = (TextView) findViewById(R.id.textView_show_celular);
textViewProfissional = (TextView) findViewById(R.id.textView_show_profissional);
textViewTipo_Sanguíneo = (TextView) findViewById(R.id.textView_show_sangue);
textViewEstado_Civil = (TextView) findViewById(R.id.textView_show_civil);
textViewNome_Garupa = (TextView) findViewById(R.id.textView_show_nomeg);
textViewNatural_Garupa = (TextView) findViewById(R.id.textView_show_naturalg);
textViewEndereco_Garupa = (TextView) findViewById(R.id.textView_show_enderecog);
textViewBairro_Garupa = (TextView) findViewById(R.id.textView_show_bairrog);
textViewCEP_Garupa = (TextView) findViewById(R.id.textView_show_CEPg);
textViewEmail_Garupa = (TextView) findViewById(R.id.textView_show_emailg);
textViewTelefone_Garupa = (TextView) findViewById(R.id.textView_show_telefoneg);
textViewCelular_Garupa = (TextView) findViewById(R.id.textView_show_celularg);
textViewTipo_Sanguíneo_Garupa = (TextView) findViewById(R.id.textView_show_sangueg);
textViewMoto = (TextView) findViewById(R.id.textView_show_moto);
textViewAno_Modelo = (TextView) findViewById(R.id.textView_show_anomodelo);
textViewCC = (TextView) findViewById(R.id.textView_show_CC);
textViewPlaca = (TextView) findViewById(R.id.textView_show_placa);
textViewNome_Contato_1 = (TextView) findViewById(R.id.textView_show_nomecont1);
textViewParentesco_Contato_1 = (TextView) findViewById(R.id.textView_show_parentcont1);
textViewCelular_Contato_1 = (TextView) findViewById(R.id.textView_show_celcont1);
textViewNome_Contato_2 = (TextView) findViewById(R.id.textView_show_nomecont2);
textViewParentesco_Contato_2 = (TextView) findViewById(R.id.textView_show_parentcont2);
textViewCelular_Contato_2 = (TextView) findViewById(R.id.textView_show_celcont2);
textViewNascimento = (TextView) findViewById(R.id.textView_show_nascimento);
textViewNascimento_Garupa = (TextView) findViewById(R.id.textView_show_nascimentog);
//ClickListener ao clicar no ImageView para editar foto de perfil
imageView = (ImageView) findViewById(R.id.foto);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Perfil.this, UploadFoto.class);
startActivity(intent);
}
});
authProfile = FirebaseAuth.getInstance();
FirebaseUser firebaseUser = authProfile.getCurrentUser();
if (firebaseUser == null){
Toast.makeText(Perfil.this, "Erro, dados do usuário indisponíveis.", Toast.LENGTH_LONG).show();
} else{
CheckEmailVerified(firebaseUser);
showUserProfile(firebaseUser);
}
}
private void CheckEmailVerified(FirebaseUser firebaseUser) {
if (!firebaseUser.isEmailVerified()){
showAlertDialog();
}
}
private void showAlertDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(Perfil.this);
builder.setTitle("Email não verificado");
builder.setMessage("Favor verificar seu e-mail.");
//open email app
builder.setPositiveButton("continuar", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_APP_EMAIL);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
private void showUserProfile(FirebaseUser firebaseUser) {
String userID = firebaseUser.getUid();
//Extrair referência do usuário do BD para "User"
DatabaseReference referenceProfile = FirebaseDatabase.getInstance().getReference("Users");
referenceProfile.child(userID).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
User readUser = snapshot.getValue(User.class);
if (readUser != null){
Apelido = readUser.Apelido;
Nome = readUser.Nome;
CNH = readUser.CNH;
Email = readUser.Email;
Categoria = readUser.Categoria;
Natural = readUser.Natural;
Endereco = readUser.Endereco;
Bairro = readUser.Bairro;
CEP = readUser.CEP;
Email = readUser.Email;
Telefone = readUser.Telefone;
Celular = readUser.Celular;
Profissional = readUser.Profissional;
Tipo_Sanguíneo = readUser.Tipo_Sanguíneo;
Estado_Civil = readUser.Estado_Civil;
Nome_Garupa = readUser.Nome_Garupa;
Natural_Garupa = readUser.Natural_Garupa;
Endereco_Garupa = readUser.Endereco_Garupa;
Bairro_Garupa = readUser.Bairro_Garupa;
CEP_Garupa = readUser.CEP_Garupa;
Email_Garupa = readUser.Email_Garupa;
Telefone_Garupa = readUser.Telefone_Garupa;
Celular_Garupa = readUser.Celular_Garupa;
Tipo_Sanguíneo_Garupa = readUser.Tipo_Sanguíneo_Garupa;
Ano_Modelo = readUser.Ano_Modelo;
CC = readUser.CC;
Placa = readUser.Placa;
Nome_Contato_1 = readUser.Nome_Contato_1;
Parentesco_Contato_1 = readUser.Parentesco_Contato_1;
Celular_Contato_1 = readUser.Celular_Contato_1;
Nome_Contato_2 = readUser.Nome_Contato_2;
Parentesco_Contato_2 = readUser.Parentesco_Contato_2;
Celular_Contato_2 = readUser.Celular_Contato_2;
Nascimento = readUser.Nascimento;
Nascimento_Garupa = readUser.Nascimento_Garupa;
textViewApelido.setText(Apelido);
textViewNome.setText(Nome);
textViewCNH.setText(CNH);
textViewCategoria.setText(Categoria);
textViewNatural.setText(Natural);
textViewEndereco.setText(Endereco);
textViewBairro.setText(Bairro);
textViewCEP.setText(CEP);
textViewEmail.setText(Email);
textViewTelefone.setText(Telefone);
textViewCelular.setText(Celular);
textViewProfissional.setText(Profissional);
textViewTipo_Sanguíneo.setText(Tipo_Sanguíneo);
textViewEstado_Civil.setText(Estado_Civil);
textViewNome_Garupa.setText(Nome_Garupa);
textViewNatural_Garupa.setText(Natural_Garupa);
textViewEndereco_Garupa.setText(Endereco_Garupa);
textViewBairro_Garupa.setText(Bairro_Garupa);
textViewCEP_Garupa.setText(CEP_Garupa);
textViewEmail_Garupa.setText(Email_Garupa);
textViewTelefone_Garupa.setText(Telefone_Garupa);
textViewCelular_Garupa.setText(Celular_Garupa);
textViewTipo_Sanguíneo_Garupa.setText(Tipo_Sanguíneo_Garupa);
textViewMoto.setText(Moto);
textViewAno_Modelo.setText(Ano_Modelo);
textViewCC.setText(CC);
textViewPlaca.setText(Placa);
textViewNome_Contato_1.setText(Nome_Contato_1);
textViewParentesco_Contato_1.setText(Parentesco_Contato_1);
textViewCelular_Contato_1.setText(Celular_Contato_1);
textViewNome_Contato_2.setText(Nome_Contato_2);
textViewParentesco_Contato_2.setText(Parentesco_Contato_2);
textViewCelular_Contato_2.setText(Celular_Contato_2);
textViewNascimento.setText(Nascimento);
textViewNascimento_Garupa.setText(Nascimento_Garupa);
//Setar foto do usuário após upload no perfil
Uri uri = firebaseUser.getPhotoUrl();
//ImageViewer setando Img no URI
Picasso.with(Perfil.this).load(uri).into(imageView);
}else {
Toast.makeText(Perfil.this, "Erro.", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(Perfil.this, "Erro!", Toast.LENGTH_LONG).show();
}
});
}
//Criar actionbar menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//inflar menu
getMenuInflater().inflate(R.menu.common_menu, menu);
return super.onCreateOptionsMenu(menu);
}
//Quando for selecionado qualquer opção do menu
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.menu_atualizar){
//atualizar atividade/página
startActivity(getIntent());
finish();
overridePendingTransition(0, 0);
} /*else if (id == R.id.menu_alterarinfo){
Intent intent = new Intent(Perfil.this, AtualizarPerfil.class);
startActivity(intent);
} */else if (id == R.id.menu_sair){
authProfile.signOut();
Toast.makeText(Perfil.this, "Logout realizado com sucesso!", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Perfil.this, Login.class);
//Limpar
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
} else {
Toast.makeText(Perfil.this, "Ocorreu um erro, tente novamente.", Toast.LENGTH_LONG).show();
}
return super.onOptionsItemSelected(item);
}
}
Using Picasso implementation 2.5.2.
Already have permission to internet.
Wanting Picasso to "fetch" the image from storage on firebase to display on the user profile.
This question already has answers here:
How to use SharedPreferences in Android to store, fetch and edit values [closed]
(30 answers)
Closed 5 years ago.
hey guys so i got a login activity that checks username and password with server to authenticate users. i want to use sharedpermissions to store username and password so that the user wont have log in every time. i also want to create a login button.
i tried to implement it but itjust skips login acitivity and takes me to my second activity. i left some of sharedpermission codes as comments (//)
can anyone show/tell me the best i can do it?
public class LoginActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//String username = "";
//String password = "";
//SharedPreferences pre;
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
final TextView tvRegisterLink = (TextView) findViewById(R.id.tvRegisterhere);
final Button bLogin = (Button) findViewById(R.id.bLogin);
if(TextUtils.isEmpty(etUsername.getText().toString())||TextUtils.isEmpty(etPassword.getText().toString())){
Intent intent = new Intent(LoginActivity.this, UserAreaActivity.class);
LoginActivity.this.startActivity(intent);
} else {
Intent registerIntent = new Intent(LoginActivity.this, LoginActivity.class);
LoginActivity.this.startActivity(registerIntent);
}
final String username1 = SharedPreferenceUtils.getUsername(this);
final String password1 = SharedPreferenceUtils.getPassword(this);
// pre = getSharedPreferences("pref",MODE_PRIVATE);
//if(pre.getBoolean("username",true) && pre.getBoolean("password",true)){
tvRegisterLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registerIntent = new Intent(LoginActivity.this, RegisterActivity.class);
LoginActivity.this.startActivity(registerIntent);
}
});
bLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = etUsername.getText().toString();
final String password = etPassword.getText().toString();
// Response received from the server
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
String name = jsonResponse.getString("name");
SharedPreferenceUtils.createSP(LoginActivity.this,username1,password1);
Intent intent = new Intent(LoginActivity.this, UserAreaActivity.class);
intent.putExtra("name", name);
intent.putExtra("username", username);
LoginActivity.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage("Login Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginRequest = new LoginRequest(username, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
queue.add(loginRequest);
}
});
}
}
public class UserAreaActivity extends AppCompatActivity {
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_area);
final TextView etusername = (TextView) findViewById(R.id.textView2);
final TextView etwelcome = (TextView) findViewById(R.id.textView);
final ImageButton red = (ImageButton) findViewById(R.id.imageButton);
final ImageButton messages = (ImageButton) findViewById(R.id.imageButton2);
final ImageButton blue = (ImageButton) findViewById(R.id.imageButton3);
final ImageButton ping = (ImageButton) findViewById(R.id.imageButton4);
final TextView etuname = (TextView) findViewById(R.id.textView3);
final Button Logout = (Button) findViewById(R.id.logout);
//String Name = SharedPreferenceUtils.getName(this);
//etwelcome.setText(Name);
red.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registerIntent = new Intent(UserAreaActivity.this, Report.class);
UserAreaActivity.this.startActivity(registerIntent);
}
});
messages.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registerIntent = new Intent(UserAreaActivity.this, Messages.class);
UserAreaActivity.this.startActivity(registerIntent);
}
});
Logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isClear = SharedPreferenceUtils.clearSP(UserAreaActivity.this);
if(isClear){
Intent registerIntent = new Intent(UserAreaActivity.this, LoginActivity.class);
UserAreaActivity.this.startActivity(registerIntent);
}
}
});
Intent intent = getIntent();
String name = intent.getStringExtra("name");
String username = intent.getStringExtra("username");
String message = "Welcome " + name;
etwelcome.setText(message);
etusername.setText(username);
//Intent in = new Intent(getApplicationContext(), Messages.class);
//in.putExtra("username", username);
//UserAreaActivity.this.startActivity(in);
}
}
You can use SharedPreferences in your code .
Try this .
public class SharedPreferenceUtils {
private static final String SP_NAME = "sp";
public static final String USERNAME = "username";
public static final String PASSWORD = "password";
// create
public static boolean createSP(Context context, String username, String password) {
SharedPreferences.Editor editor = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE).edit();
editor.putString(USERNAME, username);
editor.putString(PASSWORD, password);
return editor.commit();
}
// clear
public static boolean clearSP(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
return editor.clear().commit();
}
// get access info
public static String getUsername(Context context) {
SharedPreferences sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
return sp.getString(USERNAME, "");
}
// get branch info
public static String getPassword(Context context) {
SharedPreferences sp = context.getSharedPreferences(SP_NAME, Context.MODE_PRIVATE);
return sp.getString(PASSWORD, "");
}
}
Use in LoginActivity
SharedPreferenceUtils.createSP(this,username,password);
And use in other Activity
String username = SharedPreferenceUtils.getUsername(this);
String password = SharedPreferenceUtils.getPassword(this);
Edit
if (success) {
String name = jsonResponse.getString("name");
SharedPreferenceUtils.createSP(this, username, password);
}
Edit
private EditText etUsername, etPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
String username = SharedPreferenceUtils.getUsername(this);
String password = SharedPreferenceUtils.getPassword(this);
etUsername.setText(username);
etPassword.setText(password);
}
Edit
if(TextUtils.isEmpty(etUsername.getText().toString())||TextUtils.isEmpty(etPassword.getText().toString())){
Intent intent = new Intent(LoginActivity.this, A.class);
LoginActivity.this.startActivity(intent);
} else {
Intent registerIntent = new Intent(LoginActivity.this, B.class);
LoginActivity.this.startActivity(intent);
}
Edit
boolean isClear = SharedPreferenceUtils.clearSP(UserAreaActivity.this);
if(isClear){
Intent registerIntent = new Intent(UserAreaActivity.this, LoginActivity.class);
UserAreaActivity.this.startActivity(registerIntent);
}
Hello dear StackOverflow community!!!
While developing my recent application project i found some problems while debugging the app. In my project i want to pass one data element through 2 activities. Everything looks good (no errors or other stuff) until i choose WatchingActivity in my app. It displays no webview but only white blank space while there should be video choosen in PartActivity. Please help!!!!
public class MainActivity extends AppCompatActivity {
String clipname;
ImageView ka;
ImageView jb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ka = (ImageView) findViewById(R.id.imageView1);
jb = (ImageView) findViewById(R.id.imageView2);
}
public void imageView1Clicked(View view) {
// method that is signed in layout file to be called by clicking on imageView1
clipname="Kendra's Adventure";
Intent mainintent = new Intent(this, ChooseAPartActivity.class);
mainintent.putExtra("CLIP", clipname);
startActivity(mainintent);
}
public void imageView2Clicked(View view) {
clipname="Johhny Big";
Intent mainintent = new Intent(this, ChooseAPartActivity.class);
mainintent.putExtra("CLIP", clipname);
startActivity(mainintent);
}
}
public class ChooseAPartActivity extends AppCompatActivity {
TextView title;
TextView part1;
TextView part2;
TextView part3;
TextView part4;
TextView part5;
TextView part6;
String videoname;
String partnumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_a_part);
title.findViewById(R.id.textView);
title.findViewById(R.id.textView);
Intent mainintent = getIntent();
String clipname = mainintent.getStringExtra("CLIP");
title.setText(clipname);
videoname = clipname;
}
public void partone (View view) {
//method assigned to textview in layout file
partnumber = "one";
Intent partintent = new Intent(this, WatchingActivity.class);
partintent.putExtra("PART", videoname);
partintent.putExtra("NUMBER", partnumber);
startActivity(partintent);
}
public void parttwo (View view) {
partnumber = "two";
Intent partintent = new Intent(this, WatchingActivity.class);
partintent.putExtra("PART", videoname);
partintent.putExtra("NUMBER", partnumber);
startActivity(partintent);
}
public void partthree (View view) {
partnumber = "three";
Intent partintent = new Intent(this, WatchingActivity.class);
partintent.putExtra("PART", videoname);
partintent.putExtra("NUMBER", partnumber);
startActivity(partintent);
}
public void partfour (View view) {
partnumber = "four";
Intent partintent = new Intent(this, WatchingActivity.class);
partintent.putExtra("PART", videoname);
partintent.putExtra("NUMBER", partnumber);
startActivity(partintent);
}
public void partfive (View view) {
partnumber = "five";
Intent partintent = new Intent(this, WatchingActivity.class);
partintent.putExtra("PART", videoname);
partintent.putExtra("NUMBER", partnumber);
startActivity(partintent);
}
public void partsix (View view) {
partnumber = "six";
Intent partintent = new Intent(this, WatchingActivity.class);
partintent.putExtra("PART", videoname);
partintent.putExtra("NUMBER", partnumber);
startActivity(partintent);
}
}
public class WatchingActivity extends AppCompatActivity {
String clipkey;
WebView screen;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_watching);
Intent sceneintent = getIntent();
String videoname = partintent.getStringExtra("PART");
String partnumber = sceneintent.getStringExtra("NUMBER");
if(videoname == "Kendra's Adventure"){
if(partnumber == "one"){
clipkey = "<iframe width=\"95%\" height=\"95%\" src=\"links work fine i tried it many times so its not that\" frameborder=\"0\" allowfullscreen></iframe>";
}
}
else if(videoname == "Johnny Big"){
if(partnumber == "one") {
clipkey = "<iframe width=\"95%\" height=\"95%\" src=\"\" frameborder=\"0\" allowfullscreen></iframe>";
}
else if(partnumber == "two"){
clipkey = "<iframe width=\"95%\" height=\"95%\" src=\"\" frameborder=\"0\" allowfullscreen></iframe>";
}
}
screen=(WebView)findViewById(R.id.webView);
screen.getSettings().setJavaScriptEnabled(true);
String myvideokey = clipkey;
screen.loadData(myvideokey, "text/html", "utf-8");
screen.setWebChromeClient(new WebChromeClient(){
});
}
}
String videoname = partintent.getStringExtra("PART");
Is that line ok in WatchingActivity? There is no partintent field or something.
Defining all activities in the same class-file is not really good idea.
I am currently creating an android app that scans a network and outputs results in a ListView but I am trying to make it to where I tap on the network and it saves the data in a database then sends you to a page to show you what you selected but when I click an item it substrings the values correctly and displays work fine on the main activity but when I try to use the variables on my display page activity there values are set null.
Here is the main activity in the click listener:
networklist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String grabItemInfo = wifis[position];
Network_Info info1 = new Network_Info();
info1.setMainBSSID( grabItemInfo.substring(grabItemInfo.indexOf('#') +1, grabItemInfo.lastIndexOf('#')));
info1.setMainSSID( grabItemInfo.substring(0,(grabItemInfo.indexOf('#'))));
info1.setMainCAP( grabItemInfo.substring(grabItemInfo.lastIndexOf('#')+1, grabItemInfo.length()));
Toast toastTest = Toast.makeText(getApplicationContext(), info1.getMainSSID(), Toast.LENGTH_SHORT);
Toast toastTest2 = Toast.makeText(getApplicationContext(), info1.getMainBSSID(), Toast.LENGTH_SHORT);
Toast toastTest3 = Toast.makeText(getApplicationContext(), info1.getMainCAP(), Toast.LENGTH_SHORT);
toastTest.show();
toastTest2.show();
toastTest3.show();
ContentValues dbv = new ContentValues();
dbv.put("SSID", info1.getMainSSID());
dbv.put("BSSID", info1.getMainBSSID());
dbv.put("CAPABILITIES", info1.getMainCAP());
netDataBase.insert("netDataTable", "NULL", dbv);
Intent intent = new Intent(getApplicationContext(), Attack_Page.class);
startActivity(intent);
}
});
Here is my display page:
public class Attack_Page extends Network_List {
protected void onCreate(Bundle SavedIS){
super.onCreate(SavedIS);
setContentView(R.layout.attack_page);
TextView SSIDview = (TextView) findViewById(R.id.SSIDView);
TextView BSSIDview = (TextView) findViewById(R.id.BSSIDView);
TextView CAPview = (TextView) findViewById(R.id.CAPView);
Button backButton = (Button) findViewById(R.id.backbutton);
Intent intent = getIntent();
//String MainSSIDP = intent.getStringExtra(getMainSSID());
Network_Info info1 = new Network_Info();
Toast testToast = Toast.makeText(getApplicationContext(), info1.getMainSSID(), Toast.LENGTH_SHORT);
testToast.show();
//Cursor IDselect = netDataBase.rawQuery("SELECT SSID FROM netDataTable WHERE SSID = "+getMainSSID()+"", wifis);
//SSIDview.setText(IDselect.toString());
backButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent bintent = new Intent(getApplicationContext(), Network_List.class);
startActivity(bintent);
}
});
}
}
Here is my setters and getters class:
public class Network_Info {
private String mainCAP;
private String mainSSID;
private String mainBSSID;
public void setMainSSID(String newMainSSID){
mainSSID = newMainSSID;
}
public void setMainBSSID(String newMainBSSID){
mainBSSID = newMainBSSID;
}
public void setMainCAP(String newMainCAP){
mainCAP = newMainCAP;
}
public String getMainSSID(){
return mainSSID;
}
public String getMainBSSID(){
return mainBSSID;
}
public String getMainCAP(){
return mainCAP;
}
}
Figured out you have to pass the variable with the intent:
Intent intent = new Intent(getApplicationContext(), Attack_Page.class);
intent.putExtra("EXTRA_SSID", info1.getMainSSID());
intent.putExtra("EXTRA_BSSID", info1.getMainBSSID());
intent.putExtra("EXTRA_CAP", info1.getMainCAP());
startActivity(intent);
Then use the key that you set in putExtra()
String MainSSIDP = intent.getStringExtra("EXTRA_SSID");
Thanks for the help though!
This question already has answers here:
How do I get the dialer to open with phone number displayed?
(7 answers)
Closed 6 years ago.
I have made an application that uses Google Places API. Once I click on a place it returns the name of the company, the address and the number to the MainActivity. When I click on the number I can open the dialer but I can't seem to get the number that is returned on the MainActivity into the dialer. Any ideas on how I could go about doing this. Thanks
My Code is as follows
MainActivity
private TextView mName;
private TextView mAddress;
private TextView mNumber;
private static final LatLngBounds Sligo = new LatLngBounds(
new LatLng(54.27, -8.47), new LatLng(54.27, -8.47));
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
mName = (TextView) findViewById(R.id.textView);
mAddress = (TextView) findViewById(R.id.textView2);
mAttributions = (TextView) findViewById(R.id.textView3);
mNumber = (TextView) findViewById(R.id.textView4);
Button pickerButton = (Button) findViewById(R.id.pickerButton);
pickerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
PlacePicker.IntentBuilder intentBuilder =
new PlacePicker.IntentBuilder();
intentBuilder.setLatLngBounds(Sligo);
List<Integer> filterTypes = new ArrayList<Integer>();
filterTypes.add(Place.TYPE_CAR_REPAIR);
Intent intent = intentBuilder.build(MainActivity.this);
startActivityForResult(intent, PLACE_PICKER_REQUEST );
} catch (GooglePlayServicesRepairableException
| GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
});
#Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST
&& resultCode == Activity.RESULT_OK) {
final Place place = PlacePicker.getPlace(this, data);
final CharSequence name = place.getName();
final CharSequence address = place.getAddress();
final CharSequence formatted_phone_number = place.getPhoneNumber();
// final CharSequence car = place.TYPE_CAR_REPAIR();
//public abstract List<Integer> getTypeFilter(place.TYPE_CAR_REPAIR);
String attributions = (String) place.getAttributions();
if (attributions == null) {
attributions = "";
}
mName.setText(name);
mAddress.setText(address);
mAttributions.setText(Html.fromHtml(attributions));
mNumber.setText(formatted_phone_number);
} else {
super.onActivityResult(requestCode, resultCode, data);
}
onClick event
public void onClickNumber(View arg)
{
Intent intent = new Intent(Intent.ACTION_DIAL);
startActivity(intent);
}
The number is at the bottom of the screen
Try This
String phone = mNumber.getText().toString();
Intent phoneIntent = new Intent(Intent.ACTION_DIAL, Uri.fromParts(
"tel", phone, null));
startActivity(phoneIntent);
Try this.
String number = "494498498";
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:" +number));
startActivity(intent);