How to create Library Project in Android Studio with Resource [duplicate] - android

This question already has answers here:
Can I make an Android library which contains resource files?
(1 answer)
How to manually include external aar package using Gradle for Android
(26 answers)
Closed 7 years ago.
I am trying to create library project and used library code and resource to my other application, I can successfully get library activity or method which was not using any resource, but getting error when I try to use resource in activity or any method.
Here is my code.
package com.dhl.lib;
import android.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
public class AdditionActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initUI();
}
private void initUI() {
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
linearLayout.setOrientation(LinearLayout.VERTICAL);
final EditText edtFirst = new EditText(this);
edtFirst.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
edtFirst.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
final EditText edtSecond = new EditText(this);
edtFirst.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
edtFirst.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
Button btn = new Button(this);
btn.setLayoutParams(new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
btn.setText("Add");
btn.setBackground(getResources().getDrawable(R.mipmap.ic_launcher));
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(AdditionActivity.this, "==> " + (Integer.parseInt(edtFirst.getText().toString().trim()) + Integer.parseInt(edtSecond.getText().toString().trim())), Toast.LENGTH_SHORT).show();
}
});
linearLayout.addView(edtFirst);
linearLayout.addView(edtSecond);
linearLayout.addView(btn);
setContentView(linearLayout);
}
#Override
public void onClick(View v) {
}
}
Here another class which used resource
package com.dhl.lib;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
public class About {
public static void show(Activity activity, String aboutText,
String okButtonText) {
String versionNumber = "unknown";
Drawable icon = null;
String appName = "unknown";
View about;
TextView tvAbout;
try {
LayoutInflater inflater = activity.getLayoutInflater();
about = inflater.inflate(R.layout.about, null);
tvAbout = (TextView) about.findViewById(R.id.ca_tutortutor_aboutText);
} catch (InflateException e) {
about = tvAbout = new TextView(activity);
}
tvAbout.setText(Html.fromHtml(aboutText));
tvAbout.setMovementMethod(LinkMovementMethod.getInstance());
new AlertDialog.Builder(activity)
.setTitle(appName + " " + versionNumber)
.setIcon(icon)
.setPositiveButton(okButtonText, null)
.setView(about)
.show();
}
}
** XML Resource of About.xml **
<?xml version="1.0" encoding="utf-8"?>
<scrollview xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/ca_tutortutor_aboutView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context="com.dhl.lib.About">
<linearlayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:padding="5dp">
<textview
android:id="#+id/ca_tutortutor_aboutText"
android:layout_width="wrap_content"
android:layout_height="fill_parent"></textview>
</linearlayout>
</scrollview>
** Manifest of Lib Project **
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.dhl.lib">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".AdditionActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
** app build.gradle **
apply plugin: 'com.android.library'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
minSdkVersion 16
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
}
From that lib I can successfully get access of AdditionActivity on my Project but When I try to access About, getting error of java.lang.NoClassDefFoundError: Failed resolution of: Lcom/dhl/lib/R$layout;
Where I made mistake ? I can't found that point.
Here Is my Application app build.gradle which used library project
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "com.addtion.lib"
minSdkVersion 16
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
provided files('libs/addition.jar')
}
** Application Main Activity Class **
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.btn_callAdd);
btn.setText("Call Addition Activity");
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, AdditionActivity.class));
}
});
((Button) findViewById(R.id.btn_callAlert)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
About.show(MainActivity.this, "Hello From Application", "Ok");
}
});
}
}

Related

What steps to take to verify my Android Firebase app is on the cloud

I'm a newbie to the firebase cloud process. I have a commercial a security camera to view my house that I can view on my phone many miles from my home. Getting into IoT, I developed an Android app to turn a porch light on or off. My Android app works with my local internet but now I want to put it into the cloud so I can use it outside of my house internet. To check and see if the app is on the Firebase cloud? I use my security camera several miles away checking to see if OnOff app working on the cloud. As of now it is not working. What am doing wrong?
I installed all the required code to for firebase. Sync works with id 'com.google.gms.google-services' and installed it on my phone.
Here is my code.
build.gradle(app) code
plugins {
id 'com.android.application'
id 'com.google.gms.google-services'
}
android {
compileSdk 31
defaultConfig {
applicationId "com.example.newonoff"
minSdk 23
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
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.4.1'
implementation 'com.google.android.material:material:1.6.0'
implementation 'com.android.volley:volley:1.2.1'
implementation platform('com.google.firebase:firebase-bom:30.0.0')
implementation 'com.google.firebase:firebase-analytics'
implementation 'com.google.firebase:firebase-auth'
implementation 'com.google.firebase:firebase-core:21.0.0'
implementation 'com.google.firebase:firebase-firestore'
implementation 'com.google.firebase:firebase-crashlytics-buildtools:2.8.1'
implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
build.gradle(newOnOff)
buildscript {
repositories {
google()
mavenCentral()
}
dependencies {
classpath "com.android.tools.build:gradle:7.0.4"
classpath 'com.google.gms:google-services:4.3.10'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
google-services.json
{
"project_info": {
"project_number": "582227243238",
"project_id": "newonoff-30307",
"storage_bucket": "newonoff-30307.appspot.com"
},
"client": [
{
"client_info": {
"mobilesdk_app_id": "1:582227243238:android:23cff0bf99b266c6ca0b27",
"android_client_info": {
"package_name": "com.example.newonoff"
}
},
"oauth_client": [
{
"client_id": "582227243238-ue3ucjg31u00jgs6q32679qv6882a2fk.apps.googleusercontent.com",
"client_type": 3
}
],
"api_key": [
{
"current_key": "AIzaSyCV7GpkxkEjDtTTA7Xera5RGG111KyIgrM"
}
],
"services": {
"appinvite_service": {
"other_platform_oauth_client": [
{
"client_id": "582227243238-ue3ucjg31u00jgs6q32679qv6882a2fk.apps.googleusercontent.com",
"client_type": 3
}
]
}
}
}
],
"configuration_version": "1"
}
```
Android Manifest code
```
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.newonoff">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<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.NewOnOff">
<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>
</application>
</manifest>
```
layout
```
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/btn_ledOn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="60dp"
android:layout_marginTop="50dp"
android:layout_marginEnd="32dp"
android:layout_marginBottom="493dp"
android:onClick="buttonClick"
android:text="ON"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/btn_ledOff"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/btn_ledOff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="50dp"
android:layout_marginEnd="36dp"
android:layout_marginBottom="497dp"
android:onClick="buttonClick"
android:text="OFF"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/btn_ledOn"
app:layout_constraintVertical_bias="1.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
```
Main Activity
```
package com.example.newonoff;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
//import com.android.volley.toolbox.HttpRequestTask;
import com.google.firebase.crashlytics.buildtools.reloc.org.apache.http.HttpResponse;
import com.google.firebase.crashlytics.buildtools.reloc.org.apache.http.client.ClientProtocolException;
import com.google.firebase.crashlytics.buildtools.reloc.org.apache.http.client.HttpClient;
import com.google.firebase.crashlytics.buildtools.reloc.org.apache.http.client.methods.HttpGet;
import com.google.firebase.crashlytics.buildtools.reloc.org.apache.http.impl.client.DefaultHttpClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
public class MainActivity extends AppCompatActivity {
final Context context = this;
//private EditText ipAddress;
private Button ledOn;
private Button ledOff;
String ipAddress="192.168.12.243";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//ipAddress = findViewById(R.id.edt_ip);
ledOn = (Button) findViewById(R.id.btn_ledOn);
ledOff = (Button) findViewById(R.id.btn_ledOff);
}
/**
* When the button clicks this method executes
**/
public void buttonClick(View view) {
String ledStatus;
//if (ipAddress.getText().toString().equals(""))
//Toast.makeText(MainActivity.this, "Please enter the ip address...", Toast.LENGTH_SHORT).show();
//else {
if (view == ledOn)
ledStatus = "1";
else
ledStatus = "0";
//Connect to default port number. Ex: http://IpAddress:80
// String serverAdress = ipAddress.getText().toString() + ":" + "80";
String serverAdress = ipAddress + ":" + "80";
HttpRequestTask requestTask = new HttpRequestTask(serverAdress);
requestTask.execute(ledStatus);
}
private class HttpRequestTask extends AsyncTask<String, Void, String> {
private String serverAdress;
private String serverResponse = "";
private AlertDialog dialog;
public HttpRequestTask(String serverAdress) {
this.serverAdress = serverAdress;
dialog = new AlertDialog.Builder(context)
.setTitle("HTTP Response from Ip Address:")
.setCancelable(true)
.create();
}
#Override
protected String doInBackground(String... params) {
dialog.setMessage("Data sent , waiting response from server...");
/*if (!dialog.isShowing())
dialog.show();*/
String val = params[0];
final String url = "http://" + serverAdress + "/led/" + val;
try {
HttpClient client = new DefaultHttpClient();
HttpGet getRequest = new HttpGet();
getRequest.setURI(new URI(url));
HttpResponse response = client.execute(getRequest);
InputStream inputStream = null;
inputStream = response.getEntity().getContent();
BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(inputStream));
serverResponse = bufferedReader.readLine();
inputStream.close();
} catch (URISyntaxException e) {
e.printStackTrace();
serverResponse = e.getMessage();
} catch (ClientProtocolException e) {
e.printStackTrace();
serverResponse = e.getMessage();
} catch (IOException e) {
e.printStackTrace();
serverResponse = e.getMessage();
}
return serverResponse;
}
#Override
protected void onPreExecute() {}
/* dialog.setMessage("Sending data to server, please wait...");
if (!dialog.isShowing())
dialog.show();
}*/
#Override
protected void onPostExecute(String s) {}
/*dialog.setMessage(serverResponse);
if (!dialog.isShowing())
dialog.show();
}*/
}
}
```

ViewBinding is not working in Second Screen[error: cannot find symbol import com.example.demoapp.databinding.DragAndDropBinding]

Basically I have a app with two Screen. ScreenOne and ScreenTwo. In the first Screen, i mean in MainActivity viewBinding is working fine. But on a perticular button click it will redirect to the second screen. Now there is the problem.
the error massage is -
error: cannot find symbol import com.example.demoapp.databinding.DragAndDropBinding;
But in the first Screen It's working fine.
MainActivity[FirstScreen]
//Working Fine
package com.example.demoapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import com.example.demoapp.databinding.ActivityMainBinding;
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
binding.dragOnly.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), DragActivity.class);
v.getContext().startActivity(intent);
}
});
}
}
ActivityMain.xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:orientation="vertical"
android:layout_centerVertical="true">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/dragAndDrop"
android:text="Drag and Drop"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Drag"
android:id="#+id/dragOnly"/>
</LinearLayout>
</RelativeLayout>
and the DragAndDropActivity[Second Screen]
//Showing error for import com.example.demoapp.databinding.DragAndDropBinding;
package com.example.demoapp;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.example.demoapp.databinding.ActivityMainBinding;
import com.example.demoapp.databinding.DragAndDropBinding; //Error
public class DragActivity extends AppCompatActivity {
TextView textView;
DragAndDropBinding binding;
float xPosition, yPosition, xPrevious, yPrevious;
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drag_and_drop);
textView = findViewById(R.id.dragButton);
textView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int point = event.getActionMasked();
switch (point) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_UP:
xPrevious = event.getX();
yPrevious = event.getY();
return true;
case MotionEvent.ACTION_MOVE:
float dx = event.getX() - xPrevious;
float dy = event.getY() - yPrevious;
xPosition += dx;
yPosition += dy;
v.setX(xPosition - v.getWidth());
v.setY(yPosition - v.getHeight());
return true;
default:
return false;
}
}
});
}
}
DragAndDrop.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Drag Me any Where"
android:textSize="25sp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:id="#+id/dragButton"
android:background="#056"
android:padding="8dp"
android:textColor="#FFF"/>
</RelativeLayout>
build.gradle[App]
apply plugin: 'com.android.application'
android {
compileSdkVersion 29
buildToolsVersion "29.0.3"
defaultConfig {
applicationId "com.example.demoapp"
minSdkVersion 23
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'
}
}
viewBinding {
enabled = true
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
Android Studio version 3.6.1 and gradle plugin classpath 'com.android.tools.build:gradle:3.6.1'
I can see that you are actually not using ViewBinding in the second activity. You are just importing it generated class. Proguard obfuscates unused classes at runtime and it is thinking that you are not using your generated view binding class (which is right, you are just importing it.) so use it as you used in the first activity. It will work.

Live ads from Admob is not showing

Yesterday I created an account on Admob and on my app the test ads working well but the live (real) ads not showing. When I added onFaildToLoad event it returns INTERNAL_ERROR. So is there any solutions? and is it important to upload the app on play store to get live ads?
Here is my xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="208dp"
android:text="login" />
<EditText
android:id="#+id/editText"
android:layout_width="297dp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="183dp"
android:ems="10"
android:inputType="textPassword" />
</RelativeLayout>
<com.google.android.gms.ads.AdView
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="#+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"
ads:adSize="BANNER"
ads:adUnitId="ca-app-pub-8140603259324677/7029410922">
</com.google.android.gms.ads.AdView>
</LinearLayout>
and this is my java code:
package com.example.moamen.webbrowser;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import static com.google.android.gms.ads.AdRequest.ERROR_CODE_INTERNAL_ERROR;
import static com.google.android.gms.ads.AdRequest.ERROR_CODE_INVALID_REQUEST;
import static com.google.android.gms.ads.AdRequest.ERROR_CODE_NETWORK_ERROR;
import static com.google.android.gms.ads.AdRequest.ERROR_CODE_NO_FILL;
public class LoginActivity extends AppCompatActivity {
Button mButton;
EditText mEditText;
private AdView mAdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
try {
mAdView.loadAd(adRequest);
} catch (Exception e) {
e.printStackTrace();
}
mEditText = (EditText) findViewById(R.id.editText);
mButton = (Button) findViewById(R.id.button);
final String passA= "facebook";
final String passB = "moa";
// Sample AdMob app ID: ca-app-pub-3940256099942544~3347511713
MobileAds.initialize(this, "ca-app-pub-8140603259324677~4251010820");
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = mEditText.getText().toString().trim();
if (text.equals(passA)){
Intent intent = new Intent(LoginActivity.this,MainActivity.class);
intent.putExtra("website","https://www.facebook.com/");
startActivity(intent);
}else if (text.equals(passB) ){
Intent intent = new Intent(LoginActivity.this,MainActivity.class);
intent.putExtra("website","https://www.google.com/");
startActivity(intent);
}else {
Toast.makeText(LoginActivity.this, "Password is incorrect", Toast.LENGTH_SHORT).show();
}
}
});
mAdView.setAdListener(new AdListener(){
#Override
public void onAdFailedToLoad(int errorCode) {
// Code to be executed when an ad request fails.
if (errorCode == ERROR_CODE_INTERNAL_ERROR){
Toast.makeText(LoginActivity.this,"ERROR_CODE_INTERNAL_ERROR",Toast.LENGTH_SHORT).show();
}else if (errorCode == ERROR_CODE_INVALID_REQUEST){
Toast.makeText(LoginActivity.this,"ERROR_CODE_INVALID_REQUEST",Toast.LENGTH_SHORT).show();
}else if (errorCode == ERROR_CODE_NETWORK_ERROR){
Toast.makeText(LoginActivity.this,"ERROR_CODE_NETWORK_ERROR",Toast.LENGTH_SHORT).show();
}else if (errorCode == ERROR_CODE_NO_FILL){
Toast.makeText(LoginActivity.this,"ERROR_CODE_NO_FILL",Toast.LENGTH_SHORT).show();
}
}
});
}
}
this is my gardle.build file:
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.drshimaa.webbrowser"
minSdkVersion 19
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
//noinspection GradleCompatible
implementation 'com.android.support:appcompat-v7:28.0.0-alpha1'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:design:28.0.0-rc02'
implementation 'com.google.android.gms:play-services-ads:15.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'
}
allprojects {
repositories {
jcenter()
maven {
url "https://maven.google.com"
}
}
}
the error
test ads is working well
If you are getting TestAds then your implementation is correct.
Change your package id and check
If you have recently created an AdUnit, then you have to wait for sometime to let the AdUnits get Activated...

A library is not working on Nougat (API Level 24)

I used compile 'com.sdsmdg.harjot:rotatingtext:1.0.2' in Android app. It is working in Android Marshmallow API 22 and lower versions. To be more precise, It rotates text with Animation. In Android with Api level 22 and lover it is showing text with Animation. But higher versions don`t support. What should I do to be supported in all versions of Android devices. Please Help.
Here is Source Code:
MainActivity.java
package com.example.abdusoli.rotatingtext;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.animation.BounceInterpolator;
import android.widget.Button;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import com.sdsmdg.harjot.rotatingtext.RotatingTextWrapper;
import com.sdsmdg.harjot.rotatingtext.models.Rotatable;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/Raleway-Light.ttf");
Typeface typeface2 = Typeface.createFromAsset(getAssets(), "fonts/Reckoner_Bold.ttf");
RotatingTextWrapper rotatingTextWrapper = (RotatingTextWrapper) findViewById(R.id.custom_switcher);
rotatingTextWrapper.setSize(35);
rotatingTextWrapper.setTypeface(typeface2);
Rotatable rotatable = new Rotatable(Color.parseColor("#FFA036"), 2000, " ", "Word01", "Word02");
rotatable.setSize(35);
rotatable.setAnimationDuration(600);
rotatable.setTypeface(typeface);
rotatable.setInterpolator(new BounceInterpolator());
rotatingTextWrapper.setContent("This is ?", rotatable);
}
}
gradle.build(Module: app)
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
defaultConfig {
applicationId "com.example.abdusoli.rotatingtext"
minSdkVersion 16
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 {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
testImplementation 'junit:junit:4.12'
compile 'com.android.support:design:26.1.0'
compile 'com.android.support:cardview-v7:26.1.+'
compile 'com.flaviofaria:kenburnsview:1.0.7'
compile 'de.hdodenhof:circleimageview:2.1.0'
compile 'com.sdsmdg.harjot:rotatingtext:1.0.2'
}
Currently the library does not support higher versions
Issue has been raised on the repo in github

Android Toolbar return button didn't work after adding productFlavors

Before adding productFlavors in build.gradle(Module:app), the return button in Toolbar works.
But once I added productFlavors into build.gradle(Module:app) for Build >> Generate Signed APK..., the return button become invalid.
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.comp548.note">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme"
tools:ignore="AllowBackup,GoogleAppIndexingWarning">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".NoteEditActivity">
<meta-data android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity"/>
</activity>
</application>
</manifest>
build.gradle(Module:app) after adding productFlavors:
apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildToolsVersion "24.0.1"
defaultConfig {
applicationId "com.comp548.note"
minSdkVersion 19
targetSdkVersion 24
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
free {
applicationId "com.comp548.note.free"
versionName "1.0-free"
}
paid {
applicationId "com.comp548.note.paid"
versionName "1.0-paid"
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.2.0'
compile 'com.android.support:design:24.2.0'
}
toolbar.xml in layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#color/colorPrimary"
app:theme="#style/ThemeOverlay.AppCompat.Dark"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
tools:ignore="Overdraw">
</android.support.v7.widget.Toolbar>
activity_note_edit.xml in layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.comp548.note.NoteEditActivity">
<include layout="#layout/toolbar"
android:id="#+id/note_edit_toolbar" />
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="#dimen/fragment_margin"
android:name="com.comp548.note.NoteEditFragment"
android:id="#+id/fNoteEdit"
android:layout_centerHorizontal="true"
tools:layout="#layout/fragment_note_edit"
android:layout_below="#id/note_edit_toolbar"/>
</RelativeLayout>
MainActivity.java:
package com.comp548.note;
import android.content.Intent;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar)findViewById(R.id.note_list_toolbar);
// Set the Toolbar to act as the ActionBar for this Activity window
setSupportActionBar(toolbar);
if(getSupportActionBar() != null) {
getSupportActionBar().setTitle(R.string.toolbar_title);
}
getSupportActionBar().setIcon(R.drawable.ic_toolbar);
FloatingActionButton fabAdd = (FloatingActionButton)findViewById(R.id.fabAdd);
fabAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, NoteEditActivity.class);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menu_exit:
finish();
break;
}
return super.onOptionsItemSelected(item);
}
}
NoteEditActivity.java:
package com.comp548.note;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
public class NoteEditActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_edit);
Toolbar toolbar = (Toolbar)findViewById(R.id.note_edit_toolbar);
// Set the Toolbar to act as the ActionBar for this Activity window
setSupportActionBar(toolbar);
// Enable return button
if(getSupportActionBar() != null) {
getSupportActionBar().setHomeButtonEnabled(true);
}
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent intent = getIntent();
NoteEntity noteEntity = (NoteEntity) intent.getSerializableExtra("noteEntity");
// Set values for Views in NoteEditFragment
if (noteEntity != null) {
NoteEditFragment noteEditFragment = (NoteEditFragment)getSupportFragmentManager().findFragmentById(R.id.fNoteEdit);
noteEditFragment.setValues(noteEntity);
}
}
}
App screenshots:
After remove the productFlavors from build.gradle(Module:app) the return button works again.
Why the return button on Toolbar didn't work after adding productFlavors.
How to fix it if I still want to add productFlavors?
Okay in your NoteEditActivity add the callback method onOptionsItemSelected(MenuItem item) and do the following:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
onBackPressed();
break;
}
return super.onOptionsItemSelected(item);
}
It should fix your issue, allowing the toolbar back button to execute the action of the back button. Hope this helps.
Reason: You put different applicationId for each flavor.
In manifest you set metadata for parent activity, but during building flavor all packages are automatically moved to package com.comp548.note.free or com.comp548.note.paid. Your metadata points to com.comp548.note.MainActivity though your actual activity is located under com.comp548.note.paid|free.MainActivity.
Solutions:
Create separate manifests for each flavor with metadata points to correct packages.
Handle it at runtime like KudzieChase described.

Categories

Resources