android studio FirebaseAuth (IllegalArgumentException: Given String is empty or null) - firebase

im working on my first project
i used FirebaseAuth and firebase realtime database
i followed every step carefully at first everything is alright and my project has connect to the db successfully(two weeks ago) i had even test my db , but after i update my android studio version something went wrong :(
my app keep crash every time i click on the buttons.
i really don't know what is the problem? before everything was alright
"i read articles about the api-key and i checked it there is nothing wrong with it"
here is my register code :
package com.example.lastone;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.santalu.maskedittext.MaskEditText;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.view.View;
import android.widget.Toast;
import com.basgeekball.awesomevalidation.AwesomeValidation;
import com.basgeekball.awesomevalidation.ValidationStyle;
import com.basgeekball.awesomevalidation.utility.RegexTemplate;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class Register2 extends AppCompatActivity {
MaskEditText license,phone;
private EditText email,pass1,pass2;
private Button but;
AwesomeValidation awesomeValidation;
private FirebaseDatabase rootNode;
//realtime
DatabaseReference reference;
//authinicate
private FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register2);
//validation
awesomeValidation=new AwesomeValidation(ValidationStyle.BASIC);
updateUI();
//authinication
firebaseAuth= FirebaseAuth.getInstance();
}
private void updateUI() {
license=findViewById(R.id.license);
email=(EditText)findViewById(R.id.email);
phone=findViewById(R.id.phone);
pass1=(EditText)findViewById(R.id.pass1);
pass2=(EditText)findViewById(R.id.pass2);
but=(Button)findViewById(R.id.but);
String regexPassword = "(?=.*[a-z])(?=.*[A-Z])(?=.*[\\d])(?=.*[~`!##\\$%\\^&\\*\\(\\)\\-_\\+=\\{\\}\\[\\]\\|\\;:\"<>,./\\?]).{8,}";
String Regex = ("[0-9]{10}");
awesomeValidation.addValidation(Register2.this,R.id.license, Regex, R.string.licensee);
awesomeValidation.addValidation(Register2.this,R.id.email,android.util.Patterns.EMAIL_ADDRESS, R.string.emailrr);
awesomeValidation.addValidation(Register2.this,R.id.phone, RegexTemplate.TELEPHONE, R.string.phonen);
awesomeValidation.addValidation(Register2.this,R.id.pass1,regexPassword,R.string.pass11);
awesomeValidation.addValidation(Register2.this,R.id.pass2,R.id.pass1,R.string.pass22);
but.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
signUp();
// send to the database
rootNode= FirebaseDatabase.getInstance();
reference=rootNode.getReference("users");
//get all the values from the textfield
String License =license.getText().toString();
String Phone_number =phone.getText().toString();
String Email =email.getText().toString();
String password =pass1.getText().toString();
UserHelperClass helper=new UserHelperClass(License , Phone_number, Email, password);
reference.child(License).setValue(helper);
//validate
if(awesomeValidation.validate())
{
Toast.makeText(Register2.this, "Data Received Successfully", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(Register2.this, "Error", Toast.LENGTH_SHORT).show();
}
});
}
private void signUp() {
firebaseAuth.createUserWithEmailAndPassword(email.getText().toString(), pass1.getText().toString())
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
FirebaseUser user = firebaseAuth.getCurrentUser();
String email=user.getEmail();
String name=user.getDisplayName();
Toast.makeText(Register2.this, "Name : "+name+"\n"+"Email : "+email,
Toast.LENGTH_SHORT).show();
Intent intent=new Intent(Register2.this,Login.class);
startActivity(intent);
} else {
// If sign in fails, display a message to the user.
Toast.makeText(Register2.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
// updateUI(null);
}
// ...
}
});
}
}
login code:
package com.example.lastone;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
public class Login extends AppCompatActivity
{
private EditText email,pass;
private Button lo;
private FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
email=(EditText)findViewById(R.id.email);
pass=(EditText)findViewById(R.id.pass);
lo=(Button)findViewById(R.id.lo);
firebaseAuth= FirebaseAuth.getInstance();
lo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Signin();
}
});
}
private void Signin()
{
firebaseAuth.signInWithEmailAndPassword(email.getText().toString(), pass.getText().toString())
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
FirebaseUser user = firebaseAuth.getCurrentUser();
String email=user.getEmail();
String name=user.getDisplayName();
Toast.makeText(Login.this,"Logged in successuly",
Toast.LENGTH_SHORT).show();
} else {
// If sign in fails, display a message to the user.
Toast.makeText(Login.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
// Intent intent=new Intent(Login.this,profile.class);
}
}
});
}
}
error:
2020-04-04 02:25:41.923 7642-7642/com.example.lastone E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.lastone, PID: 7642
java.lang.IllegalArgumentException: Given String is empty or null
at com.google.android.gms.common.internal.Preconditions.checkNotEmpty(Unknown Source)
at com.google.firebase.auth.FirebaseAuth.signInWithEmailAndPassword(com.google.firebase:firebase-auth##19.3.0:205)
at com.example.lastone.Login.Signin(Login.java:53)
at com.example.lastone.Login.access$000(Login.java:27)
at com.example.lastone.Login$1.onClick(Login.java:46)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
also build gradle :
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
android {
compileSdkVersion 29
buildToolsVersion "29.0.3"
defaultConfig {
applicationId "com.example.lastone"
minSdkVersion 16
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'com.basgeekball:awesome-validation:4.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.firebase:firebase-database:19.2.1'
implementation 'com.google.firebase:firebase-auth:19.3.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'com.github.santalu:mask-edittext:1.0.2'
}
the deadline is on this week please help :((

Add these dependencies and run your your projet again
implementation 'com.google.firebase:firebase-analytics:17.2.3'
implementation 'com.google.firebase:firebase-core:17.2.3'

Related

Custom URL in push notifiactions - FCM

I have a WebView application, with firebase cloud Firebase Cloud Messaging for push notifications.I want that clicking on a notification to open a URL in my WebView, and not the main page of the default site in my app.I need it to be a different URL on every notification that I send through FCM each time.I searched a lot on Google and found all kinds of answers. But in practice it doesn't work.
for exmaple, Android Push Notification URL
.... thank you!
my code:
MainActivity.java
`
package com.webview.myapplication;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.webkit.CookieManager;
import android.webkit.URLUtil;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends Activity {
private final int STORAGE_PERMISSION_CODE = 1;
private WebView mWebView;
public void notifyParse(){
if (getIntent().getExtras() != null) {
if (getIntent().getStringExtra("LINK")!=null) {
Intent i=new Intent(this,urlFromNotify.class);
i.putExtra("link",getIntent().getStringExtra("LINK"));
MainActivity.this.startActivity(i);
finish();
}
}
}
private void requestStoragePermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
new AlertDialog.Builder(this)
.setTitle("Permission needed")
.setMessage("This permission is needed to download files")
.setPositiveButton("ok", (dialog, which) -> ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE))
.setNegativeButton("cancel", (dialog, which) -> dialog.dismiss())
.create().show();
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
}
#RequiresApi(api = Build.VERSION_CODES.Q)
#Override
#SuppressLint("SetJavaScriptEnabled")
protected void onCreate(Bundle savedInstanceState) {
requestStoragePermission();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = findViewById(R.id.activity_main_webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.setWebViewClient(new HelloWebViewClient());
mWebView.setDownloadListener((url, userAgent, contentDisposition, mimeType, contentLength) -> {
Uri source = Uri.parse(url);
DownloadManager.Request request = new DownloadManager.Request(source);
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie", cookies);
request.addRequestHeader("User-Agent", userAgent);
request.setDescription("Downloading File...");
request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, mimeType));
DownloadManager dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(this, R.string.downloading, Toast.LENGTH_LONG).show();
});
mWebView.loadUrl("https://noam.org.il"); //Replace The Link Here
}
#Override
public void onBackPressed() {
if (mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
// checking if URL is allowed
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(final WebView view, final String url)
{
view.loadUrl(url);
return true;
}
}
}
`
FirebaseMessageReceiver.java
`
package com.webview.myapplication;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.widget.RemoteViews;
import androidx.core.app.NotificationCompat;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class FirebaseMessageReceiver
extends FirebaseMessagingService {
Bitmap bitmap;
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
String message = remoteMessage.getData().get("message");
//imageUri will contain URL of the image to be displayed with Notification
String imageUri = remoteMessage.getData().get("image");
String link=remoteMessage.getData().get("link");
//To get a Bitmap image from the URL received
bitmap = getBitmapfromUrl(imageUri);
sendNotification(message, bitmap,link);
}
/**
* Create and show a simple notification containing the received FCM message.
*/
private void sendNotification(String messageBody, Bitmap image, String link) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("LINK",link);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setLargeIcon(image)/*Notification icon image*/
.setSmallIcon(R.drawable.gfg)
.setContentTitle(messageBody)
.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(image))/*Notification with Image*/
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
public Bitmap getBitmapfromUrl(String imageUrl) {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
return bitmap;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}}
`
urlFromNotify.java
`
package com.webview.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.webkit.WebView;
public class urlFromNotify extends AppCompatActivity {
void urlOpen(){
WebView webView = (WebView) findViewById(R.id.activity_main_webview);
Intent i = getIntent();
String url = i.getStringExtra("link");
webView.loadUrl(url);
}
}
`

Unable to fetch data from Firebase in Android Studio but able to save it

I am making my first app using Firebase. I am unable to fetch data from Firebase in Android Studio but I was able to upload it using login and sign up features which I created in my app.
Whenever I run the app, it does not show any error but app automatically closes after the splash screen. I am unable to resolve this error.
MainActivity.java
package com.example.blooddonationapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.google.android.material.navigation.NavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import de.hdodenhof.circleimageview.CircleImageView;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener{
private DrawerLayout drawerLayout;
private Toolbar toolbar;
private NavigationView nav_view;
private CircleImageView nav_profile_image;
private TextView nav_fullname, nav_email, nav_bloodgroup, nav_type;
private DatabaseReference userRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Blood Donation App");
drawerLayout = findViewById(R.id.drawerLayout);
nav_view = findViewById(R.id.nav_view);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(MainActivity.this, drawerLayout, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
nav_view.setNavigationItemSelectedListener(this);
nav_profile_image = nav_view.getHeaderView(0).findViewById(R.id.nav_user_image);
nav_fullname = nav_view.getHeaderView(0).findViewById(R.id.nav_user_fullname);
nav_email = nav_view.getHeaderView(0).findViewById(R.id.nav_user_email);
nav_bloodgroup = nav_view.getHeaderView(0).findViewById(R.id.nav_user_bloodgroup);
nav_type = nav_view.getHeaderView(0).findViewById(R.id.nav_user_type);
userRef = FirebaseDatabase.getInstance().getReference().child("users").child(
FirebaseAuth.getInstance().getCurrentUser().getUid()
);
userRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
String name = snapshot.child("name").getValue().toString();
nav_fullname.setText(name);
String email = snapshot.child("email").getValue().toString();
nav_email.setText(email);
String bloodgroup = snapshot.child("bloodgroup").getValue().toString();
nav_bloodgroup.setText(bloodgroup);
String type = snapshot.child("type").getValue().toString();
nav_type.setText(type);
String imageUrl = snapshot.child("profilepictureurl").getValue().toString();
Glide.with(getApplicationContext()).load(imageUrl).into(nav_profile_image);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.profile:
Intent intent = new Intent(MainActivity.this, ProfileActivity.class);
startActivity(intent);
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
}
ProfileActivity.java
package com.example.blooddonationapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.widget.Toolbar;
import com.bumptech.glide.Glide;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import de.hdodenhof.circleimageview.CircleImageView;
public class ProfileActivity extends AppCompatActivity {
private Toolbar toolbar;
private TextView type, name, email, idNumber, phoneNumber, bloodGroup;
private CircleImageView profileImage;
private Button backButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("My Profile");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
type = findViewById(R.id.type);
name = findViewById(R.id.name);
email = findViewById(R.id.email);
idNumber = findViewById(R.id.idNumber);
phoneNumber = findViewById(R.id.phoneNumber);
bloodGroup = findViewById(R.id.bloodGroup);
profileImage = findViewById(R.id.profileImage);
backButton = findViewById(R.id.backButton);
DatabaseReference reference = FirebaseDatabase.getInstance().getReference()
.child("users").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
type.setText(snapshot.child("type").getValue().toString());
name.setText(snapshot.child("name").getValue().toString());
idNumber.setText(snapshot.child("idnumber").getValue().toString());
phoneNumber.setText(snapshot.child("phonenumber").getValue().toString());
bloodGroup.setText(snapshot.child("bloodgroup").getValue().toString());
email.setText(snapshot.child("email").getValue().toString());
Glide.with(getApplicationContext()).load(snapshot.child("profilepictureurl").getValue().toString()).into(profileImage);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(ProfileActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
});
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Firebase
LogCat

Android upload to Firebase Bucket with SchedulerAPI

Background:
I am using Firebase for my Android App Development This app require every user upload an object from their phone to the bucket/ Firebase Storage once a day. So, I want to make the process of "object upload" as a background service with JobSchedulerAPI.
I have copied source code from Firebase and a youtube video related to Job Scheduler. But when I clicked the button, the app stopped immediately.
MainActivity.Java
package com.scheduleupload;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
final ComponentName mComponentName = new ComponentName(this, Scheduler.class);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
JobInfo info = new JobInfo.Builder(123, mComponentName)
.setPeriodic(15 * 60 * 1000)
.build();
JobScheduler scheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
int resultCode = scheduler.schedule(info);
if (resultCode == JobScheduler.RESULT_SUCCESS) {
Log.d(TAG, "Job scheduled");
} else {
Log.d(TAG, "Job scheduling failed");
}
}
});
}
}
Scheduler.Java
package com.scheduleupload;
import android.app.job.JobParameters;
import android.app.job.JobService;
import android.net.Uri;
import android.util.Log;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
public class Scheduler extends JobService {
private static final String TAG = "ExampleJobService";
private boolean jobCancelled =false;
private StorageReference mStorage;
mStorage = FirebaseStorage.getInstance().getReference();
String myUri = "content://com.google.android.apps.docs.storage/document/acc%3D1%3Bdoc%3D693";
final Uri uri = Uri.parse(myUri);
StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment());
#Override
public boolean onStartJob(JobParameters params) {
Log.d(TAG, "Job Started");
doBackgroundWork(params);
return true;
}
private void doBackgroundWork(JobParameters params) {
new Thread(new Runnable() {
#Override
public void run() {
filepath.putFile(uri);
}
}).start();
}
#Override
public boolean onStopJob(JobParameters params) {
return true;
}
}
Thx a lot for spending such a long while to read my question
crash log:
05-07 21:53:52.775 6261-6261/com.scheduleupload E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.scheduleupload, PID: 6261
java.lang.IllegalArgumentException: No such service ComponentInfo{com.scheduleupload/com.scheduleupload.Scheduler}
at android.os.Parcel.readException(Parcel.java:2008)
at android.os.Parcel.readException(Parcel.java:1950)
at android.app.job.IJobScheduler$Stub$Proxy.schedule(IJobScheduler.java:180)
at android.app.JobSchedulerImpl.schedule(JobSchedulerImpl.java:44)
at com.scheduleupload.MainActivity$1.onClick(MainActivity.java:35)
at android.view.View.performClick(View.java:6294)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Have found solution, it is because the Scheduler can't access to some of the storage. Simply change to file location to somewhere it is accessible by Job Scheduler can solve the problem

App crashes on clicking on textView in fragment

I'm creating an app in which there are three tab activity.In tab Three i have a textview name as login text whenever user click on this text a new activity should be opened but app crashes when we click on this.
I have done many research to resolve this problem but i'm unable to resolve at last i'm here for the solution of my problem Please help.
Thanks in advance.
This is my loginActivity.
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class loginActivity extends AppCompatActivity implements View.OnClickListener {
private EditText email_Id;
private EditText password;
private TextView sign_Up;
private Button sign_In;
private ProgressDialog progressDialog;
private FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
firebaseAuth=FirebaseAuth.getInstance();
// if(firebaseAuth.getCurrentUser()!=null){
// directly start user profile activity
// finish();
// startActivity(new Intent(this,userProfileActivity.class));
//}
progressDialog=new ProgressDialog(this);
email_Id=(EditText)findViewById(R.id.email_id);
password=(EditText)findViewById(R.id.password);
sign_In=(Button)findViewById(R.id.sign_In);
sign_Up=(TextView)findViewById(R.id.sign_up);
sign_In.setOnClickListener(this);
sign_Up.setOnClickListener(this);
}
private void user_Login(){
String email=email_Id.getText().toString().trim();
String pass_word=password.getText().toString().trim();
if(TextUtils.isEmpty(email)){
// email is empty
Toast.makeText(this,"please enter email",Toast.LENGTH_SHORT).show();
return;// to stop the function from executation.
}
if(TextUtils.isEmpty(pass_word)){
// email is empty
Toast.makeText(this,"please enter password",Toast.LENGTH_SHORT).show();
return;
}
// here if everything ok the user will be register
progressDialog.setMessage("Registering User,please wait...");
progressDialog.show();
firebaseAuth.signInWithEmailAndPassword(email,pass_word)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressDialog.dismiss();
if (task.isSuccessful()){
// start user profile activity
finish();
startActivity(new Intent(getApplicationContext(),userProfileActivity.class));
}
}
});
}
#Override
public void onClick(View view) {
if (view==sign_In){
// start user profile activity
user_Login();
}
if(view==sign_Up){
// go to registeration page
finish();
startActivity(new Intent(this,FragmentThree.class));
}
}
}
this is declaration
This is my login method
The following line in your code throws the exception:
sign_Up.setOnClickListener(this);
The problem is, that sign_Up is null!
You set sign_Up with: sign_Up=(TextView)findViewById(R.id.sign_up);
Make sure, that setContentView(R.layout.activity_login); (activity_login) is the right one. If, try to clean and rebuild your project and try again.
Update: It is possible, that sign_up should be a button? If, you make a wrong cast!
Change the TextView in this line:
sign_Up=(TextView)findViewById(R.id.sign_up);
to Button, like this:
sign_Up=(Button)findViewById(R.id.sign_up);

Dagger2 does not generate components in Test

As per the Dagger 2 documentation
I am trying to set up a test environment according to Dagger2's documentation
(Just for context, I have successfully done this in Dagger 1.)
The problem, specifically, is that while Dagger2 correctly generates DaggerRoboDaggerComponent (as used in App.java), it does not generate DaggerTestRoboDaggerComponent (as used in MainActivityTest.java). I have checked the directory structure to make sure it's not hiding in some obscure place, and done the requisite clean, rebuild, Invalidate Caches / Restart, etc.
If someone could please let me know the error of my ways, I'd appreciate it. Thanks in advance.
You can clone the project here
Or, browse thru the project files below:
build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "xx.robodagger"
minSdkVersion 15
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.dagger:dagger:2.10'
annotationProcessor "com.google.dagger:dagger-compiler:2.10"
testCompile 'junit:junit:4.12'
testCompile "org.robolectric:robolectric:3.3.1"
}
App.java
package xx.robodagger;
import android.app.Application;
public class App extends Application {
static RoboDaggerComponent roboDaggerComponent;
static RoboDaggerComponent getComponent() {
return roboDaggerComponent;
}
#Override public void onCreate() {
super.onCreate();
roboDaggerComponent = DaggerRoboDaggerComponent.builder()
.roboDaggerModule(new RoboDaggerModule())
.build();
}
}
Foo.java
package xx.robodagger;
class Foo {
#Override public String toString() {
return "foo";
}
}
MainActivity.java
package xx.robodagger;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import javax.inject.Inject;
public class MainActivity extends AppCompatActivity {
#Inject Foo foo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
App.getComponent().inject(this);
setContentView(R.layout.activity_main);
TextView tv = (TextView)findViewById(R.id.textview);
tv.setText(foo.toString());
}
}
RoboDaggerComponent.java
package xx.robodagger;
import javax.inject.Singleton;
import dagger.Component;
#Singleton
#Component(modules={RoboDaggerModule.class})
interface RoboDaggerComponent {
void inject(MainActivity mainActivity);
}
RoboDaggerModule.java
package xx.robodagger;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
#SuppressWarnings("unused")
#Module
class RoboDaggerModule {
#Provides
#Singleton
Foo providesFoo() { return new Foo(); }
}
And now in the test directory,
FakeFoo.java
package xx.robodagger;
class FakeFoo extends Foo {
#Override public String toString() {
return "bar";
}
}
MainActivityTest.java
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import javax.inject.Inject;
#RunWith(RobolectricTestRunner.class)
#Config(constants = BuildConfig.class)
public class MainActivityTest {
TestRoboDaggerComponent testRoboDaggerComponent;
#Inject Foo foo;
#Before
public void setup() {
testRoboDaggerComponent = DaggerTestRoboDaggerComponent.builder()
.testRoboDaggerModule(new TestRoboDaggerModule())
.build();
testRoboDaggerComponent.inject(this);
}
#Test
public void fooBarTest() {
assert(foo.toString().equals("bar"));
}
}
TestRoboDaggerComponent.java
package xx.robodagger;
import javax.inject.Singleton;
import dagger.Component;
#Singleton
#Component(modules={TestRoboDaggerModule.class})
interface TestRoboDaggerComponent {
void inject(MainActivityTest mainActivityTest);
}
TestRoboDaggerModule.java
package xx.robodagger;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
#SuppressWarnings("unused")
#Module
class TestRoboDaggerModule {
#Provides
#Singleton
Foo providesFoo() { return new FakeFoo(); }
}
Delete TestRoboDaggerComponent.java, it's not needed
Modify App.java to setup the component via a protected method
#Override public void onCreate() {
super.onCreate();
setupComponent();
}
protected void setupComponent() {
roboDaggerComponent = DaggerRoboDaggerComponent.builder()
.roboDaggerModule(new RoboDaggerModule())
.build();
}
Modify TestApp.java to extend App, and override the previously mentioned method with the TestModule
public class TestApp extends App {
#Override
protected void setupComponent() {
roboDaggerComponent = DaggerRoboDaggerComponent.builder()
.roboDaggerModule(new TestRoboDaggerModule())
.build();
}
}
And finally, in the actual test, leverage Robolectric's power to specify the Application module
#RunWith(RobolectricTestRunner.class)
#Config(constants = BuildConfig.class,
application = TestApp.class)
public class MainActivityTest {
private MainActivity mainActivity;
#Before
public void setup() {
mainActivity = Robolectric.setupActivity(MainActivity.class);
}
#Test
public void fooBarTest() {
TextView tv = (TextView)mainActivity.findViewById(R.id.textview);
assert(tv.getText().equals("bar"));
}
}
Notice that there isn't any DI in the actual test proper. The injection of MainActivity takes place as expected, and with the overridden module. If you have a dependency that uses #Injects in the constructor, the solution per Dagger's documentation is not to use injection in the test, but to just call the normal constructor with mocked objects. This all makes sense. I still think the originally reported issue is a bug, but whatever.

Resources