I am adding images to the firebase storage. But before adding i want to check the network connectivity for that i used a AsyncTask. But after adding it my app started crashing...
Following is my AddImages.java File of fragment_add_images.xml file
package com.example.lenovo.jdstudio;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import static android.app.Activity.RESULT_OK;
import static android.content.ContentValues.TAG;
import static java.security.AccessController.getContext;
/**
* A simple {#link Fragment} subclass.
*/
public class AddImages extends Fragment {
private static final int GALLERY_REQUEST = 1;
ArrayAdapter<CharSequence> adapter;
private EditText mtitle;
private EditText mresolution;
private EditText mImageType;
private EditText mprice;
private Spinner mcategory;
private ImageView mSelectImage;
private Button mSbtn;
private ProgressDialog mProgress;
private Uri mImageuri = null;
private StorageReference mStorage;
public AddImages() {
// Required empty public constructor
}
// checks if connection has active_internet connection
public static boolean hasInternetAccess(Context context) {
if (isNetworkAvailable(context)) {
try {
HttpURLConnection urlc = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
urlc.setRequestProperty("User-Agent", "Android");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 204 &&
urlc.getContentLength() == 0);
} catch (IOException e) {
Log.e(TAG, "Error checking internet connection", e);
}
} else {
return true;
}
return false;
}
// checks if user is connected to the any network
private static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_add_images, container, false);
mtitle = (EditText) v.findViewById(R.id.edit_title);
mresolution = (EditText) v.findViewById(R.id.edit_resol);
mSelectImage = (ImageView) v.findViewById(R.id.imageView);
mImageType = (EditText) v.findViewById(R.id.edit_image_type);
mprice = (EditText) v.findViewById(R.id.edit_price);
mcategory = (Spinner) v.findViewById(R.id.cat_spin);
mSbtn = (Button) v.findViewById(R.id.submit_btn);
//Initialisee progress dialog
mProgress = new ProgressDialog(getContext());
mProgress.setIndeterminate(true);
mProgress.setMessage("Uploading Please Wait...");
// DB instance
mStorage = FirebaseStorage.getInstance().getReference();
//setting the spinner
adapter = ArrayAdapter.createFromResource(getContext(), R.array.category, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mcategory.setAdapter(adapter);
final String category_value = mcategory.getSelectedItem().toString();
//Image Selection from gallery
mSelectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GALLERY_REQUEST);
}
});
//Posting the activity on the database
mSbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new UploadingTask().execute(category_value);
}
});
return v;
}
// Start adding the images to the DB
private void startAdding(String category_value) {
StorageReference filepath = mStorage.child("My_Images").child(category_value).child(mImageuri.getLastPathSegment());
filepath.putFile(mImageuri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadurl = taskSnapshot.getDownloadUrl();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
mProgress.setMessage(e.getMessage());
mProgress.show();
}
});
}
//show Alert box
private void showAlert(String title, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle(title);
builder.setMessage(message);
builder.setNeutralButton("Dismiss", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
//To show the progress dialog
private void showProgressDialog(boolean shouldShow) {
if (shouldShow) {
mProgress.show();
} else {
mProgress.dismiss();
}
}
// checks if user has entered all the field
#NonNull
private Boolean isFormValid() {
String title_val = mtitle.getText().toString().trim();
String resolution_val = mresolution.getText().toString().trim();
String image_type_val = mImageType.getText().toString().trim();
String price_val = mprice.getText().toString().trim();
String category_value = mcategory.getSelectedItem().toString();
if (!TextUtils.isEmpty(title_val) &&
!TextUtils.isEmpty(resolution_val) &&
!TextUtils.isEmpty(image_type_val) &&
!TextUtils.isEmpty(price_val) &&
mImageuri != null &&
category_value != "Select Category") {
return true;
}
return false;
}
//Reset All the value after uploading the images
private void clearAll() {
mtitle.setText("");
mresolution.setText("");
mprice.setText("");
mImageType.setText("");
mcategory.setSelection(0);
mSelectImage.setImageResource(R.mipmap.add_btn);
}
// Set the selected image from the gallery to the Imageview
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK) {
mImageuri = data.getData();
mSelectImage.setImageURI(mImageuri);
}
}
// perform all the task on the background Thread
class UploadingTask extends AsyncTask<String, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
if (isFormValid()) {
showProgressDialog(true);
} else {
showAlert("Error", "Please fill all the details");
}
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
showProgressDialog(false);
if (aBoolean) {
showAlert("Successful", "Upload complete.");
} else {
showAlert("Failed", "Upload doesn't complete");
}
clearAll();
}
#Override
protected Boolean doInBackground(String... params) {
String catValue = params[0];
if (hasInternetAccess(getContext())) {
showAlert("Error", "Network is not available");
} else {
startAdding(catValue);
}
return null;
}
}
}
Following is the Error I am getting
E/WindowManager: android.view.WindowLeaked: Activity com.example.lenovo.jdstudio.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{42192078 V.E..... R....... 0,0-683,378} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:422)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:250)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:297)
at android.support.v7.app.AlertDialog$Builder.show(AlertDialog.java:958)
at com.example.lenovo.jdstudio.AddImages.showAlert(AddImages.java:173)
at com.example.lenovo.jdstudio.AddImages.access$300(AddImages.java:45)
at com.example.lenovo.jdstudio.AddImages$UploadingTask.onPreExecute(AddImages.java:236)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.example.lenovo.jdstudio.AddImages$2.onClick(AddImages.java:136)
at android.view.View.performClick(View.java:4463)
at android.view.View$PerformClick.run(View.java:18770)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5333)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:828)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:644)
at dalvik.system.NativeStart.main(Native Method)
D/GraphicBuffer: create handle(0x6178f580) (w:688, h:378, f:1)
D/OpenGLRenderer: Flushing caches (mode 0)
D/GraphicBuffer: close handle(0x6177a680) (w:688 h:378 f:1)
D/GraphicBuffer: close handle(0x63688d98) (w:688 h:378 f:1)
D/GraphicBuffer: close handle(0x6178f580) (w:688 h:378 f:1)
D/ActivityThread: ACT-DESTROY_ACTIVITY handled : 1 / android.os.BinderProxy#42190ad0
V/FA: Connection attempt already in progress
D/FA: Connected to remote service
V/FA: Processing queued up service tasks: 2
D/SQLiteDatabase: beginTransaction()
D/SQLiteDatabase: endTransaction()
V/FA: Inactivity, disconnecting from the service
I/Process: Sending signal. PID: 10017 SIG: 9
W/IInputConnectionWrapper: showStatusIcon on inactive InputConnection
Disconnected from the target VM, address: 'localhost:8600', transport: 'socket'
Please Help me out!!
This is a problem I came across when attempting to show a ProgressDialog in onPreExecute() in an AsyncTask. The only solution I found was to manage the dialog outside the task, so instead of
mSbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new UploadingTask().execute(category_value);
}
});
try instead:
mSbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (isFormValid()) {
showProgressDialog(true);
new UploadingTask().execute(category_value);
} else {
showAlert("Error", "Please fill all the details");
}
}
});
And remove the corresponding code from the onPreExecute() method in UploadingTask.
I think the dialog can be dismissed in onPostExecute() without problem, but you could set up a callback interface to the task to notify the caller when the task is complete to allow it to manage the dismissal.
Related
Hi Please help me to resolve this issue I m getting this error
message. The app crashes I have tried almost every solution suggested
on Google
I am creating a Notes application for Android and the logic of the app when it starts is to check if there is a user created and logged in or not. if there is a user created then start MainActivity
if there is no user created login with Anonymous account
package com.russrezepov.mynotes;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.russrezepov.mynotes.auth.Login;
public class Splash extends AppCompatActivity {
private FirebaseAuth fAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
fAuth = FirebaseAuth.getInstance();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (fAuth.getCurrentUser() != null) {
startActivity(new Intent(getApplicationContext(), MainActivity.class));
finish();
} else {
//create a new Anonymous account if a User is not logged in or does not have an account
fAuth.signInAnonymously().addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
Toast.makeText(Splash.this, "Logged in with Temp Account", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),MainActivity.class));
finish();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Splash.this, "Error" + e.getMessage(), Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), Login.class));
finish();
}
});
}
}
}, 1000);
}
}
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.russrezepov.mynotes, PID: 5158
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.russrezepov.mynotes/com.russrezepov.mynotes.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.google.firebase.auth.FirebaseUser.isAnonymous()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3449)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.google.firebase.auth.FirebaseUser.isAnonymous()' on a null object reference
at com.russrezepov.mynotes.MainActivity.onCreate(MainActivity.java:97)
at android.app.Activity.performCreate(Activity.java:8000)
at android.app.Activity.performCreate(Activity.java:7984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3601)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
I/Process: Sending signal. PID: 5158 SIG: 9
Disconnected from the target VM, address: 'localhost:54989', transport: 'socket'
The Error message shows that if (user.isAnonymous()) is where the code below is stops
package com.russrezepov.mynotes;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.firestore.FirestoreRecyclerAdapter;
import com.firebase.ui.firestore.FirestoreRecyclerOptions;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import com.russrezepov.mynotes.auth.Login;
import com.russrezepov.mynotes.auth.Register;
import com.russrezepov.mynotes.model.Note;
import com.russrezepov.mynotes.note.AddNote;
import com.russrezepov.mynotes.note.EditNote;
import com.russrezepov.mynotes.note.TheNoteDetails;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawerLayout;
ActionBarDrawerToggle toggle;
NavigationView nav_view;
RecyclerView noteList;
FloatingActionButton fab;
FirebaseUser user;
FirebaseAuth fAuth;
private FirebaseFirestore fStore;
//private Adapter adapter;
//private NoteAdapter noteAdapter;
final static String TAG = "Firebase Not Reading";
final static String TAGF = "Firebase CONNECTED";
FirestoreRecyclerAdapter<Note,NoteViewHolder> noteAdapter;
//>>>ON CREATE <<<
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Log.i(TAGF,"onCreate");
drawerLayout = findViewById(R.id.drawer);
nav_view = findViewById(R.id.nav_view);
nav_view.setNavigationItemSelectedListener(this);
toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.open, R.string.close);
drawerLayout.addDrawerListener(toggle);
toggle.setDrawerIndicatorEnabled(true);
toggle.syncState();
noteList = findViewById(R.id.noteList);
fab = findViewById(R.id.addNoteFloat);
View headerView = nav_view.getHeaderView(0);
TextView userDisplayName = headerView.findViewById(R.id.userDisplayName);
TextView userDisplayEmail = headerView.findViewById(R.id.userDisplayEmail);
if (user.isAnonymous()) {
userDisplayName.setText("Temporary Account");
userDisplayEmail.setVisibility(View.GONE);
} else {
userDisplayEmail.setText(user.getEmail());
userDisplayName.setText(user.getDisplayName());
}
setUpRecyclerView();
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(view.getContext(), AddNote.class));
overridePendingTransition(R.anim.slide_up,R.anim.slide_down);
finish();
}
});
}
private void setUpRecyclerView() {
fStore = FirebaseFirestore.getInstance();
fAuth = FirebaseAuth.getInstance();
user = fAuth.getCurrentUser();
//query notes=>UID=>MyNotes=>user all notes
Query query = fStore.collection("notes").document(user.getUid()).collection("myNotes").orderBy("title",Query.Direction.DESCENDING);
//executing the query
FirestoreRecyclerOptions<Note> allNotes;
allNotes = new FirestoreRecyclerOptions.Builder<Note>()
.setQuery(query, Note.class)
.build();
// fStore.collection("notes")
// .get()
// .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
// #Override
// public void onComplete(#NonNull Task<QuerySnapshot> task) {
// if (task.isSuccessful()) {
// Log.i(TAGF,"Firebase Connected Successfully");
// for (QueryDocumentSnapshot document : Objects.requireNonNull(task.getResult())) {
// //titles.add(document.getString("title"));
// //content.add(document.getString("content"));
// Log.i(TAGF,document.getString("title"));
// Log.i(TAGF,document.getString("content"));
// Log.i(TAGF,"Firebase Connected Successfully");
// }
// } else {
// Log.w(TAG,"Error getting documents.", task.getException());
// }
// }
// });
noteAdapter = new FirestoreRecyclerAdapter<Note, NoteViewHolder> (allNotes) {
#RequiresApi(api = Build.VERSION_CODES.M)
protected void onBindViewHolder(#NonNull NoteViewHolder noteViewHolder, final int i, #NonNull final Note note) {
//Binding data from MainActivity, when Adapter object is created, to this View that we have here
noteViewHolder.noteTitle.setText(note.getTitle());
noteViewHolder.noteContent.setText(note.getContent());
final int colorCodes = getRandomColor();
noteViewHolder.mCardView.setBackgroundColor(noteViewHolder.view.getResources().getColor(colorCodes,null));
//getting each doc id to be able to update them in EditNote using i as a position in collections
final String docId = noteAdapter.getSnapshots().getSnapshot(i).getId();
noteViewHolder.view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//getting current context where we are starting the Activity and passing them to another activity
Intent i = new Intent(v.getContext(), TheNoteDetails.class);
//When someone clicks on the first item in the RecyclerView it is going to get the position as Zero -> Position
//passing the title and description to the NoteDetails
i.putExtra("title", note.getTitle());
i.putExtra("content", note.getContent());
i.putExtra("color", colorCodes);
i.putExtra("noteId",docId);
v.getContext().startActivity(i); //Not passing anything yet. Just getting current context and passing current context
}
});
//Adding menu Edit & Delete functionality for each Note in Main Activity
ImageView menuIcon = noteViewHolder.view.findViewById(R.id.menuIcon);
menuIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
final String docId = noteAdapter.getSnapshots().getSnapshot(i).getId();
PopupMenu popupMenu = new PopupMenu(v.getContext(),v);
popupMenu.setGravity(Gravity.END);
popupMenu.getMenu().add("Edit").setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
Intent i = new Intent(v.getContext(), EditNote.class);
i.putExtra("title",note.getTitle());
i.putExtra("content",note.getContent());
i.putExtra("noteId",docId);
startActivity(i);
return false;
}
});
popupMenu.getMenu().add("Delete").setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
DocumentReference docRef = fStore.collection("notes").document(user.getUid()).collection("myNotes").document(docId);
docRef.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(MainActivity.this, "Note Deleted", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Error Deleting Note", Toast.LENGTH_SHORT).show();
}
});
return false;
}
});
popupMenu.show();
}
});
}
#NonNull
#Override
public NoteViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.note_view_layout,parent, false);
return new NoteViewHolder(view);
}
};
//Staggered layout expands based on Context Size
noteList.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL));
noteList.setAdapter(noteAdapter);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
drawerLayout.closeDrawer(GravityCompat.START);
switch (item.getItemId()) {
case R.id.addNote:
startActivity(new Intent(this, AddNote.class));
overridePendingTransition(R.anim.slide_up,R.anim.slide_down);
break;
case R.id.sync:
// sending Anonymous users only to Sync Activity aka Register New Account
if (user.isAnonymous()) {
startActivity(new Intent(this, Login.class));
overridePendingTransition(R.anim.slide_up,R.anim.slide_down);
} else {
Toast.makeText(this, "You Are Already Connected", Toast.LENGTH_SHORT).show();
}
break;
case R.id.logout:
checkUser();
break;
default:
Toast.makeText(this, "Coming Soon!", Toast.LENGTH_SHORT).show();
}
return false;
}
private void checkUser() {
//Check if the user is real or Anonymous
if (user.isAnonymous()) {
displayAlert();
} else {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getApplicationContext(), Splash.class));
overridePendingTransition(R.anim.slide_up,R.anim.slide_down);
}
}
private void displayAlert() {
AlertDialog.Builder warnignAlert = new AlertDialog.Builder(this)
.setTitle("Are you sure?")
.setMessage("you are logged in with Temp account. Logging out will delete all unsaved notes")
.setPositiveButton("Sync Note", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(getApplicationContext(), Register.class));
finish();
}
}).setNegativeButton("Logout", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//TODO: delete all the notes created by the anonymous user
// fStore.collection("notes").document(user.getUid()).document()
// fStore.collection("notes").document(user.getUid())
// .delete()
// .addOnSuccessListener(new OnSuccessListener<Void>() {
// #Override
// public void onSuccess(Void aVoid) {
// Log.d(TAG, "Notes successfully deleted!");
// }
// })
// .addOnFailureListener(new OnFailureListener() {
// #Override
// public void onFailure(#NonNull Exception e) {
// Log.w(TAG, "Error deleting Notes", e);
// }
// });
//TODO: delete the anonymous user
user.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
startActivity(new Intent(getApplicationContext(),Splash.class));
overridePendingTransition(R.anim.slide_up,R.anim.slide_down);
}
});
}
});
warnignAlert.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == R.id.settings) {
Toast.makeText(this, "Settings Menu is Clicked!", Toast.LENGTH_SHORT).show();
}
return super.onOptionsItemSelected(item);
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
#Override
protected void onStart() {
super.onStart();
noteAdapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
noteAdapter.stopListening();
}
public static class NoteViewHolder extends RecyclerView.ViewHolder {
TextView noteTitle, noteContent;
View view;
CardView mCardView;
private NoteViewHolder(#NonNull final View itemView) {
super(itemView);
noteTitle = itemView.findViewById(R.id.titles);
noteContent = itemView.findViewById(R.id.content);
mCardView = itemView.findViewById(R.id.noteCard);
view = itemView; //Handles clicks on Recycle View items. Clicks are redirected to the inside of a Note
}
}
private int getRandomColor() {
List<Integer> colorCode = new ArrayList<>();
colorCode.add(R.color.blue);
colorCode.add(R.color.yellow);
colorCode.add(R.color.skyBlue);
colorCode.add(R.color.lightPurple);
colorCode.add(R.color.lightGreen);
colorCode.add(R.color.greenlight);
colorCode.add(R.color.gray);
colorCode.add(R.color.pink);
colorCode.add(R.color.red);
colorCode.add(R.color.notgreen);
Random randomColor = new Random();
int numberColor = randomColor.nextInt(colorCode.size());
return colorCode.get(numberColor);
}
}
You are initializing the user object after accessing it. You are doing it in setUpRecyclerView but accessing it before.
setUpRecyclerView();
if (user.isAnonymous()) {
userDisplayName.setText("Temporary Account");
userDisplayEmail.setVisibility(View.GONE);
} else {
userDisplayEmail.setText(user.getEmail());
userDisplayName.setText(user.getDisplayName());
}
This will make sure you have user object before using it.
Before starting explaining my problem, i'll show you the full image of my error.
I did my best to find the solution and the reason why this error would happen.
I found a few sources such as this or this.
I'm afraid you guys would think that my question is the same as those questions, but I think that there are some differences, so i really hope you guys read my question.
First, I have followed the official chat app tutorial by Google. (this)
and I just copied the source codes, but the error occured on chapter 8(Send Message). And there were no problems when i send the message just with texts, but problem occured when i send the message with image file from my local storage. And i just found the source that says 'In the google firebase this type of StorageException are commonly caused because of wrong StorageReference reference.', so I looked my source codes about StorageReference. But i couldn't understand that answer and I couldn't find any problems.
Second, I showed you more detail about the error message and i'll show you my full source code of MainActivity.
package com.google.firebase.codelab.friendlychat;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Layout;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.firebase.ui.database.SnapshotParser;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.appinvite.AppInvite;
import com.google.android.gms.appinvite.AppInviteInvitation;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.crash.FirebaseCrash;
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.remoteconfig.FirebaseRemoteConfig;
import com.google.firebase.remoteconfig.FirebaseRemoteConfigSettings;
import com.google.firebase.appindexing.Action;
import com.google.firebase.appindexing.FirebaseAppIndex;
import com.google.firebase.appindexing.FirebaseUserActions;
import com.google.firebase.appindexing.Indexable;
import com.google.firebase.appindexing.builders.Indexables;
import com.google.firebase.appindexing.builders.PersonBuilder;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.util.HashMap;
import java.util.Map;
import de.hdodenhof.circleimageview.CircleImageView;
public class MainActivity extends AppCompatActivity
implements GoogleApiClient.OnConnectionFailedListener {
public static class MessageViewHolder extends RecyclerView.ViewHolder {
TextView messageTextView;
ImageView messageImageView;
TextView messengerTextView;
CircleImageView messengerImageView;
public MessageViewHolder(View v) {
super(v);
messageTextView = (TextView) itemView.findViewById(R.id.messageTextView);
messageImageView = (ImageView) itemView.findViewById(R.id.messageImageView);
messengerTextView = (TextView) itemView.findViewById(R.id.messengerTextView);
messengerImageView = (CircleImageView) itemView.findViewById(R.id.messengerImageView);
}
public void bind(FriendlyMessage friendlyMessage){
messageTextView.setText(friendlyMessage.getText());
messageTextView.setVisibility(View.VISIBLE);
messageImageView.setVisibility(View.GONE);
}
}
private static final String TAG = "MainActivity";
public static final String MESSAGES_CHILD = "messages";
private static final int REQUEST_INVITE = 1;
private static final int REQUEST_IMAGE = 2;
private static final String LOADING_IMAGE_URL = "https://www.google.com/images/spin-32.gif";
public static final int DEFAULT_MSG_LENGTH_LIMIT = 10;
public static final String ANONYMOUS = "anonymous";
private static final String MESSAGE_SENT_EVENT = "message_sent";
private String mUsername;
private String mPhotoUrl;
private SharedPreferences mSharedPreferences;
private GoogleApiClient mGoogleApiClient;
private static final String MESSAGE_URL = "http://friendlychat.firebase.google.com/message/";
private Button mSendButton;
private RecyclerView mMessageRecyclerView;
private LinearLayoutManager mLinearLayoutManager;
private ProgressBar mProgressBar;
private EditText mMessageEditText;
private ImageView mAddMessageImageView;
// Firebase instance variables
private FirebaseAuth mFirebaseAuth;
private FirebaseUser mFirebaseUser;
private DatabaseReference mFirebaseDatabaseReference;
private FirebaseRecyclerAdapter<FriendlyMessage, MessageViewHolder> mFirebaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
// Set default username is anonymous.
mUsername = ANONYMOUS;
// Initialize Firebase Auth
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseUser = mFirebaseAuth.getCurrentUser();
if(mFirebaseUser == null){
// Not signed in, launch the Sign In activity
startActivity(new Intent(this, SignInActivity.class));
finish();
return;
}
else {
mUsername = mFirebaseUser.getDisplayName();
if(mFirebaseUser.getPhotoUrl() != null){
mPhotoUrl = mFirebaseUser.getPhotoUrl().toString();
}
}
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */)
.addApi(Auth.GOOGLE_SIGN_IN_API)
.build();
// Initialize ProgressBar and RecyclerView.
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mMessageRecyclerView = (RecyclerView) findViewById(R.id.messageRecyclerView);
mLinearLayoutManager = new LinearLayoutManager(this);
mLinearLayoutManager.setStackFromEnd(true);
// mLinearLayoutManager.setReverseLayout(true);
mMessageRecyclerView.setLayoutManager(mLinearLayoutManager);
mProgressBar.setVisibility(ProgressBar.INVISIBLE);
mMessageEditText = (EditText) findViewById(R.id.messageEditText);
mMessageEditText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(mSharedPreferences
.getInt(CodelabPreferences.FRIENDLY_MSG_LENGTH, DEFAULT_MSG_LENGTH_LIMIT))});
mMessageEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (charSequence.toString().trim().length() > 0) {
mSendButton.setEnabled(true);
} else {
mSendButton.setEnabled(false);
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
mSendButton = (Button) findViewById(R.id.sendButton);
mSendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Send messages on click.
FriendlyMessage friendlyMessage = new FriendlyMessage(mMessageEditText.getText().toString(),
mUsername,
mPhotoUrl,
null);
mFirebaseDatabaseReference.child(MESSAGES_CHILD)
.push().setValue(friendlyMessage);
mMessageEditText.setText("");
}
});
mAddMessageImageView = (ImageView) findViewById(R.id.addMessageImageView);
mAddMessageImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Select image for image message on click.
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, REQUEST_IMAGE);
}
});
// New child entries
mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference();
SnapshotParser<FriendlyMessage> parser = new SnapshotParser<FriendlyMessage>() {
#Override
public FriendlyMessage parseSnapshot(DataSnapshot dataSnapshot) {
FriendlyMessage friendlyMessage = dataSnapshot.getValue(FriendlyMessage.class);
if(friendlyMessage != null){
friendlyMessage.setId(dataSnapshot.getKey());
}
return friendlyMessage;
}
};
DatabaseReference messageRef = mFirebaseDatabaseReference.child(MESSAGES_CHILD);
FirebaseRecyclerOptions<FriendlyMessage> options =
new FirebaseRecyclerOptions.Builder<FriendlyMessage>()
.setQuery(messageRef, parser)
.build();
mFirebaseAdapter = new FirebaseRecyclerAdapter<FriendlyMessage, MessageViewHolder>(options) {
#Override
public MessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
return new MessageViewHolder(inflater.inflate(R.layout.item_message, parent, false));
}
#Override
protected void onBindViewHolder(final MessageViewHolder holder, int position, FriendlyMessage friendlyMessage) {
mProgressBar.setVisibility(View.INVISIBLE);
if(friendlyMessage.getText() != null){
holder.bind(friendlyMessage);
}
else {
String imageUrl = friendlyMessage.getImageUrl();
if(imageUrl.startsWith("gs://")) {
StorageReference storageReference = FirebaseStorage.getInstance()
.getReferenceFromUrl(imageUrl);
storageReference.getDownloadUrl().addOnCompleteListener(
new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if(task.isSuccessful()){
String downloadUrl= task.getResult().toString();
Glide.with(holder.messageImageView.getContext())
.load(downloadUrl)
.into(holder.messageImageView);
}
else {
Log.w(TAG, "Getting download url was not seccessful.",
task.getException());
}
}
}
);
}
else {
Glide.with(holder.messageImageView.getContext())
.load(friendlyMessage.getImageUrl())
.into(holder.messageImageView);
}
holder.messageImageView.setVisibility(ImageView.VISIBLE);
holder.messageTextView.setVisibility(TextView.GONE);
}
holder.messengerTextView.setText(friendlyMessage.getName());
if(friendlyMessage.getPhotoUrl() == null){
holder.messengerImageView.setImageDrawable(ContextCompat.getDrawable(MainActivity.this,
R.drawable.ic_account_circle_black_36dp));
}
else {
Glide.with(MainActivity.this)
.load(friendlyMessage.getPhotoUrl())
.into(holder.messengerImageView);
}
}
};
mFirebaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
#Override
public void onItemRangeInserted(int positionStart, int itemCount) {
super.onItemRangeInserted(positionStart, itemCount);
int friendlyMessageCount = mFirebaseAdapter.getItemCount();
int lastVisiblePosotion =
mLinearLayoutManager.findLastCompletelyVisibleItemPosition();
if(lastVisiblePosotion == -1 ||
(positionStart >= (friendlyMessageCount - 1) && lastVisiblePosotion == (positionStart - 1))){
mMessageRecyclerView.scrollToPosition(positionStart);
}
}
});
mMessageRecyclerView.setAdapter(mFirebaseAdapter);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, "onActivityResult: requestCode=" + requestCode + ", resultCode=" + resultCode);
if (requestCode == REQUEST_IMAGE) {
if (resultCode == RESULT_OK) {
if (data != null) {
final Uri uri = data.getData();
Log.d(TAG, "Uri: " + uri.toString());
FriendlyMessage tempMessage = new FriendlyMessage(null, mUsername, mPhotoUrl,
LOADING_IMAGE_URL);
mFirebaseDatabaseReference.child(MESSAGES_CHILD).push()
.setValue(tempMessage, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError,
DatabaseReference databaseReference) {
if (databaseError == null) {
String key = databaseReference.getKey();
StorageReference storageReference =
FirebaseStorage.getInstance()
.getReference(mFirebaseUser.getUid())
.child(key)
.child( uri.getLastPathSegment());
putImageInStorage(storageReference, uri, key);
} else {
Log.w(TAG, "Unable to write message to database.",
databaseError.toException());
}
}
});
}
}
}
}
private void putImageInStorage(StorageReference storageReference, Uri uri, final String key) {
storageReference.putFile(uri).addOnCompleteListener(MainActivity.this,
new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
FriendlyMessage friendlyMessage =
new FriendlyMessage(null, mUsername, mPhotoUrl,
task.getResult().getMetadata().getDownloadUrl()
.toString());
mFirebaseDatabaseReference.child(MESSAGES_CHILD).child(key)
.setValue(friendlyMessage);
} else {
Log.w(TAG, "Image upload task was not successful.",
task.getException());
}
}
});
}
#Override
public void onStart() {
super.onStart();
// Check if user is signed in.
// TODO: Add code to check if user is signed in.
}
#Override
public void onPause() {
mFirebaseAdapter.stopListening();
super.onPause();
}
#Override
public void onResume() {
super.onResume();
mFirebaseAdapter.startListening();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.sign_out_menu:
mFirebaseAuth.signOut();
Auth.GoogleSignInApi.signOut(mGoogleApiClient);
mUsername = ANONYMOUS;
startActivity(new Intent(this, SignInActivity.class));
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
// An unresolvable error has occurred and Google APIs (including Sign-In) will not
// be available.
Log.d(TAG, "onConnectionFailed:" + connectionResult);
Toast.makeText(this, "Google Play Services error.", Toast.LENGTH_SHORT).show();
}
}
I think I have no problems with Firebase authentication and the intallation or the version of Google Play Service.
Thank you for reading my question.
im unable to retrieve the facebook profile pic:
package com.androidtutorialpoint.flogin.Adapter;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.androidtutorialpoint.flogin.ImageHelper;
import com.androidtutorialpoint.flogin.Model.Post_Song;
import com.androidtutorialpoint.flogin.R;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
/**
* Created by sravya on 19-02-2017.
*/
public class SongPostListAdapter extends BaseAdapter {
private Context context;
private int layout;
private ArrayList<Post_Song> songlist;
public SongPostListAdapter(ArrayList<Post_Song> songlist, int layout, Context context) {
this.songlist = songlist;
this.layout = layout;
this.context = context;
}
#Override
public int getCount() {
return songlist.size();
}
#Override
public Object getItem(int position) {
return songlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder{
TextView name,time,title,artist;
LinearLayout song_pic;
}
ImageView profilePicImageView;
#Override
public View getView(int position, View view, ViewGroup parent) {
View row = view;
ViewHolder holder = new ViewHolder();
if(row ==null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(layout,null);
holder.artist = (TextView)row.findViewById(R.id.artist);
holder.name = (TextView)row.findViewById(R.id.user_name);
holder.time = (TextView)row.findViewById(R.id.time);
holder.title = (TextView)row.findViewById(R.id.song_title);
holder.song_pic = (LinearLayout)row.findViewById(R.id.track_pic);
//holder.userImage =(ImageView) row.findViewById(R.id.user_pic);
profilePicImageView = (ImageView) row.findViewById(R.id.profilePicture);
row.setTag(holder);
}else{
holder = (ViewHolder)row.getTag();
}
Post_Song posts = songlist.get(position);
holder.artist.setText(posts.getArtist());
holder.name.setText(posts.getUname());
holder.time.setText(posts.getTime());
holder.title.setText(posts.getTitle());
new LoadProfileImage(profilePicImageView).execute(posts.getUser_pic());
final ViewHolder finalHolder = holder;
Picasso.with(context).load(posts.getArtwork()).placeholder(R.drawable.music_placeholder).into(new Target(){
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
finalHolder.song_pic.setBackground(new BitmapDrawable(context.getResources(), bitmap));
}
#Override
public void onBitmapFailed(final Drawable errorDrawable) {
Log.d("TAG", "FAILED");
}
#Override
public void onPrepareLoad(final Drawable placeHolderDrawable) {
Log.d("TAG", "Prepare Load");
}
});
return row;
}
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public LoadProfileImage(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... uri) {
String url = uri[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(url).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
if (result != null) {
Bitmap resized = Bitmap.createScaledBitmap(result,90,90, true);
bmImage.setImageBitmap(ImageHelper.getRoundedCornerBitmap(context,resized,100,90,90, false, false, false, false));
}
}
}
}
This is my adaptor. Iam not able to get the profile pic here.
This is my Facebook fragment, here there is no problem with getting the profile pic
package com.androidtutorialpoint.flogin;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.content.Context;
import android.content.SharedPreferences;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookAuthorizationException;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.appevents.AppEventsLogger;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.facebook.share.ShareApi;
import com.facebook.share.Sharer;
import com.facebook.share.model.ShareLinkContent;
import com.facebook.share.model.SharePhoto;
import com.facebook.share.model.SharePhotoContent;
import com.facebook.share.widget.ShareDialog;
import org.json.JSONObject;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
public class FacebookFragment extends Fragment{
DatabaseHelper myDb;
private LoginButton loginButton;
private Button getLibrary;
private Button getShared;
private boolean postingEnabled = false;
private static final String PERMISSION = "publish_actions";
private final String PENDING_ACTION_BUNDLE_KEY =
"com.example.hellofacebook:PendingAction";
//private Button postStatusUpdateButton;
// private Button postPhotoButton;
private ImageView profilePicImageView;
private TextView greeting;
private PendingAction pendingAction = PendingAction.NONE;
private boolean canPresentShareDialog;
private boolean canPresentShareDialogWithPhotos;
private CallbackManager callbackManager;
private ProfileTracker profileTracker;
private ShareDialog shareDialog;
private FacebookCallback<Sharer.Result> shareCallback = new FacebookCallback<Sharer.Result>() {
#Override
public void onCancel() {
Log.d("FacebookFragment", "Canceled");
}
#Override
public void onError(FacebookException error) {
Log.d("FacebookFragment", String.format("Error: %s", error.toString()));
String title = getString(R.string.error);
String alertMessage = error.getMessage();
showResult(title, alertMessage);
}
#Override
public void onSuccess(Sharer.Result result) {
Log.d("FacebookFragment", "Success!");
if (result.getPostId() != null) {
String title = getString(R.string.success);
String id = result.getPostId();
String alertMessage = getString(R.string.successfully_posted_post, id);
showResult(title, alertMessage);
}
}
private void showResult(String title, String alertMessage) {
new AlertDialog.Builder(getActivity())
.setTitle(title)
.setMessage(alertMessage)
.setPositiveButton(R.string.ok, null)
.show();
}
};
private enum PendingAction {
NONE,
POST_PHOTO,
POST_STATUS_UPDATE
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myDb = new DatabaseHelper(getActivity());
FacebookSdk.sdkInitialize(getActivity());
// Other app specific specialization
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_facebook, parent, false);
loginButton = (LoginButton) v.findViewById(R.id.loginButton);
// If using in a fragment
loginButton.setFragment(this);
callbackManager = CallbackManager.Factory.create();
// Callback registration
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Toast toast = Toast.makeText(getActivity(), "Logged In", Toast.LENGTH_SHORT);
postingEnabled = true;
// postPhotoButton.setVisibility(View.VISIBLE);
// postStatusUpdateButton.setVisibility(View.VISIBLE);
getLibrary.setVisibility(View.VISIBLE);
getShared.setVisibility(View.VISIBLE);
toast.show();
handlePendingAction();
updateUI();
}
#Override
public void onCancel() {
// App code
if (pendingAction != PendingAction.NONE) {
showAlert();
pendingAction = PendingAction.NONE;
}
updateUI();
}
#Override
public void onError(FacebookException exception) {
if (pendingAction != PendingAction.NONE
&& exception instanceof FacebookAuthorizationException) {
showAlert();
pendingAction = PendingAction.NONE;
}
updateUI();
}
private void showAlert() {
new AlertDialog.Builder(getActivity())
.setTitle(R.string.cancelled)
.setMessage(R.string.permission_not_granted)
.setPositiveButton(R.string.ok, null)
.show();
}
});
shareDialog = new ShareDialog(this);
shareDialog.registerCallback(
callbackManager,
shareCallback);
if (savedInstanceState != null) {
String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY);
pendingAction = PendingAction.valueOf(name);
}
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
updateUI();
handlePendingAction();
}
};
profilePicImageView = (ImageView) v.findViewById(R.id.profilePicture);
greeting = (TextView) v.findViewById(R.id.greeting);
//postStatusUpdateButton = (Button) v.findViewById(R.id.postStatusUpdateButton);
/*postStatusUpdateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickPostStatusUpdate();
}
});*/
/*postPhotoButton = (Button) v.findViewById(R.id.postPhotoButton);
postPhotoButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickPostPhoto();
}
});*/
getLibrary = (Button) v.findViewById(R.id.getLibraryButton);
getShared = (Button)v.findViewById(R.id.getSharedButton);
getShared.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), SongPostList.class));
}
});
getLibrary.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(), MainActivity.class));
}
});
// Can we present the share dialog for regular links?
canPresentShareDialog = ShareDialog.canShow(
ShareLinkContent.class);
// Can we present the share dialog for photos?
canPresentShareDialogWithPhotos = ShareDialog.canShow(
SharePhotoContent.class);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LoginManager.getInstance().logInWithReadPermissions(getActivity(), Arrays.asList("public_profile"));
if(!postingEnabled) {
postingEnabled = true;
// postPhotoButton.setVisibility(View.VISIBLE);
// postStatusUpdateButton.setVisibility(View.VISIBLE);
getLibrary.setVisibility(View.VISIBLE);
getShared.setVisibility(View.VISIBLE);
}else{
postingEnabled = false;
// postPhotoButton.setVisibility(View.GONE);
//postStatusUpdateButton.setVisibility(View.GONE);
getLibrary.setVisibility(View.GONE);
getShared.setVisibility(View.GONE);
}
// GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
// new GraphRequest.GraphJSONObjectCallback() {
// #Override
// public void onCompleted(
// JSONObject object,
// GraphResponse response) {
// if (object != null) {
// Log.d("Me Request",object.toString());
// Toast t = Toast.makeText(getActivity(), object.toString(), Toast.LENGTH_SHORT);
// t.show();
// }
//
// }
// });
// Bundle parameters = new Bundle();
// parameters.putString("fields", "id,name,link,email");
// request.setParameters(parameters);
// request.executeAsync();
}
});
// loginButton.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
//
// LoginManager.getInstance().logInWithReadPermissions(getActivity(), Arrays.asList("public_profile", "user_friends"));
//
//
//
// }
// });
return v;
}
#Override
public void onResume() {
super.onResume();
// Call the 'activateApp' method to log an app event for use in analytics and advertising
// reporting. Do so in the onResume methods of the primary Activities that an app may be
// launched into.
AppEventsLogger.activateApp(getActivity());
updateUI();
}
#Override
public void onPause() {
super.onPause();
// Call the 'deactivateApp' method to log an app event for use in analytics and advertising
// reporting. Do so in the onPause methods of the primary Activities that an app may be
// launched into.
AppEventsLogger.deactivateApp(getActivity());
}
#Override
public void onDestroy() {
super.onDestroy();
profileTracker.stopTracking();
}
private void updateUI() {
boolean enableButtons = AccessToken.getCurrentAccessToken() != null;
//postStatusUpdateButton.setEnabled(enableButtons || canPresentShareDialog);
//postPhotoButton.setEnabled(enableButtons || canPresentShareDialogWithPhotos);
Profile profile = Profile.getCurrentProfile();
if (enableButtons && profile != null) {
new LoadProfileImage(profilePicImageView).execute(profile.getProfilePictureUri(200, 200).toString());
greeting.setText(getString(R.string.hello_user, profile.getName()));
boolean isInserted =myDb.insertData(profile.getId(),profile.getName(),profile.getProfilePictureUri(200,200).toString());
if(isInserted == true){
Toast.makeText(getActivity(),"Data Inserted",Toast.LENGTH_LONG).show();
SharedPreferences settings = getActivity().getSharedPreferences("mysettings",
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("uid", profile.getId());
editor.putString("name",profile.getName());
editor.putString("pic",profile.getProfilePictureUri(200,200).toString());
editor.commit();
}else{
Toast.makeText(getActivity(),"Not Inserted",Toast.LENGTH_LONG).show();
}
postingEnabled = true;
//postPhotoButton.setVisibility(View.VISIBLE);
//postStatusUpdateButton.setVisibility(View.VISIBLE);
getLibrary.setVisibility(View.VISIBLE);
getShared.setVisibility(View.VISIBLE);
} else {
Bitmap icon = BitmapFactory.decodeResource(getContext().getResources(),R.drawable.user_default);
profilePicImageView.setImageBitmap(ImageHelper.getRoundedCornerBitmap(getContext(), icon, 200, 200, 200, false, false, false, false));
greeting.setText(null);
postingEnabled = false;
// postPhotoButton.setVisibility(View.GONE);
//postStatusUpdateButton.setVisibility(View.GONE);
getLibrary.setVisibility(View.GONE);
getShared.setVisibility(View.GONE);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name());
}
private void handlePendingAction() {
PendingAction previouslyPendingAction = pendingAction;
// These actions may re-set pendingAction if they are still pending, but we assume they
// will succeed.
pendingAction = PendingAction.NONE;
switch (previouslyPendingAction) {
case NONE:
break;
case POST_PHOTO:
postPhoto();
break;
case POST_STATUS_UPDATE:
postStatusUpdate();
break;
}
}
private void onClickPostStatusUpdate() {
performPublish(PendingAction.POST_STATUS_UPDATE, canPresentShareDialog);
}
private void postStatusUpdate() {
Profile profile = Profile.getCurrentProfile();
ShareLinkContent linkContent = new ShareLinkContent.Builder()
.setContentTitle("Integrate Facebook Login to your Android App")
.setContentDescription(
"This app shows how to integrate Facebook Login to your Android App")
.setContentUrl(Uri.parse("http://www.androidtutorialpoint.com/material-design/adding-facebook-login-to-android-app/"))
.build();
if (canPresentShareDialog) {
shareDialog.show(linkContent);
} else if (profile != null && hasPublishPermission()) {
ShareApi.share(linkContent, shareCallback);
} else {
pendingAction = PendingAction.POST_STATUS_UPDATE;
}
}
private void onClickPostPhoto() {
performPublish(PendingAction.POST_PHOTO, canPresentShareDialogWithPhotos);
}
private void postPhoto() {
Bitmap image = BitmapFactory.decodeResource(this.getResources(), R.drawable.androidlogo);
SharePhoto sharePhoto = new SharePhoto.Builder().setBitmap(image).build();
ArrayList<SharePhoto> photos = new ArrayList<>();
photos.add(sharePhoto);
SharePhotoContent sharePhotoContent =
new SharePhotoContent.Builder().setPhotos(photos).build();
if (canPresentShareDialogWithPhotos) {
shareDialog.show(sharePhotoContent);
} else if (hasPublishPermission()) {
ShareApi.share(sharePhotoContent, shareCallback);
} else {
pendingAction = PendingAction.POST_PHOTO;
// We need to get new permissions, then complete the action when we get called back.
LoginManager.getInstance().logInWithPublishPermissions(
this,
Arrays.asList(PERMISSION));
}
}
private boolean hasPublishPermission() {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
return accessToken != null && accessToken.getPermissions().contains("publish_actions");
}
private void performPublish(PendingAction action, boolean allowNoToken) {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
if (accessToken != null || allowNoToken) {
pendingAction = action;
handlePendingAction();
}
}
/**
* Background Async task to load user profile picture from url
* */
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public LoadProfileImage(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... uri) {
String url = uri[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(url).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
if (result != null) {
Bitmap resized = Bitmap.createScaledBitmap(result,200,200, true);
bmImage.setImageBitmap(ImageHelper.getRoundedCornerBitmap(getContext(),resized,250,200,200, false, false, false, false));
}
}
}
}
Please help, iam unable to figure out whats wrong
Instead of downloading the image using a custom class extended from AsyncTask you can load it with Picasso.
Uri image = Profile.getCurrentProfile().getProfilePictureUri(200, 200);
Picasso.with(context).load(image).placeholder(R.drawable.placeholder).into(imageView);
I have made a chat app using this lesson. I have tested it:
Then I closed the app, and opened it some time later. And surprisingly all messages had disappeared:
They appeared back only when I logged out and logged in again.
How to solve that bug?
My code:
MainActivity.java:
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.firebase.ui.auth.AuthUI;
import com.firebase.ui.database.FirebaseListAdapter;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.FirebaseDatabase;
public class MainActivity extends AppCompatActivity {
private static final int SIGN_IN_REQUEST_CODE = 111;
private FirebaseListAdapter<ChatMessage> adapter;
private ListView listView;
private String loggedInUserName = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//find views by Ids
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
final EditText input = (EditText) findViewById(R.id.input);
listView = (ListView) findViewById(R.id.list);
if (FirebaseAuth.getInstance().getCurrentUser() == null) {
// Start sign in/sign up activity
startActivityForResult(AuthUI.getInstance()
.createSignInIntentBuilder()
.build(), SIGN_IN_REQUEST_CODE);
} else {
// User is already signed in, show list of messages
showAllOldMessages();
}
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (input.getText().toString().trim().equals("")) {
Toast.makeText(MainActivity.this, "Please enter some texts!", Toast.LENGTH_SHORT).show();
} else {
FirebaseDatabase.getInstance()
.getReference()
.push()
.setValue(new ChatMessage(input.getText().toString(),
FirebaseAuth.getInstance().getCurrentUser().getDisplayName(),
FirebaseAuth.getInstance().getCurrentUser().getUid())
);
input.setText("");
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_sign_out) {
AuthUI.getInstance().signOut(this)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(MainActivity.this, "You have logged out!", Toast.LENGTH_SHORT).show();
finish();
}
});
}
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SIGN_IN_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Toast.makeText(this, "Signed in successful!", Toast.LENGTH_LONG).show();
showAllOldMessages();
} else {
Toast.makeText(this, "Sign in failed, please try again later", Toast.LENGTH_LONG).show();
// Close the app
finish();
}
}
}
private void showAllOldMessages() {
loggedInUserName = FirebaseAuth.getInstance().getCurrentUser().getUid();
Log.d("Main", "user id: " + loggedInUserName);
adapter = new MessageAdapter(this, ChatMessage.class, R.layout.item_in_message,
FirebaseDatabase.getInstance().getReference());
listView.setAdapter(adapter);
}
public String getLoggedInUserName() {
return loggedInUserName;
}
}
ChatMessage.java:
public class ChatMessage {
private String messageText;
private String messageUser;
private String messageUserId;
public ChatMessage(String messageText, String messageUser, String messageUserId) {
this.messageText = messageText;
this.messageUser = messageUser;
this.messageUserId = messageUserId;
}
public ChatMessage(){
}
public String getMessageUserId() {
return messageUserId;
}
public void setMessageUserId(String messageUserId) {
this.messageUserId = messageUserId;
}
public String getMessageText() {
return messageText;
}
public void setMessageText(String messageText) {
this.messageText = messageText;
}
public String getMessageUser() {
return messageUser;
}
public void setMessageUser(String messageUser) {
this.messageUser = messageUser;
}
}
ChatAdapter.java:
import android.text.format.DateFormat;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseListAdapter;
import com.google.firebase.database.DatabaseReference;
public class MessageAdapter extends FirebaseListAdapter<ChatMessage> {
private MainActivity activity;
public MessageAdapter(MainActivity activity, Class<ChatMessage> modelClass, int modelLayout, DatabaseReference ref) {
super(activity, modelClass, modelLayout, ref);
this.activity = activity;
}
#Override
protected void populateView(View v, ChatMessage model, int position) {
TextView messageText = (TextView) v.findViewById(R.id.message_text);
TextView messageUser = (TextView) v.findViewById(R.id.message_user);
messageText.setText(model.getMessageText());
messageUser.setText(model.getMessageUser());
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
ChatMessage chatMessage = getItem(position);
if (chatMessage.getMessageUserId().equals(activity.getLoggedInUserName()))
view = activity.getLayoutInflater().inflate(R.layout.item_out_message, viewGroup, false);
else
view = activity.getLayoutInflater().inflate(R.layout.item_in_message, viewGroup, false);
//generating view
populateView(view, chatMessage, position);
return view;
}
#Override
public int getViewTypeCount() {
// return the total number of view types. this value should never change
// at runtime
return 2;
}
#Override
public int getItemViewType(int position) {
// return a value between 0 and (getViewTypeCount - 1)
return position % 2;
}
}
P.S I have tried to paste code below into onResume method of MainActivity but nothing good is happening.
if (FirebaseAuth.getInstance().getCurrentUser() == null) {
// Start sign in/sign up activity
startActivityForResult(AuthUI.getInstance()
.createSignInIntentBuilder()
.build(), SIGN_IN_REQUEST_CODE);
} else {
// User is already signed in, show list of messages
showAllOldMessages();
}
P.P.S When I try to send new messages in chat, when there is a bug, I see them. But when I log out and login again, these messages are absent.
Check the logs when you close and re-open the app or if you want a tutorial here's one that uses firebase to create a chat application.
Part-1 https://www.youtube.com/watch?v=wVCz1a3ogqk
Part-2 https://www.youtube.com/watch?v=uX6_w6yhj4E
package com.donateblood.blooddonation;
/**
* Created by YouCaf Iqbal on 4/5/2016.
*/
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class SignupActivity extends AppCompatActivity {
private Spinner mySpinner; private String bloodgroup,name,password,number,location,email;
#InjectView(R.id.input_name) EditText _nameText;
#InjectView(R.id.input_email) EditText _emailText;
#InjectView(R.id.input_password) EditText _passwordText;
#InjectView(R.id.btn_signup) Button _signupButton;
#InjectView(R.id.link_login) TextView _loginLink;
#InjectView(R.id.input_location) TextView _locText;
#InjectView(R.id.input_number) TextView _numText;
DB db; boolean duplicate=false;
DBCursor cursor;
DBCollection collection;
Database dbobj = new Database();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
Spinner spinner =(Spinner) findViewById(R.id.spinner);
String[] list = getResources().getStringArray(R.array.blood_type);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.spinner_layout,R.id.txt,list);
spinner.setAdapter(adapter);
ButterKnife.inject(this);
_signupButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signup();
}
});
_loginLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Finish the registration screen and return to the Login activity
finish();
}
});
}
public void signup() {
if (validate()==false) {
onSignupFailed();
return;
}
if(CheckEmailDuplicate()){
Toast.makeText(getBaseContext(), "Account with this Email already exists", Toast.LENGTH_LONG).show();
return;
}
_signupButton.setEnabled(false);
dbAsync signupThread = new dbAsync();
signupThread.execute();
}
public void onSignupSuccess() {
_signupButton.setEnabled(true);
setResult(RESULT_OK, null);
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
finish();
}
public void onSignupFailed() {
Toast.makeText(getBaseContext(), "Sign Up failed", Toast.LENGTH_LONG).show();
_signupButton.setEnabled(true);
}
public boolean validate() {
boolean valid = true;
GetUserDetails();
if (name.isEmpty() || name.length() < 3) {
_nameText.setError("at least 3 characters");
valid = false;
} else {
_nameText.setError(null);
}
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
_emailText.setError("Enter a valid email address");
valid = false;
} else {
_emailText.setError(null);
}
if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
_passwordText.setError("between 4 and 10 alphanumeric characters");
valid = false;
} else {
_passwordText.setError(null);
}
if (location.isEmpty()) {
_locText.setError("Enter location");
valid = false;
} else {
_locText.setError(null);
}
if (number.isEmpty()) {
_numText.setError("Enter valid number");
valid = false;
} else {
_numText.setError(null);
}
return valid;
}
public class dbAsync extends AsyncTask<Void,Void,Void> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SignupActivity.this);
pDialog.setMessage("Creating Account");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
GetUserDetails();
dbobj.insertUser(name,email,password,location,number,bloodgroup);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pDialog.dismiss();
Toast.makeText(getBaseContext(), "Created Successfully", Toast.LENGTH_LONG).show();
onSignupSuccess();
}
}
public void GetUserDetails(){
mySpinner=(Spinner) findViewById(R.id.spinner);
bloodgroup = mySpinner.getSelectedItem().toString();
name = _nameText.getText().toString();
email = _emailText.getText().toString();
password = _passwordText.getText().toString();
location = _locText.getText().toString();
number = _numText.getText().toString();
}
public boolean CheckEmailDuplicate(){
email = _emailText.getText().toString();
db = dbobj.getconnection();
collection= db.getCollection("UserDetails");
BasicDBObject query = new BasicDBObject();
query.put("email", email);
cursor = collection.find(query);
if(cursor.hasNext()){
duplicate=true;
}
return duplicate;
}
}
I do not know what to do. I am new to android development and i am using mongodb as my database. How can i solve this time out exception to get my code working. I tried out searched for this issue but did not find a simple and good descriptive solution. Help will be appreciated. Thanks in advance.
The error is time out error. If you look into the detail error log.
You get exception unknown host name ds015730.mlab.com:15730
Please the timeout error is due to the wrong hostname. Please check your host name.
Time Out error is occur when user request to the server but server is
not responding within time then that request throws time out error.
In your case issue is due to the wrong hostname.