Issue when compiling android application - java

Good evening. I am taking a course in android and having issues compiling the app.
I am currently following this tutorial. I have earlier set up a requestQueue for GET requests.
This is my MainActivity.java file:
package com.ticketapp.emailaddresss.ticketapp;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.facebook.AccessToken;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.HttpMethod;
import com.facebook.login.LoginManager;
import com.facebook.share.model.ShareHashtag;
import com.facebook.share.model.ShareLinkContent;
import com.facebook.share.widget.ShareDialog;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Button button;
TextView textView;
String server_url = "https://www.idg.se/";
RequestQueue requestQueue;
private ShareDialog shareDialog;
private String name, surname, imageUrl;
private String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.bm);
textView = (TextView) findViewById(R.id.txt);
Bundle inBundle = getIntent().getExtras();
name = inBundle.getString("name");
surname = inBundle.getString("surname");
imageUrl = inBundle.getString("imageUrl");
TextView nameView = (TextView) findViewById(R.id.nameAndSurname);
nameView.setText("" + name + " " + surname);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, server_url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
textView.setText(response);
//requestQueue.stop();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
textView.setText("Something went wrong");
error.printStackTrace();
//requestQueue.stop();
}
});
//requestQueue.add(stringRequest);
SingletonRequestQueue.getmInstance(getApplicationContext()).addRequestQueue(stringRequest);
}
});
}
private void share() {
shareDialog = new ShareDialog(this);
List<String> taggedUserIds = new ArrayList<String>();
taggedUserIds.add("{USER_ID}");
taggedUserIds.add("{USER_ID}");
taggedUserIds.add("{USER_ID}");
ShareLinkContent content = new ShareLinkContent.Builder()
.setContentUrl(Uri.parse("http://www.sitepoint.com"))
.setContentTitle("This is a content title")
.setContentDescription("This is a description")
.setShareHashtag(new ShareHashtag.Builder().setHashtag("#sitepoint").build())
.setPeopleIds(taggedUserIds)
.setPlaceId("{PLACE_ID}")
.build();
shareDialog.show(content);
}
private void getPosts() {
new GraphRequest(AccessToken.getCurrentAccessToken(), "/me/posts", null, HttpMethod.GET, new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
Log.e(TAG, response.toString());
}
}).executeAsync();
}
private void logout() {
LoginManager.getInstance().logOut();
Intent login = new Intent(MainActivity.this, LoginActivity.class);
startActivity(login);
finish();
}
//#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.share:
share();
break;
case R.id.getPosts:
getPosts();
break;
case R.id.logout:
logout();
break;
}
}
}
LoginActivity.java
package com.ticketapp.emailaddress.ticketapp;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.MalformedURLException;
import java.net.URL;
public class LoginActivity extends AppCompatActivity {
private CallbackManager callbackManager;
private AccessTokenTracker accessTokenTracker;
private ProfileTracker profileTracker;
private LoginButton loginButton;
private String firstName,lastName, email,birthday,gender;
private URL profilePicture;
private String userId;
private String TAG = "LoginActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// FacebookSdk.sdkInitialize(this);
//FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_login);
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setHeight(100);
loginButton.setTextColor(Color.WHITE);
loginButton.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
loginButton.setCompoundDrawablePadding(0);
loginButton.setReadPermissions("email", "user_birthday","user_posts");
loginButton.registerCallback(callbackManager, callback);
}
FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.e(TAG,object.toString());
Log.e(TAG,response.toString());
try {
userId = object.getString("id");
profilePicture = new URL("https://graph.facebook.com/" + userId + "/picture?width=500&height=500");
if(object.has("first_name"))
firstName = object.getString("first_name");
if(object.has("last_name"))
lastName = object.getString("last_name");
if (object.has("email"))
email = object.getString("email");
if (object.has("birthday"))
birthday = object.getString("birthday");
if (object.has("gender"))
gender = object.getString("gender");
Intent main = new Intent(LoginActivity.this,MainActivity.class);
main.putExtra("name",firstName);
main.putExtra("surname",lastName);
main.putExtra("imageUrl",profilePicture.toString());
startActivity(main);
finish();
} catch (JSONException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
});
//Here we put the requested fields to be returned from the JSONObject
Bundle parameters = new Bundle();
parameters.putString("fields", "id, first_name, last_name, email, birthday, gender");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
e.printStackTrace();
}
};
#Override
protected void onActivityResult(int requestCode, int responseCode, Intent intent) {
super.onActivityResult(requestCode, responseCode, intent);
callbackManager.onActivityResult(requestCode, responseCode, intent);
}
}
SingletonRequestQueue.java
package com.ticketapp.emailaddress.ticketapp;
import android.content.Context;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import java.lang.ref.ReferenceQueue;
/**
* Created by Adde on 2017-09-11.
*/
public class SingletonRequestQueue {
private
static SingletonRequestQueue mInstance;
private RequestQueue requestQueue;
private static Context mCtx;
private SingletonRequestQueue(Context context){
mCtx = context;
requestQueue = getRequestQueue();
}
public RequestQueue getRequestQueue(){
if(requestQueue == null){
requestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
}
return requestQueue;
}
public static synchronized SingletonRequestQueue getmInstance(Context context) {
if(mInstance == null){
mInstance = new SingletonRequestQueue(context);
}
return mInstance;
}
public<T> void addRequestQueue(Request<T> request){
requestQueue.add(request);
}
}
build.gradle (module)
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
buildToolsVersion "26.0.1"
defaultConfig {
applicationId "com.ticketapp.myName.ticketapp"
minSdkVersion 15
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
//FB SDK
compile fileTree(include: ['*.jar'], dir: 'libs')
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:26.+'
// compile 'com.android.support:design:26.0.1'
// compile 'com.android.support:appcompat-v7:26.0.1'
// compile 'com.android.support:multidex:1.0.1'
// Firebase
// Volley
// compile 'com.android.volley:volley:1.0.0'
compile 'com.facebook.android:facebook-android-sdk:[4,5)'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.firebase:firebase-auth:11.2.2'
compile 'com.mcxiaoke.volley:library:1.0.19'
//compile "com.google.android.gms:play-services-location:11.2.2"
testCompile 'junit:junit:4.12'
}
// Add to the bottom of the file
apply plugin: 'com.google.gms.google-services'
build.gradle (app)
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
//FB SDK
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
// Add this line
classpath 'com.google.gms:google-services:3.1.0'
}
}
allprojects {
repositories {
jcenter()
//FB SDK
maven {
url "https://maven.google.com" // Google's Maven repository
}
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
logcat message
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ticketapp.myname.ticketapp, PID: 9650
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.ticketapp.myname.ticketapp/com.ticketapp.myname.ticketapp.MainActivity}: android.view.InflateException: Binary XML file line #14: Binary XML file line #14: Error inflating class com.facebook.login.widget.LoginButton
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: android.view.InflateException: Binary XML file line #14: Binary XML file line #14: Error inflating class com.facebook.login.widget.LoginButton
Caused by: android.view.InflateException: Binary XML file line #14: Error inflating class com.facebook.login.widget.LoginButton
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
at android.view.LayoutInflater.createView(LayoutInflater.java:647)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:790)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.ticketapp.myname.ticketapp.MainActivity.onCreate(MainActivity.java:49)
at android.app.Activity.performCreate(Activity.java:6975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: The SDK has not been initialized, make sure to call FacebookSdk.sdkInitialize() first.
at com.facebook.internal.Validate.sdkInitialized(Validate.java:145)
at com.facebook.AccessTokenTracker.<init>(AccessTokenTracker.java:55)
at com.facebook.login.widget.LoginButton$2.<init>(LoginButton.java:581)
at com.facebook.login.widget.LoginButton.configureButton(LoginButton.java:581)
at com.facebook.FacebookButtonBase.<init>(FacebookButtonBase.java:64)
at com.facebook.login.widget.LoginButton.<init>(LoginButton.java:210)
at java.lang.reflect.Constructor.newInstance0(Native Method) 
at java.lang.reflect.Constructor.newInstance(Constructor.java:334) 
at android.view.LayoutInflater.createView(LayoutInflater.java:647) 
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:790) 
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730) 
at android.view.LayoutInflater.rInflate(LayoutInflater.java:863) 
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:515) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:423) 
at android.view.LayoutInflater.inflate(LayoutInflater.java:374) 
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:292) 
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140) 
at com.ticketapp.myname.ticketapp.MainActivity.onCreate(MainActivity.java:49) 
at android.app.Activity.performCreate(Activity.java:6975) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6541) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 
Manifest
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<activity
android:name="com.facebook.CustomTabActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="#string/fb_login_protocol_scheme" />
</intent-filter>
</activity>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="Secretokrn" />
<activity
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="#string/app_name"
android:screenOrientation="portrait" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name="com.facebook.FacebookContentProvider"
android:authorities="com.facebook.app.FacebookContentProviderSecretToken"
android:exported="true" />
<activity android:name=".LoginActivity"></activity>
</application>
strings.xml
<resources>
<string name="app_name">TicketApp</string>
<string name="facebook_app_id">SecretToken</string>
<string name="fb_login_protocol_scheme">fbSecretToken</string>
<string name="app_id">$app_id_here</string>
<string name="ShareContent">Share Content</string>
<string name="Posts">Posts</string>
<string name="Logout">Logout</string>
<string name="Hello">Hello</string>
</resources>
I hope I have included enough for a replicating this or solving it without testing.
Updated catlog.
09-12 15:13:21.988 5675-5675/com.ticketapp.myname.ticketapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.ticketapp.myname.ticketapp, PID: 5675
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.ticketapp.myname.ticketapp/com.ticketapp.myname.ticketapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
at com.ticketapp.myname.ticketapp.MainActivity.onCreate(MainActivity.java:76)
at android.app.Activity.performCreate(Activity.java:6975)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6541) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767) 
Ok guys! New update! Apparently there was an issue in the code so I put a try and catch and the application worked. Unfortunately when u log in nothing displays at the moment. This is what I changed in the MainActivity.java
try {
name = inBundle.getString("name");
surname = inBundle.getString("surname");
imageUrl = inBundle.getString("imageUrl");
TextView nameView = (TextView) findViewById(R.id.nameAndSurname);
nameView.setText("" + name + " " + surname);
} catch (Exception e){
Log.e("Error on setContent", e.getMessage());
}

In your MainActivity, you have this:
Bundle inBundle = getIntent().getExtras();
name = inBundle.getString("name");
surname = inBundle.getString("surname");
imageUrl = inBundle.getString("imageUrl");
But the first time you load it, inBundle will be null. You should check if it is null before running getString on it:
Bundle inBundle = getIntent().getExtras();
if(inBundle!=null){
name = inBundle.getString("name");
surname = inBundle.getString("surname");
imageUrl = inBundle.getString("imageUrl");
}

Related

Android app. Connecting to firebase and wanting to get data from it app crashes

I'm trying to build an app which fetches data from firebase and displays info in cardholders when searched by word but when I try to open the window where the code is implemented I get the app crashed. Any advice and help will do.
More in detail.
Basically, I created buttons on the first page(MainActivity.java) and made a button to toggle a new window where you can search foods from firebase in real time (datasearch.java).
As soon as I press the button to the search window the app crashes without any error messages.
MainActivity:
package com.example.kursinis;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.ImageView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class MainActivity extends AppCompatActivity {
ImageView logo;
Button mKmi_btn,mDatasearch_btn,mLogdata_btn;
CalendarView mCalendar;
DatabaseReference ref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
logo = findViewById(R.id.logo);
mKmi_btn = findViewById(R.id.kmi_btn);
mDatasearch_btn = findViewById(R.id.datasearch_btn);
mLogdata_btn = findViewById(R.id.logdata_btn);
mCalendar = findViewById(R.id.calendarView3);
mDatasearch_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(),datasearch.class));
}
});
mLogdata_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(),logdata.class));
}
});
mKmi_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(),kmi.class));
}
});
/* Insert calendar clicks for every day to see logged results */
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id==R.id.action_logout) {
logout();
return true;
}
return super.onOptionsItemSelected(item);
}
private void logout() {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getApplicationContext(),login.class));
finish();
}
}
datasearch java
package com.example.kursinis;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.widget.SearchView;
import android.widget.Toast;
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 java.util.ArrayList;
import java.util.Locale;
public class datasearch extends AppCompatActivity {
DatabaseReference ref;
ArrayList<produktas> list;
RecyclerView recyclerView;
SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_datasearch);
ref = FirebaseDatabase.getInstance().getReference().child("https://link_to_ref/");
recyclerView = findViewById(R.id.rec_view);
searchView = findViewById(R.id.search_data);
}
#Override
protected void onStart() {
super.onStart();
if (ref!=null){
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
list = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()){
list.add(ds.getValue(produktas.class));
}
AdapterClass adapterClass = new AdapterClass(list);
recyclerView.setAdapter(adapterClass);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(datasearch.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
if (searchView != null){
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
search(s);
return true;
}
});
}
}
private void search(String str){
ArrayList<produktas> sList = new ArrayList<>();
for (produktas object : list){
if (object.getKalorijos().toLowerCase().contains(str.toLowerCase())){
sList.add(object);
}
if (object.getAngliavandianiai().toLowerCase().contains(str.toLowerCase())){
sList.add(object);
}
if (object.getBaltymai().toLowerCase().contains(str.toLowerCase())){
sList.add(object);
}
if (object.getRiebalai().toLowerCase().contains(str.toLowerCase())){
sList.add(object);
}
}
AdapterClass adapterClass = new AdapterClass(sList);
recyclerView.setAdapter(adapterClass);
}
}
Adapterclass
package com.example.kursinis;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class AdapterClass extends RecyclerView.Adapter<AdapterClass.MyViewHolder>{
ArrayList<produktas> list;
public AdapterClass(ArrayList<produktas> list){
this.list = list;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cardholder,viewGroup,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myViewHolder, int i) {
myViewHolder.id.setText(list.get(i).getMaisto_prod());
myViewHolder.desc1.setText(list.get(i).getKalorijos());
myViewHolder.desc2.setText(list.get(i).getAngliavandianiai());
myViewHolder.desc3.setText(list.get(i).getBaltymai());
myViewHolder.desc4.setText(list.get(i).getRiebalai());
}
#Override
public int getItemCount() {
return list.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView id,desc1,desc2,desc3,desc4;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
id = itemView.findViewById(R.id.prod_name);
desc1 = itemView.findViewById(R.id.prod_desc1);
desc2 = itemView.findViewById(R.id.prod_desc2);
desc3 = itemView.findViewById(R.id.prod_desc3);
desc4 = itemView.findViewById(R.id.prod_desc4);
}
}
}
product.java
package com.example.kursinis;
public class produktas {
private String angliavandianiai;
private String baltymai;
private String kalorijos;
private String maisto_prod;
private String riebalai;
public produktas(String angliavandianiai, String baltymai, String kalorijos, String maisto_prod, String riebalai) {
this.angliavandianiai = angliavandianiai;
this.baltymai = baltymai;
this.kalorijos = kalorijos;
this.maisto_prod = maisto_prod;
this.riebalai = riebalai;
}
public String getAngliavandianiai() {
return angliavandianiai;
}
public void setAngliavandianiai(String angliavandianiai) {
this.angliavandianiai = angliavandianiai;
}
public String getBaltymai() {
return baltymai;
}
public void setBaltymai(String baltymai) {
this.baltymai = baltymai;
}
public String getKalorijos() {
return kalorijos;
}
public void setKalorijos(String kalorijos) {
this.kalorijos = kalorijos;
}
public String getMaisto_prod() {
return maisto_prod;
}
public void setMaisto_prod(String maisto_prod) {
this.maisto_prod = maisto_prod;
}
public String getRiebalai() {
return riebalai;
}
public void setRiebalai(String riebalai) {
this.riebalai = riebalai;
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.kursinis">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.Kursinis">
<activity
android:name=".calendar"
android:exported="false" />
<activity
android:name=".kmi"
android:exported="false" />
<activity
android:name=".logdata"
android:exported="false" />
<activity
android:name=".datasearch"
android:exported="false" />
<activity
android:name=".login"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".registration"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Gradel
plugins {
id 'com.android.application'
id 'com.google.gms.google-services'
}
android {
compileSdk 31
defaultConfig {
applicationId "com.example.kursinis"
minSdk 26
targetSdk 31
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
buildFeatures {
viewBinding true
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.6.1'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'androidx.navigation:navigation-fragment:2.4.2'
implementation 'androidx.navigation:navigation-ui:2.4.2'
implementation 'com.google.firebase:firebase-database:20.0.5'
implementation 'com.google.firebase:firebase-firestore:24.1.2'
implementation 'com.google.firebase:firebase-auth:21.0.5'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation platform('com.google.firebase:firebase-bom:30.1.0')
implementation 'com.google.firebase:firebase-analytics'
implementation 'com.google.firebase:firebase-core:21.0.0'
}
As well I don't get any error upon app crash, but the only thing I found in Database Inspector that the google_app_measurement_local.db (closed).
Any help and answers are welcome and I will be very thankful.
EDITED:
I changed the ref link in datasearch.java to a name which I created "food" from firebase realtime database, but the only thing that got fixed it that now the window opens up with the search bar but when I try to enter at least one letter it crashes again.
EDITED added logcat
2022-06-19 22:11:45.729 2067-2072/com.example.kursinis I/zygote: After code cache collection, code=469KB, data=239KB
2022-06-19 22:11:45.767 2067-2067/com.example.kursinis E/RecyclerView: No adapter attached; skipping layout
2022-06-19 22:11:45.807 2067-2124/com.example.kursinis D/EGL_emulation: eglMakeCurrent: 0xa10061a0: ver 2 0 (tinfo 0xa10032f0)
2022-06-19 22:11:45.845 2067-2124/com.example.kursinis I/chatty: uid=10089(u0_a89) RenderThread identical 1 line
2022-06-19 22:11:45.857 2067-2124/com.example.kursinis D/EGL_emulation: eglMakeCurrent: 0xa10061a0: ver 2 0 (tinfo 0xa10032f0)
2022-06-19 22:11:45.906 2067-2124/com.example.kursinis D/OpenGLRenderer: endAllActiveAnimators on 0x84068c80 (RippleDrawable) with handle 0xa10030d0
2022-06-19 22:11:46.456 2067-2165/com.example.kursinis W/PersistentConnection: pc_0 - Firebase Database connection was forcefully killed by the server. Will not attempt reconnect. Reason: Database lives in a different region. Please change your database URL to https://kursinis-kcal......
2022-06-19 22:11:50.760 2067-2103/com.example.kursinis V/FA: Inactivity, disconnecting from the service
2022-06-19 22:11:50.991 2067-2067/com.example.kursinis W/View: dispatchProvideAutofillStructure(): not laid out, ignoring
2022-06-19 22:11:50.993 2067-2067/com.example.kursinis W/View: dispatchProvideAutofillStructure(): not laid out, ignoring
2022-06-19 22:11:50.997 2067-2067/com.example.kursinis I/AssistStructure: Flattened final assist data: 2208 bytes, containing 1 windows, 9 views
2022-06-19 22:11:50.997 2067-2072/com.example.kursinis I/zygote: Do partial code cache collection, code=478KB, data=260KB
2022-06-19 22:11:50.998 2067-2072/com.example.kursinis I/zygote: After code cache collection, code=478KB, data=260KB
2022-06-19 22:11:50.998 2067-2072/com.example.kursinis I/zygote: Increasing code cache capacity to 2MB
2022-06-19 22:11:51.252 2067-2067/com.example.kursinis E/RecyclerView: No adapter attached; skipping layout
2022-06-19 22:11:51.467 2067-2067/com.example.kursinis E/InputEventSender: Exception dispatching finished signal.
2022-06-19 22:11:51.467 2067-2067/com.example.kursinis E/MessageQueue-JNI: Exception in MessageQueue callback: handleReceiveCallback
2022-06-19 22:11:51.469 2067-2067/com.example.kursinis E/MessageQueue-JNI: java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.Iterator java.util.ArrayList.iterator()' on a null object reference
at com.example.kursinis.datasearch.search(datasearch.java:79)
at com.example.kursinis.datasearch.access$000(datasearch.java:20)
at com.example.kursinis.datasearch$2.onQueryTextChange(datasearch.java:71)
at android.widget.SearchView.onTextChanged(SearchView.java:1250)
at android.widget.SearchView.-wrap9(Unknown Source:0)
at android.widget.SearchView$8.onTextChanged(SearchView.java:1776)
at android.widget.TextView.sendOnTextChanged(TextView.java:9359)
at android.widget.TextView.handleTextChanged(TextView.java:9446)
at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:11904)
at android.text.SpannableStringBuilder.sendTextChanged(SpannableStringBuilder.java:1252)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:573)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:504)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:502)
at android.text.method.QwertyKeyListener.onKeyDown(QwertyKeyListener.java:228)
at android.text.method.TextKeyListener.onKeyDown(TextKeyListener.java:141)
at android.widget.TextView.doKeyDown(TextView.java:7316)
at android.widget.TextView.onKeyDown(TextView.java:7093)
at android.widget.AutoCompleteTextView.onKeyDown(AutoCompleteTextView.java:831)
at android.view.KeyEvent.dispatch(KeyEvent.java:2688)
at android.view.View.dispatchKeyEvent(View.java:11662)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at com.android.internal.policy.DecorView.superDispatchKeyEvent(DecorView.java:437)
at com.android.internal.policy.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1818)
at androidx.core.view.KeyEventDispatcher.activitySuperDispatchKeyEventPre28(KeyEventDispatcher.java:130)
at androidx.core.view.KeyEventDispatcher.dispatchKeyEvent(KeyEventDispatcher.java:87)
at androidx.core.app.ComponentActivity.dispatchKeyEvent(ComponentActivity.java:140)
at androidx.appcompat.app.AppCompatActivity.dispatchKeyEvent(AppCompatActivity.java:569)
at androidx.appcompat.view.WindowCallbackWrapper.dispatchKeyEvent(WindowCallbackWrapper.java:59)
at androidx.appcompat.app.AppCompatDelegateImpl$AppCompatWindowCallback.dispatchKeyEvent(AppCompatDelegateImpl.java:3054)
at com.android.internal.policy.DecorView.dispatchKeyEvent(DecorView.java:351)
at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:4714)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4586)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4128)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4181)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4147)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4274)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4155)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4331)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4128)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4181)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4147)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4155)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4128)
at android.
2022-06-19 22:11:51.469 2067-2067/com.example.kursinis D/AndroidRuntime: Shutting down VM
2022-06-19 22:11:51.471 2067-2067/com.example.kursinis E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.kursinis, PID: 2067
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.Iterator java.util.ArrayList.iterator()' on a null object reference
at com.example.kursinis.datasearch.search(datasearch.java:79)
at com.example.kursinis.datasearch.access$000(datasearch.java:20)
at com.example.kursinis.datasearch$2.onQueryTextChange(datasearch.java:71)
at android.widget.SearchView.onTextChanged(SearchView.java:1250)
at android.widget.SearchView.-wrap9(Unknown Source:0)
at android.widget.SearchView$8.onTextChanged(SearchView.java:1776)
at android.widget.TextView.sendOnTextChanged(TextView.java:9359)
at android.widget.TextView.handleTextChanged(TextView.java:9446)
at android.widget.TextView$ChangeWatcher.onTextChanged(TextView.java:11904)
at android.text.SpannableStringBuilder.sendTextChanged(SpannableStringBuilder.java:1252)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:573)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:504)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:502)
at android.text.method.QwertyKeyListener.onKeyDown(QwertyKeyListener.java:228)
at android.text.method.TextKeyListener.onKeyDown(TextKeyListener.java:141)
at android.widget.TextView.doKeyDown(TextView.java:7316)
at android.widget.TextView.onKeyDown(TextView.java:7093)
at android.widget.AutoCompleteTextView.onKeyDown(AutoCompleteTextView.java:831)
at android.view.KeyEvent.dispatch(KeyEvent.java:2688)
at android.view.View.dispatchKeyEvent(View.java:11662)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1827)
at com.android.internal.policy.DecorView.superDispatchKeyEvent(DecorView.java:437)
at com.android.internal.policy.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1818)
at androidx.core.view.KeyEventDispatcher.activitySuperDispatchKeyEventPre28(KeyEventDispatcher.java:130)
at androidx.core.view.KeyEventDispatcher.dispatchKeyEvent(KeyEventDispatcher.java:87)
at androidx.core.app.ComponentActivity.dispatchKeyEvent(ComponentActivity.java:140)
at androidx.appcompat.app.AppCompatActivity.dispatchKeyEvent(AppCompatActivity.java:569)
at androidx.appcompat.view.WindowCallbackWrapper.dispatchKeyEvent(WindowCallbackWrapper.java:59)
at androidx.appcompat.app.AppCompatDelegateImpl$AppCompatWindowCallback.dispatchKeyEvent(AppCompatDelegateImpl.java:3054)
at com.android.internal.policy.DecorView.dispatchKeyEvent(DecorView.java:351)
at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:4714)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4586)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4128)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4181)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4147)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4274)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4155)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4331)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4128)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4181)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4147)
2022-06-19 22:11:51.471 2067-2067/com.example.kursinis E/AndroidRuntime: at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4155)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4128)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4181)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4147)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4307)
at android.view.ViewRootImpl$ImeInputStage.onFinishedInputEvent(ViewRootImpl.java:4468)
at android.view.inputmethod.InputMethodManager$PendingEvent.run(InputMethodManager.java:2435)
at android.view.inputmethod.InputMethodManager.invokeFinishedInputEventCallback(InputMethodManager.java:1998)
at android.view.inputmethod.InputMethodManager.finishedInputEvent(InputMethodManager.java:1989)
at android.view.inputmethod.InputMethodManager$ImeInputEventSender.onInputEventFinished(InputMethodManager.java:2412)
at android.view.InputEventSender.dispatchInputEventFinished(InputEventSender.java:141)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:325)
at android.os.Looper.loop(Looper.java:142)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
At your search function, the value list is null. To solve this problem, you need to check if the list is null or not.
private void search(String str){
ArrayList<produktas> sList = new ArrayList<>();
//At here you need to check list is null or not and if got any list or not.
if (list != null && list.size() > 0) {
for (produktas object : list){
if (object.getKalorijos().toLowerCase().contains(str.toLowerCase())){
sList.add(object);
}
if (object.getAngliavandianiai().toLowerCase().contains(str.toLowerCase())){
sList.add(object);
}
if (object.getBaltymai().toLowerCase().contains(str.toLowerCase())){
sList.add(object);
}
if (object.getRiebalai().toLowerCase().contains(str.toLowerCase())){
sList.add(object);
}
}
dapterClass adapterClass = new AdapterClass(sList);
recyclerView.setAdapter(adapterClass);
}
}

cannot find implementation for com.example.roomwordssample.WordRoomDatabase. WordRoomDatabase_Impl does not exist

I'm following this tutorial from CodeLab Google https://codelabs.developers.google.com/codelabs/android-training-livedata-viewmodel/index.html?index=..%2F..android-training
However, after following all the details, at the end I got this error:
2019-10-04 07:05:11.310 10476-10476/com.example.roomwordssample E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.roomwordssample, PID: 10476
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.roomwordssample/com.example.roomwordssample.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.example.roomwordssample.WordViewModel
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2946)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3081)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1831)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Caused by: java.lang.RuntimeException: Cannot create an instance of class com.example.roomwordssample.WordViewModel
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:208)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:135)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:103)
at com.example.roomwordssample.MainActivity.onCreate(MainActivity.java:36)
at android.app.Activity.performCreate(Activity.java:7224)
at android.app.Activity.performCreate(Activity.java:7213)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2926)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3081) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1831) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:201) 
at android.app.ActivityThread.main(ActivityThread.java:6810) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873) 
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:200)
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:135) 
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:103) 
at com.example.roomwordssample.MainActivity.onCreate(MainActivity.java:36) 
at android.app.Activity.performCreate(Activity.java:7224) 
at android.app.Activity.performCreate(Activity.java:7213) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2926) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3081) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1831) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:201) 
at android.app.ActivityThread.main(ActivityThread.java:6810) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873) 
Caused by: java.lang.RuntimeException: cannot find implementation for com.example.roomwordssample.WordRoomDatabase. WordRoomDatabase_Impl does not exist
at androidx.room.Room.getGeneratedImplementation(Room.java:94)
at androidx.room.RoomDatabase$Builder.build(RoomDatabase.java:667)
at com.example.roomwordssample.WordRoomDatabase.getDatabase(WordRoomDatabase.java:26)
at com.example.roomwordssample.WordRepository.<init>(WordRepository.java:14)
at com.example.roomwordssample.WordViewModel.<init>(WordViewModel.java:16)
at java.lang.reflect.Constructor.newInstance0(Native Method) 
at java.lang.reflect.Constructor.newInstance(Constructor.java:343) 
at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.java:200) 
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:135) 
at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:103) 
at com.example.roomwordssample.MainActivity.onCreate(MainActivity.java:36) 
at android.app.Activity.performCreate(Activity.java:7224) 
at android.app.Activity.performCreate(Activity.java:7213) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2926) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3081) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1831) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:201) 
at android.app.ActivityThread.main(ActivityThread.java:6810) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873) 
I've tried to look for solutions from these links:
https://stackoverflow.com/questions/49224539/roomdatabase-impl-does-not-exist
https://stackoverflow.com/questions/47274677/room-cannot-find-implementation?noredirect=1&lq=1
https://stackoverflow.com/questions/55679940/database-impl-doesnt-exist-android-app-with-room
https://stackoverflow.com/questions/50453822/room-cannot-find-implementation-db-db-impl-does-not-exist
But none is working because I'm using Java not Kotlin. Many of the solutions above suggested change the annotationProcessor to kapt then add apply plugin: 'kotlin-kapt' but it'll only give another error
build.grade (Module:app)
apply plugin: 'com.android.application'
android {
compileSdkVersion 29
buildToolsVersion "29.0.2"
defaultConfig {
applicationId "com.example.roomwordssample"
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.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.android.material:material:1.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
implementation 'androidx.room:room-runtime:2.0.0'
annotationProcessor 'androidx.room:room-compiler:2.0.0'
androidTestImplementation 'androidx.room:room-testing:2.0.0'
implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0'
annotationProcessor 'androidx.lifecycle:lifecycle-compiler:2.0.0'
}
WordRoomDatabase.java
package com.example.roomwordssample;
import android.content.Context;
import android.os.AsyncTask;
import androidx.annotation.NonNull;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.sqlite.db.SupportSQLiteDatabase;
public abstract class WordRoomDatabase extends RoomDatabase {
public abstract WordDao wordDao();
private static WordRoomDatabase INSTANCE;
static WordRoomDatabase getDatabase(final Context context) {
if (INSTANCE == null) {
synchronized (WordRoomDatabase.class) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
WordRoomDatabase.class, "word_database")
// Wipes and rebuilds instead of migrating
// if no Migration object.
// Migration is not part of this practical.
.fallbackToDestructiveMigration()
.addCallback(sRoomDatabaseCallback)
.build();
}
}
}
return INSTANCE;
}
private static RoomDatabase.Callback sRoomDatabaseCallback = new RoomDatabase.Callback(){
#Override
public void onOpen (#NonNull SupportSQLiteDatabase db){
super.onOpen(db);
new PopulateDbAsync(INSTANCE).execute();
}
};
private static class PopulateDbAsync extends AsyncTask<Void, Void, Void> {
private final WordDao mDao;
String[] words = {"dolphin", "crocodile", "cobra"};
PopulateDbAsync(WordRoomDatabase db) {
mDao = db.wordDao();
}
#Override
protected Void doInBackground(final Void... params) {
// Start the app with a clean database every time.
// Not needed if you only populate the database
// when it is first created
mDao.deleteAll();
for (int i = 0; i <= words.length - 1; i++) {
Word word = new Word(words[i]);
mDao.insert(word);
}
return null;
}
}
}
WordViewModel.java
import android.app.Application;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import java.util.List;
public class WordViewModel extends AndroidViewModel {
private WordRepository mRepository;
private LiveData<List<Word>> mAllWords;
public WordViewModel (Application application) {
super(application);
mRepository = new WordRepository(application);
mAllWords = mRepository.getAllWords();
}
LiveData<List<Word>> getAllWords() { return mAllWords; }
public void insert(Word word) { mRepository.insert(word); }
}
MainActivity.java
package com.example.roomwordssample;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private WordViewModel mWordViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
RecyclerView recyclerView = findViewById(R.id.recyclerview);
final WordListAdapter adapter = new WordListAdapter(this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mWordViewModel = ViewModelProviders.of(this).get(WordViewModel.class);
mWordViewModel.getAllWords().observe(this, new Observer<List<Word>>() {
#Override
public void onChanged(#Nullable final List<Word> words) {
// Update the cached copy of the words in the adapter.
adapter.setWords(words);
}
});
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I missed the #Database annotation right before the abstract class WordRoomDatabase. After adding #Database(entities = {Word.class}, version = 1, exportSchema = false), everything works fine.
In my case, annotations were fine but I had issue with Gradle dependencies. So make sure that you have at lease these too:
implementation "androidx.room:room-ktx:$rootProject.roomVersion"
kapt "androidx.room:room-compiler:$rootProject.roomVersion"
And also you should have id 'kotlin-kapt' in your plugins brackets.

my app does not have any errors when it builds, however, it stops working when I run it on my phone

my app does not have any errors when it builds, however, it stops working when I run it on my phone, and when I open the app it stopped working and then I decided to run it in the debug and see the errors that have in it through logcat
My build.gradle
apply plugin: 'com.android.application'
android {
configurations.all {exclude group: 'com.android.support', module: 'support-v4'}
compileSdkVersion 28
defaultConfig {
applicationId "tdl.com.dindim"
minSdkVersion 16
targetSdkVersion 28
multiDexEnabled true
versionCode 2
versionName "1.1"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
multiDexEnabled true
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
implementation 'com.android.support:design:28.0.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.adefruandta.spinningwheel:spinningwheel:0.1.0'
implementation 'com.google.firebase:firebase-core:10.0.1'
implementation 'com.google.firebase:firebase-database:10.0.1'
implementation 'org.immutables:gson:2.6.1'
implementation 'com.google.android.gms:play-services:10.0.1'
implementation 'com.google.android.gms:play-services-maps:10.0.1'
implementation 'com.google.android.gms:play-services-ads:10.0.1'
implementation 'com.android.support:cardview-v7:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation 'gun0912.ted:tedpermission:2.1.0'
}
apply plugin: 'com.google.gms.google-services'
Logcat error (I just took the words that were in red)
2019-07-19 03:33:43.960 7572-7572/? E/FirebaseInstanceId: binding to the service failed
at android.os.HandlerThread.run(HandlerThread.java:65)
2019-07-19 04:23:16.863 15686-15704/? E/DIAL:SsdpWriter: Error sending M-SEARCH request
java.net.SocketException: Socket is closed
at java.net.DatagramSocket.send(DatagramSocket.java:686)
at com.google.android.music.dial.SsdpWriter.sendSearch(SsdpWriter.java:67)
at com.google.android.music.dial.SsdpScanner.run(SsdpScanner.java:45)
at com.google.android.music.utils.async.TraceableRunnable.runLogged(TraceableRunnable.java:21)
at com.google.android.music.utils.async.LoggedRunnable.run(LoggedRunnable.java:30)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at com.google.android.music.utils.LoggableHandler.dispatchMessage(LoggableHandler.java:74)
at android.os.Looper.loop(Looper.java:164)
at android.os.HandlerThread.run(HandlerThread.java:65)
Debug error (I just took the words that were in red)
E/AndroidRuntime: FATAL EXCEPTION: main
Process: tdl.com.dindim, PID: 11596
java.lang.RuntimeException: Unable to start activity ComponentInfo{tdl.com.dindim/com.gun0912.tedpermission.TedPermissionActivity}: java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2830)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2909)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1606)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6592)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769)
Caused by: java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation
at android.app.Activity.onCreate(Activity.java:991)
at android.support.v4.app.SupportActivity.onCreate(ComponentActivity.java:75)
at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:335)
at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:85)
at com.gun0912.tedpermission.TedPermissionActivity.onCreate(TedPermissionActivity.java:69)
at android.app.Activity.performCreate(Activity.java:6984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1235)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2783)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2909) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1606) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6592) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769) 
E/UncaughtException: java.lang.RuntimeException: Unable to start activity ComponentInfo{tdl.com.dindim/com.gun0912.tedpermission.TedPermissionActivity}: java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2830)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2909)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1606)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6592)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769)
Caused by: java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation
at android.app.Activity.onCreate(Activity.java:991)
at android.support.v4.app.SupportActivity.onCreate(ComponentActivity.java:75)
at android.support.v4.app.FragmentActivity.onCreate(FragmentActivity.java:335)
at android.support.v7.app.AppCompatActivity.onCreate(AppCompatActivity.java:85)
at com.gun0912.tedpermission.TedPermissionActivity.onCreate(TedPermissionActivity.java:69)
at android.app.Activity.performCreate(Activity.java:6984)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1235)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2783)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2909) 
at android.app.ActivityThread.-wrap11(Unknown Source:0) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1606) 
at android.os.Handler.dispatchMessage(Handler.java:105) 
at android.os.Looper.loop(Looper.java:164) 
at android.app.ActivityThread.main(ActivityThread.java:6592) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769) 
E/FirebaseCrash: Unable to parse Json response string to get message: No value for crashes
My MainActivity
package tdl.com.dindim.activities;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import java.util.List;
import tdl.com.dindim.R;
import tdl.com.dindim.managers.SpinManager;
import tdl.com.dindim.managers.WithdrawManager;
import tdl.com.dindim.models.Score;
import tdl.com.dindim.models.Withdraw;
import tdl.com.dindim.utils.ApplicationMode;
import tdl.com.dindim.utils.ConnectionChecker;
import tdl.com.dindim.utils.SharedPreferenceValue;
public class MainActivity extends AppCompatActivity implements WithdrawManager.WithdrawFeedbackListener {
private TextView tvTotalEarn, tvLastWithdraw;
private AdView adView, adView2, adView3;
private InterstitialAd mInterstitialAd;
private WithdrawManager withdrawManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUI();
}
private void initUI() {
tvTotalEarn = findViewById(R.id.tvTotalEarn);
tvLastWithdraw = findViewById(R.id.tvLastWithdraw);
adView = findViewById(R.id.adViewD);
adView2 = findViewById(R.id.adView2D);
adView3 = findViewById(R.id.adView3D);
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId(getString(R.string.dashboard_interstitial_ads));
loadAds();
showInterstitialAdds();
if (ConnectionChecker.isOnline(MainActivity.this)) {
new SpinManager(MainActivity.this, false, new SpinManager.SpinFeedbackListener() {
#Override
public void pointSaveSuccess() {
}
#Override
public void pointSaveFailed() {
}
#Override
public void noLastPointFound() {
tvTotalEarn.setText("My Total Earn Points: 0");
}
#Override
public void userLastScore(Score score) {
tvTotalEarn.setText("My Total Earn Points: " + score.getPoints());
}
#Override
public void updateScoreSuccess() {
}
#Override
public void updateScoreFailed() {
}
#Override
public void noScoreForTodayUpdateScoreOnly(Score score) {
tvTotalEarn.setText("My Total Earn Points: " + score.getPoints());
}
}).getUserLastScore(SharedPreferenceValue.getLoggedinUser(MainActivity.this));
withdrawManager = new WithdrawManager(MainActivity.this, false, this);
withdrawManager.getUserLastWithdraw(SharedPreferenceValue.getLoggedinUser(MainActivity.this));
} else {
Toast.makeText(this, "No internet . try to connect with internet", Toast.LENGTH_SHORT).show();
}
}
private void loadAds() {
// ads:adUnitId="ca-app-pub-4836336224499913/6703144349"></com.google.android.gms.ads.AdView>
//mAdViewTop.setAdUnitId("ca-app-pub-4836336224499913/6703144349");
if (ApplicationMode.devMode) {
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice("35E1AEC74E43C6B3529C4F77AC4CB10F")
.build();
adView.loadAd(adRequest);
} else {
AdRequest adRequest = new AdRequest.Builder()
//.addTestDevice("35E1AEC74E43C6B3529C4F77AC4CB10F")
.build();
adView.loadAd(adRequest);
}
if (ApplicationMode.devMode) {
AdRequest adRequest2 = new AdRequest.Builder()
.addTestDevice("35E1AEC74E43C6B3529C4F77AC4CB10F")
.build();
adView2.loadAd(adRequest2);
} else {
AdRequest adRequest2 = new AdRequest.Builder()
//.addTestDevice("35E1AEC74E43C6B3529C4F77AC4CB10F")
.build();
adView2.loadAd(adRequest2);
}
if (ApplicationMode.devMode) {
AdRequest adRequest3 = new AdRequest.Builder()
.addTestDevice("35E1AEC74E43C6B3529C4F77AC4CB10F")
.build();
adView3.loadAd(adRequest3);
} else {
AdRequest adRequest3 = new AdRequest.Builder()
//.addTestDevice("35E1AEC74E43C6B3529C4F77AC4CB10F")
.build();
adView3.loadAd(adRequest3);
}
}
private void showInterstitialAdds() {
mInterstitialAd.loadAd(new AdRequest.Builder().build());
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
// Load the next interstitial.
//mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
});
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
showAdsFinal();
}
}, 5000);
}
void showAdsFinal() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Log.d("TAG", "The interstitial wasn't loaded yet.");
}
}
#Override
public void withdrawSaveSuccess() {
}
#Override
public void withdrawSaveFailed() {
}
#Override
public void noLastWithdrawFound() {
tvLastWithdraw.setText("My Last Withdraw: 0");
}
#Override
public void userLastWithdraw(Withdraw withdraw) {
tvLastWithdraw.setText("My Last Withdraw: " + withdraw.getWithdrawPoints());
}
#Override
public void withDrawRequests(List<Withdraw> withdrawList) {
}
#Override
public void noRequestsAvailable() {
}
}
are u using Android 8.0?
Try delete android:screenOrientation='portrait' in manifest
In style, <item name="android:windowIsTranslucent">true</item> set True to false
If not work, test with another phone

App stopped after first launch, but no errors

hello, thanks a lot for the time you re according to my issue.
I am trying to run an app in android studio and it builds fine with 0 errors, the app icon is showing on the device(i tried on different devices and emulators btw) but when it launches, it crashes after a few seconds, saying "my app" has stopped. I tried to view the logcat errors and i didnt understand the problem.
here is the logcat error file, and tell me if you need any other information about the problem please.
03-28 19:20:23.382 13915-13921/? E/jdwp: Failed sending reply to debugger: Broken pipe
03-28 19:20:23.532 13915-13929/? E/dalvikvm: Could not find class 'android.app.AppOpsManager', referenced from method com.google.android.gms.internal.zzadf.zzg
03-28 19:20:23.762 13915-13915/? E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
03-28 19:20:23.782 13915-13915/? E/OneSignal: OneSignal AppId format is invalid.
Example: 'b2f7f966-d8cc-11e4-bed1-df8f05be55ba'
java.lang.NumberFormatException: Invalid long: "xxxxxxxx"
at java.lang.Long.invalidLong(Long.java:125)
at java.lang.Long.parse(Long.java:362)
at java.lang.Long.parseLong(Long.java:353)
at java.util.UUID.fromString(UUID.java:201)
at com.onesignal.OSUtils.initializationChecker(OSUtils.java:52)
at com.onesignal.OneSignal.init(OneSignal.java:238)
at com.onesignal.OneSignal.init(OneSignal.java:215)
at com.onesignal.OneSignal.access$000(OneSignal.java:68)
at com.onesignal.OneSignal$Builder.init(OneSignal.java:142)
at com.mp3player.searchonline.MainActivity.onCreate(MainActivity.java:65)
at android.app.Activity.performCreate(Activity.java:5326)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2218)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2309)
at android.app.ActivityThread.access$700(ActivityThread.java:157)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1289)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5317)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
03-28 19:20:27.816 13915-13915/com.usmans.songscloud E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NoClassDefFoundError: android.support.v7.internal.widget.TintManager
at android.support.design.widget.TabLayout$TabView.<init>(TabLayout.java:1041)
at android.support.design.widget.TabLayout.createTabView(TabLayout.java:582)
at android.support.design.widget.TabLayout.addTabView(TabLayout.java:616)
at android.support.design.widget.TabLayout.addTab(TabLayout.java:334)
at android.support.design.widget.TabLayout.addTab(TabLayout.java:309)
at android.support.design.widget.TabLayout.setTabsFromPagerAdapter(TabLayout.java:571)
at android.support.design.widget.TabLayout.setupWithViewPager(TabLayout.java:550)
at com.mp3player.searchonline.MainActivity.setView(MainActivity.java:93)
at com.mp3player.searchonline.MainActivity.onCreate(MainActivity.java:86)
at android.app.Activity.performCreate(Activity.java:5326)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2218)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2309)
at android.app.ActivityThread.access$700(ActivityThread.java:157)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1289)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5317)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mp3player.searchonline" >
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/MyMaterialTheme"
android:name="com.mp3player.searchonline.App" >
<!--This meta-data tag is required to use Google Play Services.-->
<meta-data android:name="com.google.android.gms.version" android:value="#integer/google_play_services_version" />
<activity
android:name="com.google.android.gms.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>
<activity
android:name="com.mp3player.searchonline.MainActivity"
android:label="#string/app_name"
android:windowSoftInputMode="adjustNothing" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.mp3player.searchonline.PlayerActivity"
android:label="#string/app_name"
android:theme="#style/MyDialogTheme" >
</activity>
</application>
</manifest>
MainActivity.java
package com.mp3player.searchonline;
/**
* Created by Usman Jamil on 02/02/2017.
* Usmans.net
* Skype usman.jamil78
* email usmanjamil547#gmail.com
*/
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.CursorAdapter;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.support.design.widget.Snackbar;
import com.onesignal.OneSignal;
import java.util.ArrayList;
import java.util.List;
import android.support.design.widget.CoordinatorLayout;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends AppCompatActivity implements constants {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private CoordinatorLayout coordinatorLayout;
private SearchView mSearchView;
private MenuItem searchMenuItem;
String[] Final_Suggestions=null;
private SimpleCursorAdapter mAdapter;
String SearchText=null;
SongFragment fragment;
ProgressDialog pDialog;
String TabFragmentB;
Boolean Is = false;
FloatingActionButton Sharebutton;
String urs;
SharedPreferences sharedpreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id
.coordinatorLayout);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager) findViewById(R.id.viewpager);
int id = viewPager.getCurrentItem();
OneSignal.startInit(this).init();
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
Sharebutton = (FloatingActionButton) findViewById(R.id.fav);
Sharebutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onshare();
}
});
final String[] from = new String[] {"cityName"};
final int[] to = new int[] {android.R.id.text1};
mAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
null,
from,
to,
CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
Snackbar snackbar = Snackbar .make(coordinatorLayout, getString(R.string.WelcomeMsg), Snackbar.LENGTH_LONG);
SongFragment toy1 = (SongFragment) getSupportFragmentManager().findFragmentByTag(
"android:switcher:" + viewPager.getId() + ":" + 0);
setView();
snackbar.show();
}
public void setView(){
Sharebutton.setVisibility(View.VISIBLE);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new SongFragment(), "Search");
adapter.addFragment(new DownloadFragment(), "Downloaded");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
public Fragment getActiveFragment() {
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
return null;
}
String tag = getSupportFragmentManager().getBackStackEntryAt(getSupportFragmentManager().getBackStackEntryCount() - 1).getName();
return getSupportFragmentManager().findFragmentByTag(tag);
}
#Override
public boolean onKeyDown(int paramInt, KeyEvent paramKeyEvent) {
if ((paramInt == 4) && (paramKeyEvent.getRepeatCount() == 0)) {
onexit();
}
return super.onKeyDown(paramInt, paramKeyEvent);
}
public void onexit() {
AlertDialog.Builder localBuilder = new AlertDialog.Builder(this);
localBuilder.setTitle("Rate Us");
localBuilder
.setMessage(getString(R.string.rating)).setNeutralButton("Rate",
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface paramAnonymousDialogInterface,
int paramAnonymousInt) {
MainActivity.this.ratee(MainActivity.this
.getApplicationContext()
.getPackageName());
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface paramAnonymousDialogInterface,
int paramAnonymousInt) {
paramAnonymousDialogInterface.dismiss();
MainActivity.this.finish();
}
});
localBuilder.show();
}
public void onshare() {
AlertDialog.Builder localBuilder = new AlertDialog.Builder(this);
localBuilder.setTitle("Share");
localBuilder
.setMessage(getString(R.string.share)).setNeutralButton("Share",
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface paramAnonymousDialogInterface,
int paramAnonymousInt) {
MainActivity.this.share(getString(R.string.ShareMsg)+MainActivity.this
.getApplicationContext()
.getPackageName());
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface paramAnonymousDialogInterface,
int paramAnonymousInt) {
paramAnonymousDialogInterface.dismiss();
}
});
localBuilder.show();
}
public void ratee(String paramString) {
try {
Intent localIntent = new Intent("android.intent.action.VIEW");
localIntent
.setData(Uri.parse("market://details?id=" + paramString));
startActivity(localIntent);
return;
} catch (Exception localException) {
}
}
public void share(String paramString) {
try {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT,paramString);
sendIntent.setType("text/plain");
startActivity(sendIntent);
return;
} catch (Exception localException) {
}
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
Build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion '25.0.0'
defaultConfig {
applicationId "com.usmans.songscloud"
minSdkVersion 14
targetSdkVersion 25
versionCode 1
versionName "1.0"
manifestPlaceholders = [onesignal_app_id: "xxxxxxxx-e269-4dfb-8b48-357b707acdae",
// Project number pulled from dashboard, local value is ignored.
onesignal_google_project_number: "108880509xxxx"]
useLibrary 'org.apache.http.legacy'
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
repositories {
maven {
url 'https://dl.bintray.com/ayz4sci/maven/'
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:25.0.0'
compile 'com.android.support:design:22.2.0'
compile 'com.cjj.materialrefeshlayout:library:1.3.0'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.ayz4sci.androidfactory:downloadprogress:1.0.1'
compile 'com.android.support:support-v4:25.0.0'
// Required for OneSignal, even if you have added FCM.
compile 'com.google.android.gms:play-services-gcm:+'
// Required for geotagging
compile 'com.google.android.gms:play-services-location:+'
compile 'com.google.android.gms:play-services-analytics:+'
// play-services-analytics is only needed when using 8.1.0 or older.
// compile 'com.google.android.gms:play-services-analytics:+'
compile 'com.google.android.gms:play-services-ads:10.2.1'
compile 'com.onesignal:OneSignal:3.4.3'
}
Seems like the "app id" you're passing to the OneSignal framework should be of type Long but you're passing an invalid value.
See this error discussion: OneSignal AppId format is invalid

ClassNotFoundException with Parse and Facebook

I am hoping you can help me with a problem I am facing. I am trying to integrate Facebook login to my app using Parse, and I get a ClassNotFoundException error, when I call the method
ParseFacebookUtils.logInWithReadPermissionsInBackground(LoginActivity.this, permissions, new LogInCallback()
The error stack trace:
05-15 10:36:00.749 3936-3936/kstr14.tipper E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: kstr14.tipper, PID: 3936
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:4007)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4002)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NoClassDefFoundError: Failed resolution of: Lcom/parse/ParseTaskUtils;
at com.parse.ParseFacebookUtils.logInWithReadPermissionsInBackground(ParseFacebookUtils.java:173)
at kstr14.tipper.Activities.LoginActivity.facebookLoginPressed(LoginActivity.java:170)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4002)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.ClassNotFoundException: Didn't find class "com.parse.ParseTaskUtils" on path: DexPathList[[zip file "/data/app/kstr14.tipper-1/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
at com.parse.ParseFacebookUtils.logInWithReadPermissionsInBackground(ParseFacebookUtils.java:173)
at kstr14.tipper.Activities.LoginActivity.facebookLoginPressed(LoginActivity.java:170)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4002)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Suppressed: java.lang.ClassNotFoundException: com.parse.ParseTaskUtils
at java.lang.Class.classForName(Native Method)
at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
... 16 more
Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available
I have the following jar files in my lib folder:
Parse-1.9.1.jar
javax.mail.jar
bolts-android-1.2.0.jar
ParseFacebookUtilsV4-1.9.2.jar
I have tried various things with the dependencies part of the build.gradle file, as I suspect this error is due to some library not being included correctly, but none of what I have tried have worked. I've tried different ways of specifying compiling the jar files as well as specifying the jars in different orders.
Currently my build.gradle file looks like this:
apply plugin: 'com.android.application'
android {
compileSdkVersion 21
buildToolsVersion "21.1.2"
defaultConfig {
applicationId "kstr14.tipper"
minSdkVersion 21
targetSdkVersion 21
versionCode 1
versionName "1.0"
}
buildTypes {
debug {
debuggable true
}
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
}
}
repositories {
mavenCentral()
}
dependencies {
compile fileTree(include: ['*.jar'] ,dir: 'libs')
compile files('libs/bolts-android-1.2.0.jar')
compile 'com.parse.bolts:bolts-android:1.2.0'
compile files('libs/Parse-1.9.1.jar')
compile files('libs/ParseFacebookUtilsV4-1.9.2.jar')
compile files('libs/javax.mail.jar')
compile 'com.android.support:appcompat-v7:22.0.0'
compile 'com.facebook.android:facebook-android-sdk:4.0.0'
compile 'com.google.android.gms:play-services:7.0.0'
}
Anyone have any suggestions?
Oh and by the way, when my app crashes due to the error, I press OK, and then the Facebook login screen shows up anyway.. So I suppose the facebook jar is being imported fine, and the problem is within the Parse jars. However, I have been using the Pars jar before I tried to integrate Facebook, and it worked just fine. I imported the bolts jar at the same time I imported the Facebook jar, as I read somewhere that it was necessary, so it might be a problem with the bolts jar?
EDIT: Added code for LoginActivity:
package kstr14.tipper.Activities;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.Toast;
import com.facebook.FacebookSdk;
import com.parse.LogInCallback;
import com.parse.ParseException;
import com.parse.ParseFacebookUtils;
import com.parse.ParseObject;
import com.parse.ParseUser;
import com.parse.SignUpCallback;
import java.util.ArrayList;
import java.util.List;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import kstr14.tipper.Data.Category;
import kstr14.tipper.Data.Group;
import kstr14.tipper.Data.Tip;
import kstr14.tipper.R;
public class LoginActivity extends ActionBarActivity {
// UI elements for default login fragment
private EditText usernameDefaultLogin;
private EditText passwordDefaultLogin;
// UI elements for sign up fragment
private EditText usernameSignup;
private EditText emailSignup;
private EditText passwordSignup;
private EditText reenterPasswordSignup;
#Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
getSupportActionBar().hide();
// initalize facebook
FacebookSdk.sdkInitialize(getApplicationContext());
// Initialize Parse
ParseObject.registerSubclass(Tip.class);
ParseObject.registerSubclass(Category.class);
ParseObject.registerSubclass(Group.class);
ParseObject.registerSubclass(ParseUser.class);
// check cache for current user - if found go directly to MainActivity
ParseUser currentUser = ParseUser.getCurrentUser();
if(currentUser != null) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
// otherwise set fragment to the default login screen
DefaultLoginFragment defaultLoginFragment = new DefaultLoginFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, defaultLoginFragment).commit();
}
// Required for making Facebook login work
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
ParseFacebookUtils.onActivityResult(requestCode, resultCode, data);
}
/**
* Method called when sign up button pressed on the default login fragment
* Switches the default login fragment with a sign up fragment
* #param view
*/
public void defaultSignUpPressed(View view) {
SignUpFragment signUpFragment = new SignUpFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// Replace the default login fragment with the sign up fragment,
// and add the transaction to the back stack so the user can navigate back
fragmentTransaction.replace(R.id.fragment_container, signUpFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
/**
* Method called when login button pressed on the default login fragment
* Attempts to log in the user, if successful goes to MainActivity
* #param view
*/
public void defaultLoginPressed(View view) {
// initialize UI elements for default login fragment
usernameDefaultLogin = (EditText) findViewById(R.id.usernameDefaultLoginFragment);
passwordDefaultLogin = (EditText) findViewById(R.id.passwordDefaultLoginFragment);
// fetch input and attempt login
String username = usernameDefaultLogin.getText().toString();
String password = passwordDefaultLogin.getText().toString();
ParseUser.logInInBackground(username, password, new LogInCallback() {
public void done(ParseUser user, ParseException e) {
if (user != null) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Login failed.", Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Method called when sign up button pressed in sign up fragment
* Attempts to register the user, if successful goes to MainActivity
* #param view
*/
public void signupPressed(View view) {
// UI elements for sign up fragment
usernameSignup = (EditText) findViewById(R.id.usernameSignupFragment);
emailSignup = (EditText) findViewById(R.id.emailSignupFragment);
passwordSignup = (EditText) findViewById(R.id.passwordSignupFragment);
reenterPasswordSignup = (EditText) findViewById(R.id.reenterPasswordSignupFragment);
String username = usernameSignup.getText().toString();
String email = emailSignup.getText().toString();
String password1 = passwordSignup.getText().toString();
String password2 = reenterPasswordSignup.getText().toString();
// validate passwords and email
if(!validatePassword(password1, password2)) {
Toast.makeText(getApplicationContext(), "Passwords do not match, try again.", Toast.LENGTH_SHORT).show();
} else if (!validateEmail(email)) {
Toast.makeText(getApplicationContext(), "Please enter a valid email.", Toast.LENGTH_SHORT).show();
} else {
ParseUser user = new ParseUser();
user.setUsername(username);
user.setPassword(password1);
user.setEmail(email);
user.signUpInBackground(new SignUpCallback() {
public void done(ParseException e) {
if (e == null) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Sign up failed. Please try again.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
public void facebookLoginPressed(View view) {
List<String> permissions = new ArrayList<String>();
permissions.add("public_profile");
ParseFacebookUtils.logInWithReadPermissionsInBackground(LoginActivity.this, permissions, new LogInCallback() {
#Override
public void done(ParseUser user, ParseException err) {
if (user == null) {
Log.d("MyApp", "Uh oh. The user cancelled the Facebook login.");
} else if (user.isNew()) {
Log.d("MyApp", "User signed up and logged in through Facebook!");
} else {
Log.d("MyApp", "User logged in through Facebook!");
}
}
});
}
/**
* Validates that two passwords are equal
* #param password1
* #param password2
* #return
*/
public boolean validatePassword(String password1, String password2) {
if(password1.equals(password2)) return true;
else return false;
}
/**
* Validates the structure of an email address
* #param email
* #return
*/
public boolean validateEmail(String email) {
boolean result = true;
try {
InternetAddress internetAddress = new InternetAddress(email);
internetAddress.validate();
} catch (AddressException e) {
e.printStackTrace();
result = false;
}
return result;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_login, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
I actually just ran into this same problem. Hopefully I can save a lot of headache for anyone searching for this issue. The answer is not to use an older SDK. Actually all you needed to do was be sure that you were using the same version of Parse and ParseFacebookUtils. Look at your gradle file above
compile 'com.parse.bolts:bolts-android:1.2.0'
compile files('libs/Parse-1.9.1.jar')
compile files('libs/ParseFacebookUtilsV4-1.9.2.jar')
You were using Parse-1.9.1 and ParseFacebookUtilsV4-1.9.2. I actually made the same mistake. I pulled the Parse-1.9.1 from another project and downloaded the SDK again to pull the FacebookUtils library out.
After trying a bunch of different things, including upgrading AndroidStudio and gradle, I solved this by using an older version of the Parse libraries. I was using the newest version 1.9.2, and now I am using 1.9.0, and it works! So there must be some bug in the new version..

Categories

Resources