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.
Related
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.
I was learning to make a simple login app from youtube, however, when I build the code, although the app runs quite fine but it never assigns the value of 3 to the attempt counter later in the code, only the layout is visible and hence login doesn't work. Can you please help me? If you need any other file, write it in comment, I'll upload it later. Thanks.
package com.shubham.splashscreenemulation;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class UserLogin extends AppCompatActivity {
private static EditText username;
private static EditText password;
private static TextView attempts_left;
private static Button login_btn;
int attempt_counter = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_login);
}
public void LoginButton(){
username = (EditText)findViewById(R.id.editText_user);
password = (EditText)findViewById(R.id.editText_password);
attempts_left = (TextView)findViewById(R.id.textView_attempt_count);
login_btn = (Button)findViewById(R.id.button_login);
attempts_left.setText(Integer.toString(attempt_counter));
login_btn.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v){
if(username.getText().toString().equals("Shubh") && password.getText().toString().equals("adidev"))
{
Toast.makeText(UserLogin.this, "Login credentials are correct!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent("com.shubham.splashscreenemulation.SplashScreen");
startActivity(intent);
}
else
{
Toast.makeText(UserLogin.this, "Login credentials are not correct!", Toast.LENGTH_SHORT).show();
attempt_counter--;
attempts_left.setText(Integer.toString(attempt_counter));
if(attempt_counter == 0)
{
login_btn.setEnabled(false);
}
}
}
}
);
}
}
You don't call the function LoginButton() in your Activity.
Here some tips : function name starts with lowercase letter like loginButton ( with camelCase ), classes names starts with uppercase letter like AppCompatActivity. This tip is for more readability for the code. Why do you declare Views as static in that function?
package com.shubham.splashscreenemulation;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class UserLogin extends AppCompatActivity {
private static EditText username;
private static EditText password;
private static TextView attempts_left;
private static Button login_btn;
int attempt_counter = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_login);
LoginButton();
}
public void LoginButton(){
username = (EditText)findViewById(R.id.editText_user);
password = (EditText)findViewById(R.id.editText_password);
attempts_left = (TextView)findViewById(R.id.textView_attempt_count);
login_btn = (Button)findViewById(R.id.button_login);
attempts_left.setText(Integer.toString(attempt_counter));
login_btn.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v){
if(username.getText().toString().equals("Shubh") && password.getText().toString().equals("adidev"))
{
Toast.makeText(UserLogin.this, "Login credentials are correct!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent("com.shubham.splashscreenemulation.SplashScreen");
startActivity(intent);
}
else
{
Toast.makeText(UserLogin.this, "Login credentials are not correct!", Toast.LENGTH_SHORT).show();
attempt_counter--;
attempts_left.setText(Integer.toString(attempt_counter));
if(attempt_counter == 0)
{
login_btn.setEnabled(false);
}
}
}
}
);
}
You can add LoginButton() after setContentView or remove the LoginButton method, move everything inside onCreate.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_login);
username = (EditText)findViewById(R.id.editText_user);
password = (EditText)findViewById(R.id.editText_password);
attempts_left = (TextView)findViewById(R.id.textView_attempt_count);
login_btn = (Button)findViewById(R.id.button_login);
attempts_left.setText(Integer.toString(attempt_counter));
login_btn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if(username.getText().toString().equals("Shubh") && password.getText().toString().equals("adidev"))
{
Toast.makeText(UserLogin.this, "Login credentials are correct!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent("com.shubham.splashscreenemulation.SplashScreen");
startActivity(intent);
}
else
{
Toast.makeText(UserLogin.this, "Login credentials are not correct!", Toast.LENGTH_SHORT).show();
attempt_counter--; attempts_left.setText(Integer.toString(attempt_counter));
if(attempt_counter == 0)
{
login_btn.setEnabled(false);
}
}
}
});
}
You can also change your setText to this attempts_left.setText(attempt_counter+"");
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
I am creating user sign up application with parse. when I fill edit field and press signup button a toast message show that invalid token session.I have filled all filed.How can i resolve this problem.Here below is my code
package com.example.home.communicate
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.parse.ParseException;
import com.parse.ParseUser;
import com.parse.SignUpCallback;
public class SignupActivity extends AppCompatActivity {
EditText editusername, editpassword, editemail, editrepassword;
Button signup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
editusername = (EditText) findViewById(R.id.usernamesignup);
editemail = (EditText) findViewById(R.id.email);
editpassword = (EditText) findViewById(R.id.passwordinsignup);
editrepassword = (EditText) findViewById(R.id.re_enterpassword);
signup = (Button) findViewById(R.id.signup);
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
userSignUp();
}
});
}
private void userSignUp() {
String username = editusername.getText().toString().trim();
String email = editemail.getText().toString().trim();
String password = editpassword.getText().toString().trim();
String repassword = editrepassword.getText().toString().trim();
boolean validationError = false;
StringBuilder validationErrorMessage = new StringBuilder(getString(R.string.error_intro));
if (username.length() == 0) {
validationError = true;
validationErrorMessage.append(getString(R.string.error_blank_username));
}
if (password.length()== 0){
if(validationError){
validationErrorMessage.append(getString(R.string.error_join));
}
validationError = true;
validationErrorMessage.append(getString(R.string.error_blank_password));
}
if(!password.equals(repassword)){
if(validationError){
validationErrorMessage.append(getString(R.string.error_join));
}
validationError = true;
validationErrorMessage.append(getString(R.string.error_mismatched_passwords));
}
if (email.length()== 0){
if(validationError){
validationErrorMessage.append(getString(R.string.error_join));
}
validationError = true;
validationErrorMessage.append(getString(R.string.error_blank_email));
}
if(validationError){
Toast.makeText(SignupActivity.this, validationErrorMessage.toString(),Toast.LENGTH_SHORT).show();
}
ParseUser user = new ParseUser();
user.setUsername(username);
user.setEmail(email);
user.setPassword(password);
user.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
if (e==null){
Intent intent = new Intent(SignupActivity.this,MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else {
Toast.makeText(SignupActivity.this,e.getMessage(),Toast.LENGTH_LONG).show();
}
}
});
}
}
This could potentially happen when your current user is not completely logged out. Make sure to do a check on your current user and logout before signing up a new user.
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser != null) {
ParseUser.logOut();
}
I try to start a new fragment from my fragmentActivity, but every time I try it, it comes up with a error, that tells me : Activity has been destroyed.
Source code from a tabController i've created:
package com.crosscommunications.kvodeventer;
import java.io.File;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
public class TabControllerMeldingen extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabcontroller);
final File f = new File("/data/data/com.crosscommunications.kvodeventer/files/data.txt");
if (f.exists()) {
System.out.println("File existed");
addFragment(new KVOCards(), false, FragmentTransaction.TRANSIT_NONE);
} else {
System.out.println("File not found!");
addFragment(new KVOMeldingen(), false, FragmentTransaction.TRANSIT_NONE);
}
}
public void addFragment(Fragment fragment, boolean addToBackStack, int transition) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.simple_fragment, fragment);
ft.setTransition(transition);
if (addToBackStack)
ft.addToBackStack(null);
ft.commit();
}
public void finishFragmentOrActivity(View v) {
FragmentManager manager = getSupportFragmentManager();
if (manager.getBackStackEntryCount() > 0)
getSupportFragmentManager().popBackStack();
else
finish();
}
public void launchNewFragment(View v) {
addFragment(new KVOOver(), true, FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
}
}
This code opens the KVOMeldingen class in most cases. So source of KVOMeldingen is:
package com.crosscommunications.kvodeventer;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class KVOMeldingen extends Fragment {
static String Username;
static String Password;
static String LoginResult;
static String LoginOk = "vet";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View fragmentView = inflater.inflate(R.layout.kvomeldingen, container, false);
final EditText etUsername = (EditText) fragmentView.findViewById(R.id.etUsername);
final EditText etPassword = (EditText) fragmentView.findViewById(R.id.etPassword);
Button bLogin = (Button) fragmentView.findViewById(R.id.bLogin);
Button bCreateAccount = (Button) fragmentView.findViewById(R.id.bCreateAccount);
Button bResetPassword = (Button) fragmentView.findViewById(R.id.bResetPassword);
bLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (etUsername.length() <= 0) {
etUsername.setError("Veld mag niet leeg zijn");
} else if (etPassword.length() <= 0) {
etPassword.setError("Veld mag niet leeg zijn");
} else {
Username = etUsername.getText().toString();
Password = etPassword.getText().toString();
}
LoginTask NDLT = new LoginTask();
NDLT.execute();
}
});
bCreateAccount.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (etUsername.length() <= 0) {
etUsername.setError("Veld mag niet leeg zijn");
} else if (etPassword.length() <= 0) {
etPassword.setError("Veld mag niet leeg zijn");
} else {
Username = etUsername.getText().toString();
Password = etPassword.getText().toString();
}
RegisterTask RegTask = new RegisterTask();
RegTask.execute();
}
});
bResetPassword.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (etUsername.length() <= 0) {
etUsername.setError("Veld mag niet leeg zijn");
} else if (etPassword.length() <= 0) {
etPassword.setError("Veld mag niet leeg zijn");
} else {
Username = etUsername.getText().toString();
Password = etPassword.getText().toString();
}
ForgotTask forgTask = new ForgotTask();
forgTask.execute();
}
});
return fragmentView;
}
class LoginTask extends AsyncTask<Void, Void, JSONObject> {
ProgressDialog waitingDialog;
#Override
protected void onPreExecute() {
waitingDialog = new ProgressDialog(getActivity());
waitingDialog.setMessage("Laden...");
waitingDialog.show();
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(Void... params) {
JSONObject json = JsonFunctions
.getJsonLoginResult("http://api.crossalertdeventer.nl/login.json");
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
super.onPostExecute(json);
if (waitingDialog.isShowing()) {
waitingDialog.dismiss();
}
try {
LoginResult = json.getString("login");
Log.d("LoginResult", LoginResult);
if (LoginResult.equals("success")) {
WriteSettings(getActivity(), Username, Password,
"data.txt");
TabControllerMeldingen newFragment = new TabControllerMeldingen();
newFragment.addFragment(new KVOCards(), false, FragmentTransaction.TRANSIT_NONE);
} else if (LoginResult.equals("failed")) {
final AlertDialog alertDialog = new AlertDialog.Builder(
getActivity()).create();
alertDialog.setTitle("Fout");
alertDialog
.setMessage("Gebruikersnaam of wachtwoord incorrect");
alertDialog.setButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
alertDialog.dismiss();
}
});
alertDialog.show();
}
} catch (Exception e) {
Log.e("KVOMeldingen", "error" + e.getMessage());
}
}
}
This source is actually bigger than this (i've cut it in half).
But you see in the AsyncTask, i try to call the method from the TabControllerMeldingen class to add a new fragment. When this method get's called, the app crashes
I've read on another thread on stackoverflow that it has to do something with the Super Oncreate method, but I can't figure out exactly what is going wrong.
Can anybody help me with this..? it's really important for me to understand this, because i believe fragments is the way to go basically these days.
You can't do this:
TabControllerMeldingen newFragment = new TabControllerMeldingen();
All activities have to be created through the framework. However, you are already inside one (you use the getActivity() method), so you need to do the same in this case. Get the activity and add the fragment on that.